Synchronize commerce stock for product variations

Here's a relatively straightforward way to track stock based on a group:

  Caveat Emptor: This will only work well if you have unique products per product display, if you try to re-use products (same ticket for multiple events) it could wreak havoc on your stock numbers.

Before starting: Download and enable "Rules Data Transforms" and "Conditional Rules"

Create master stock field. Add a field to your Product Display called "master stock" or "open seats" or whatever makes sense for your use case.
Clone rule. Find the rule that decrements stock on the product level, clone it, disable the original. If it is a component, you may need to locate the event rule that calls it and clone/disable that rule as well. Just depends on your setup.
Edit new cloned rule. Inside your newly cloned rule, you are going to add an action that decrements the master stock.
Calculate new Stock number. First, calculate the new stock number by subtracting one from the product's stock field. This will be the new stock number that we will set on the product display, and all of it's children.
Load Product Display. Pull a product display from the line item field commerce_display_path. This can be tricky, which is why I had you install the Rules Data Transforms (link above).

A. Add a condition Entity has field and we're checking that the line item has the field commerce_display_path (this works great with default add-to-cart settings, but may not work if your add-to-cart doesn't track the display node path).

B. Add an action Explode Text under data transforms. You are exploding commerce-line-item:commerce-display-path using the delimited / and calling it "display_path"

C. Add an action Convert data type under the first group called Data. Your target type is integer and the value to convert is display-path:1 (the second value after exploding) and we'll call this product_display_nid

D. Add an action Fetch entity by id. Click the "Switch to data select" button and pull in the newly converted product-display-nid
Set master stock. Set master stock value of product_display by adding an action Set a data value for the product_display's master stock field to your calculated new stock price.
Create inline condition. Next we need to create a conditional to bring in the "field_product" (or whatever field you use for product references). This is why I had you install the Conditional Rules module. (Yes, this could be accomplished with core rules components, but this feels more straightforward.)

A. Click Add Conditional

B. Click Add if and let's make the conditional an Entity has field by loading the product-display node and looking for your product reference field. By default it's called field_product

C. Click Add loop and loop over the product-display:field-product list and call it sibling_product
Set all sibling products stock. Finally, we need to add a Set a data value action to set each sibling_product's stock field to the new value. Note, this will include the product that has been purchased.

There you go! Admittedly, this is a pretty naive solution. If your master stock says "10" then all of your products will be "10" and when one is purchased, they will all say "9." When there is only 1 seat left, there will still be 3 tickets that could be purchased.


drush updb fails with "the 'media_delete_action' plugin does not exist" after 8.4.6 > 8.5.1 update

This is how we were able to solve this problem:

Temporarily install drupal/media_entity_actions:

composer require drupal/media_entity_actions:^1.0
drush en media_entity_actions

Run the database update:

drush updb

This time it will work:

system module :
  Change plugin IDs of actions.
  Clear caches due to schema changes in core.entity.schema.yml.

views module :
  Update dependencies for moved bulk field plugin.
  Add additional settings to the entity link field and convert node_path usage  to entity_link.
  Add placeholder settings to string or numeric filters.
  Fix cache max age for table displays.
  Include views data table provider in views dependencies.

Do you wish to run all pending updates? (y/n): y
Post updating system                                                                                [ok]
Post updating system                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Post updating views                                                                                [ok]
Cache rebuild complete.                                                                                [ok]
Finished performing updates.                                                                                [ok]

Then the module can be uninstalled safely:

drush pm-uninstall media_entity_actions
composer remove drupal/media_entity_actions


What is the value of "Drupal user" in Drush status for?

The value "Drupal user" is the user the Drush command is run as. You can supply a (valid) user name to any Drush command using -u - for example drush status -u admin. Your implicit question, why did the status command suddenly report "anonymous" as the user, I can not answer. You would have examine the code you pulled - maybe something in the settings?


Splitting up content fields into different regions

There is no easy out of the box way to add the content of a node to different regions on the page.    There is multiple ways to tackle this problem.

Non-coding way: Views & Blocks

Create a view

Type: Block
Contextual Filter: Content: Nid

default value: grab from current page

Fields:  Whichever you want
Filter:

Content Type: Seminar

(plus whatever additonal settings you want)

Then go to administrator block page
Move the newly create view block, to the region you want it displayed.   It should only display on the seminar node pages.

Repeat for all regions

Coding Way with theme_preprocess_region():

code would look something like this

MYTHEME_preprocess_region(&$variables) {
  if (isset($node) && ($node->type == 'seminar' )) {
     //add new variable here.
  }
}

This is for Drupal 7 only.   Now its avaiable in your region.tpl.php.


Solved my problem with the following:

function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'tasks') {
    $i = 0;
    foreach($view->result as $value) {
      if($i == 2)
        unset($view->result[$i]);
      $i++;
    }
  }
 }

The code above does not show the 3rd result from the view results. Add logic as you need.


how to create a free shipping coupon code in drupal commerce

Use Commerce Discount and Commerce Coupon.

Create a discount that uses the Free shipping offer.
Set the conditions (if any).
Add a coupon that links to this discount.

Now when the coupon is added to the order and the conditions (if any) are met the shipping method specified in the Free shipping offer will free.


What's the best practice to show a node's fields in different regions?

Not exactly sure why you want to have every single field as a separate block? That's pretty inefficient, if nothing else.

To have one or two additional blocks, you can use an Entity view block provided by ctools module. It will take the current node and display it in a certain view mode. Of course that will be painful to maintain if every field is separate, but I don't really see why you would want to do that?


Getting terms for only one taxonomy from services module

I was working on exactly the same thing the other day, the format is like this:

http://domain.com/endpoint/taxonomy_term?parameters[vid]=2

To explain that a bit further...

If you look at the code in _taxonomy_resource_definition() the index resource defines a few arguments:

page (int)
fields (string)
parameters (array)
pagesize (int)

The way to pass any of those is:

http://domain.com/endpoint/taxonomy_term?arg_name=value

Since parameters is an array you need to format it as if it was an associative array in the URL, so you use (e.g.) parameters[vid]=2.

It will also work for other parameters, e.g. parameters[name]=TermName.


How to bulk delete content of a given type?

Check the Views Bulk Operation module. This allows you to create list for exactly this purpose and gives you some other interesting functions.


View that only shows content that have a certain date?

Filter by the start date with granularity of day.  When you setup the filter, you can specify operator Is equal to and in the Date default field use the keyword now to default to the current date at runtime.


If you don't want to delete the field, you can exclude the field from input:

/admin/config/people/accounts/form-display

and from output:

/admin/config/people/accounts/display


Uncaught PHP Exception: MissingValueContextException

It seems to be related to a new constraint added on releases, as seen on https://www.drupal.org/project/drupal/issues/3113474
As "view mode" is asked, with no default context, some modules like Panels IPE, Panels, MiniLayout may generate problems if you ask to display a single entity field as FieldBlock.
Just apply patch on https://www.drupal.org/files/issues/2020-02-13/3001313--63_0.patch ; for the record :

--- a/core/modules/layout_builder/src/Plugin/Derivative/FieldBlockDeriver.php
+++ b/core/modules/layout_builder/src/Plugin/Derivative/FieldBlockDeriver.php
@@ -124,7 +124,14 @@ public function getDerivativeDefinitions($base_plugin_definition) {
           $context_definition->addConstraint('Bundle', [$bundle]);
           $derivative['context_definitions'] = [
             'entity' => $context_definition,
-            'view_mode' => new ContextDefinition('string'),
+            'view_mode' =>  new ContextDefinition(
+              'string',
+              $this->t('View Mode'),
+              FALSE,
+              FALSE,
+              NULL,
+              'default'
+            ),
           ];


Show a region outside page tpl or check node type to show it

You might also consider using the Context module to define different contexts for the different cases. But as mentioned elsewhere, the simplest and commonest solution would be to use blocks:

Create a block (or blocks) with the content you wish to show conditionally in it.
Assign that block to the region.
Configure the visibility setting for the block so it only displays on pages with the view on it. An empty region is not displayed on other pages, so if no blocks are visible neither is the region.

If there's a lot of mixed content to be displayed in that region you might also use Panels to create a mini-panel which is then effectively a single block with one visibility setting but having various different items within it (which may also be context-sensitive).


Private files aren't blocking direct access to image files

There are three implementations of hook_file_download(), in Drupal:

file_file_download()
image_file_download()
user_file_download()

The first two implementations always check the user has access to the entity to which the file is associated; the third one doesn't check that, but it only checks the directory containing the file is the one used for the user profile's pictures.

function user_file_download($uri) {
  if (strpos(file_uri_target($uri), variable_get('user_picture_path', 'pictures') . '/picture-') === 0) {
    $info = image_get_info($uri);
    return array('Content-Type' => $info['mime_type']);
  }
}

If there isn't any other module implementing hook_file_download(), I would expect the users to be able to access the files through http://example.com/system/files when the URI points to the same directory containing the images used for the user accounts.


Is it possible to filter by taxonomy field?

Absolutely. When creating a new View, be sure to show "Taxonomy Terms" rather than Content. Change "of type" to be Countries.

After that, you should be able to add a Filter for the language field.


Use read-only database user to minimize security risks

You can make make read only tables, except: semaphor, watchdog, cache, cache_[ANOTHERS], sessions, and another tables, depend on installed modules, that can modify tables on guests visiting, login or form submissions, like statistics, flag and so on.
But I strongly DO NOT recommend this, because instead of showing read only site you may show white or errors screen.
Better is use Read only mode module, that make site read only (prevent form submissions and so on).
Another solution - make backup, then restore 1 per day via bash script. Samples.


How To Open The Comment Form In Modal Form

You can use Colorbox Node.

So you should have this link in your node.tpl.php:

print l(t('Review'), 'comment/reply/' . $nid . '?width=600&height=600', array(
          'attributes' => array(
            'class' => array('colorbox-node')
                )));


hook_path_update (and insert and delete) not getting called

sigh I flushed all caches a TON of times and it would never call my hooks. I had to completely disable my module, flush all caches, and then re-enable my module.

Then the system saw my hooks.

sigh


How to enforce role selection on the user's create, so they can edit other certain users?

Look at Auto Assign Role module.
This documentation will help you.


You can use hook init to check for the path and add JavaScript in custom module.

<?php

function yourmodule_init() {
  if (arg(0) == "checkout" && arg(2) == "complete" && is_numeric(arg(1))) {
    drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
    drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
  }
}

?>

OR

You can edit template.php and add below code.

function yourtheme_preprocess_page(&$variables) {
     if (arg(0) == "checkout" && arg(2) == "complete" && is_numeric(arg(1))) {
        drupal_add_js('var google_conversion_id = 1003933475; var google_conversion_language = "en"; var google_conversion_format = "3"; var google_conversion_color = "ffffff"; var google_conversion_label = "IC5cCMXVqwcQo57b3gM"; var google_conversion_value = 0;', 'inline');
        drupal_add_js('http://www.googleadservices.com/pagead/conversion.js', 'external');
      }

}


Change the sorting order used for Book nodes

You should checkout the Book helper module.

  The Book helper module enables additional features from Drupal's menu system to improve the ordering of a book's pages. This module also allows administrators to further customize a book's navigation block.

  Features

  Enhances the book outline manager
  Adds 'enable' checkbox (aka hidden) to the manage book outline page
  Adds an 'Order' tab (node/%/order) to a book's main page
  Adds 'administer own book outlines' permission for ordering books from a book's main page
  Removes the 'Outline' tab from all nodes
  Removes the book fieldset from node edit pages if the content type does not allowed book outlines
  Removes 'add child page' and 'printer-friendly version'
  Removes book navigation
  Customizes visibility of a book's navigation elements
  Automatically 'Create new book' for selected content types
  Includes 'Book (inline) navigation' block that can be easily positioned after a node's content
  Disables new revisions from being created when a book's node title is updated
  Displays a warning when deleting a book page (node/%/delete) that has child pages


How to display field collection items left to right in views grid

Click on Content: MyProducts (within fields).

Then scroll down a bit, until you see MULTIPLE FIELD SETTINGS, click on it to expand it and then uncheck the Display all items in the same row box.


Rendering field groups (not individual fields)

I ended up using hide() on content elements I wanted place independently before print rendering the rest of content. As I have learned the way drupal renders/prints makes this very easy. Example:

<?php hide($content['product:title']); ?>

  <?php print render($content); ?>

  <?php print render($content['product:field_image']); ?>


You should remove function emtr_enable() out of the .install file, and place its code in a more proper hook where the field is meaningful to be created, like for instance hook_node_type_insert() or EntityAPIController-derived class for your entity bundle, etc.  It depends on what one wants to achieve really.


Change front page url by keeping its content

You simple need to configure that in your website settings:

Configuration >> System >> Site information

There you will find the "Front page" panel where you can enter your new front page URL.

Cheers!


How do I get a plaintext list of tags from a multi value entity reference field?

You can get the array of reference entities from node using

  $node->get('field_tags')->referencedEntities();

So the code will look something like below:

// Get the referenced entities
$tags = $node->get('field_tags')->referencedEntities();
// Check if we have output. (Assuming we get an array, You will have to check what your output it.)
if (!empty($tags)) {
  // Go through each entity.
  foreach ($tags as $tag) {
    // Write your Business Logic here to create your Keywords Array.
  }
}
// Use the Keywords Array for further use.

I Hope this helps you.


Using twig|without for a commerce product

You remove the sub-keys below product:

article{{ attributes }}>

      {{ product.field_price_original }}
      {{ product.variation_price }}

      {{ product.field_discount_percentage }}

  {{ product|without('field_price_original', 'variation_price', 'field_discount_percentage') }}


Can i add a Slide show to my website in a block. Is it possible for my Theme

You could do this with the Fields slideshow module https://drupal.org/project/field_slideshow and optionally the Colorbox module.

Create a content type with an image field. Configure it so that you can load infinite images. Set the formatter of the image field as "slideshow". Then create a block with views and display the block in your sidebar.

Here is a good screencast to set it up: http://vimeo.com/26411524


Example of entity-within-entity subform processing

It's not really that hard. You would want to create form elements that use the #tree attribute, to make sure the data for instances of EntityB will be well structured.

In order to make add another functionality you need to:

Keep track of the count in the $form_state.

if (empty($form_state['count'])) {
  $form_state['count'] = 2;
}

Add a button somewhere to add another.

$form['entity_b']['add_another'] = array(
  '#type' => 'submit',
  '#value' => t('Add another'),
  '#limit_validation_errors' => array(),
  '#submit' => array('add_another_submit_handler'),
);

function add_another_submit_handler(&$form, &$form_state) {
  // Add one to our counter and rebuild the form
  $form_state['count'] += 1;
  $form_state['rebuild'] = TRUE;
}

The above will work with no JavaScript. If you want to Ajax-enable it, you need to do some work on the wrapper.

Add a CSS ID that is used from the Ajax callback.

$form['entity_b'] = array(
  '#tree' => TRUE,
  '#attributes' => array('id' => array('add-another')),
  // ...
);

Add the #ajax element.

 // ...
 '#ajax' =>  array(
  'callback' => 'add_another_ajax',
  'wrapper' => 'add-another',
  'effect' => 'fade',
 ),
 // ...

Add the Ajax callback function.

function add_another_ajax($form, &$form_state) {
  return $form['entity_b'];
}


D8: Replacing Contact Form Title With Label

{{ page['#title'] }} seems to work consistently and accesses the form's label.


How to select nodes of a certain type, created by a certain user and which have reference field to a node equal a certain nid?

This code assumes you're using the entityreference module using field name "field_reference":

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition('type', $type);
$query->propertyCondition('uid', $userid);
$query->fieldCondition('field_reference', 'target_id', $referenceid);
$result = $query->execute();

$nodes = array();
if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}


How do I hide the title on a specific node?

You can create a cck field(checkbox/boolean) for that will act as a flag. So you can have a dynamic option if you want to hide the node or not.

Pseudo code:

In template.php

function yourtTheme_process_page(&$variables) {
  if($variables['node']->field_hide_title['und'][0]['value']) {
    $variables['title'] = NULL;
  }
}

Haven't try this code but I think this will work.

EDIT: Added screenshot of a new field

This should be the value of your cck


Access view exposed filter arguments in field view

You have to use object methods (functions) to get and set exposed filter inputs.

E.g.

Use $views->get_input_filter and $views->set_input_filter($filters).  The format for filters is as follows:

$filters = array(
  'identifier' => '[your ident name]',
  'value' => '[your value']
);


Go to your content type and edit the field. You'll find "More settings and values" as a collapsed fieldset (which is how I always missed it at first.)

The first option will be to change the "Date entry options" and how this is displayed.

You can also modify the default start and end dates here, as well.


Your question is actually very generic and can have a big explanation but I will actually pickup a couple of points from the question description and will try to explain.

How is node is rendered?
Node is drupal's "most" core part. Most of the code is written in node.module in "modules/" directory.
https://api.drupal.org/api/drupal/modules%21node%21node.module/7

Drupal uses a theming layer to render the content to the browser. If you want to alter the display of any node, you can check node.tpl.php in the current active theme directory. You can override the HTML of a node using node--[CONTENT_TYPE].tpl.php. For example if you want to change the HTML structure of article content type, you can copy node.tpl.php to node--article.tpl.php and can update the structure.

How to check the view

The easy way
The easiest way is to login using admin and place mouse on the part of page you think rendered using views. You will see a dropdown menue with links like "Edit", "Delete" etc. If it doesn't help, there is a:

Technical way
You can check the css class of the div enclosing the view data. For example if a view's div contains the class "view-front-page", then most likely the views name will be something like "front_page" or "Front Page".

Thirdly, I will recommend that you install devel module. I have never seen any module for developers that is more helpful than devel. It helps your print a lot of debugging information like error stacks etc.

Hope this will help.


User pictures are no longer guaranteed to exist in Drupal 8. It is added by the standard profile, but not added if you use the minimal profile.

$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$file->getFileUri();


How can I call 2 functions in the same custom module?

You need to add 'access arguments' to your call:

$items['disableproject'] = array(
  'title' => 'Second function',
  'page callback' => array('myModule_second_function'),
  'page arguments' => array(1),
  'access arguments' => array('some permission'),
);

Or you can add a custom access callback:

$items['disableproject'] = array(
  'title' => 'Second function',
  'page callback' => array('myModule_second_function'),
  'page arguments' => array(1),
  'access callback' => 'some_access_callback_function',
);


Which hook occurs last before rendering the exposed filter widgets?

You can do what you need by adding a custom property to your form array via form alter:

function yourmodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // get the related view
  $view = $form_state['view'];

  // get the exposed_input and store it into a custom property
  $form['#exposed_input'] = $view->exposed_input;

}

The form array is directly available as a variable in your views-exposed-form.tpl.php, try adding the following to the end of that tpl file:

<?php print_r($form['#exposed_input']); ?>

Hope this helps!


Using images in custom module (not through css)

If you want to access images in the module folder:

preprocess function (assuming page, but can be any other template):

mymodule.module:
function mymodule_preprocess_page(&$variables) {
  global $base_root, $base_path;
  $variables['image1'] = $base_root . $base_path . drupal_get_path('module', 'mymodule') . '/images/' . $image1;
}

twig:

I don't know your logic for multiple images, I guess you have to code a loop for this.

But accessing static images in a module folder is not a cms way to do this, I would put the images into a node. You can make a content type "slider" for this and then access the absolute path of the image field:

twig:

Here you can code a twig loop to access multiple images in the field.


I suggest using file_save_upload() anyway, beacause (as the API docs say):

  The file will be added to the {file_managed} table as a temporary file. Temporary files are periodically cleaned. To make the file a permanent file, assign the status and use file_save() to save the changes.

So you don't need to worry about having the file "managed" by Drupal as long as you don't change the status of the file to FILE_STATUS_PERMANENT.

Otherwise, if you really don't want this default behaviour (and also no hooks to get invoked), just copy the file in your form_submit() using file_unmanaged_copy() (give it uploaded tmp file as source).


Alter user_pass_reset for one time login D7

This is a bit of a SNAFU as user_password_reset doesn't have a hook associated with it. Why that is, I fail to see.

However, you can always use this little trick in hook_user_login to determine when users log in with a reset link by checking the emptiness of the $edit parameter as the only time it will be empty will be when the user didn't submit a form to log in = when they were automatically logged in.

function mymodule_user_login(&$edit, $account){
  if(!$edit){ // only for automatic pwd resets
    // do your thing, redirect to a password change form with drupal_goto or whatever you need.
  }
}

The implementation of forcing the user set a new password is another question altogether. We do it with a modal window that shows a simple custom form, but there are plenty of ways to do it. Unfortunately the easiest one is sending the user to their user edit form like the password reset functionality automatically does, but there's absolutely no reason why you couldn't just do whatever at that point as the user is logged in and good to go.


file_create_url printing different addresses on live and local installations

The following code worked on both the local and live install:

<?php print file_create_url(theme_get_setting('my_setting')); ?>


How to loop through a taxonomy vocabulary to find the top category in a nested tree?

I would recommend using taxonomy_get_parents_all(). If you have a vocabylary that looks like:

Vocabulary

Child 1 (tid=1)

Child 1.1 (tid=3)

Child 2 (tid=2)

Then you can do:

<?php
$parents = taxonomy_get_parents_all(3);
$top_category = array_pop($parents);

Will give you the term for tid 1.


I believe this will do:

!empty(views_get_view_result('your_views_machine_name','your_display_id'));

If you need to pass arguments, you can pass them as individual strings after the display id. See the API documentation. I'm not sure if you can pass exposed filter arguments, though (the above would work fine for contextual filter arguments).


How to avoid writing to database in form submit?

Form validation is called in the the first part af your code not in the submit function. Add another parameter to your form_alter:

$form['#validate'][] = 'nameOfMyModule_functionName_validate';
$form['#submit'][] = "_validate_entry_webform_client_form_submit_handler";

When validation passes, the submit function will be called. if not form_set_error can be called displaying a message like so:

function nameOfMyModule_functionName_validate($form, &$form_state) {
// Check for the color 'blue'.
    if ($form_state['values']['color'] == 'blue') {
    form_set_error('color', 'Sorry, your favorite color is actually yellow.');
    }
}


Theme a view of one content type with node references to another

What you need to do is add a view relationship (in Views 2 and Views 3) that uses your node_reference field to create the relationship. This will make these fields available to your view.

Thats the quick answer, this video explains it better:

http://gotdrupal.com/videos/drupal-views-relationships


There are few standard "Text formats" for a text field. Which one you actually can use depends on your permission settings (for example permission Use the Full HTML text format).

Then you have the settings for each of the text format (admin/config/content/formats), there you can set up what options a specific format has (you can add/remove image/link buttons).

The last thing to know is that order in which text formats are listed in the administrator page is important. It decides which text format is used as a default. A typical problem with ordering of text formats are automatic messages with broken links (result of "Plain text" format having too high priority).


Depending on the kind of rule event which I expect to be "When a new content is created" in your case.

When you choose action of rule as "send email" it allows you to use tokens, as declared by token modules. You will see the node tokens for the field as well, use it and those will get automatically replaced.


How can I defined regions like default admin theme (Seven)?

That functionality doesn't come from a theme, it's provided by the core Dashboard module.

The short answer to your question is: copy what the Dashboard module does. To actually do it will require a fair bit of development.

The regions are defined in dashboard_dashboard_regions(), and are eventually added to the page by dashboard_page_build(). The whole process bypasses the usual workflow of defining regions in the theme file.

I'm guessing it's been done like this so that the Dashboard can be used by any admin theme, not just the Seven theme included with core.


Pathauto gives you the option of defining per taxonomy path patterns.  Just set the value for your blog categories taxonomy to blog/topics/[catpath-raw] and regenerate your aliases.  These settings are controlled in http://example.com/admin/build/path/pathauto


How to change the view mode programmatically?

Altering the view mode in the preprocess function is doing it too late.
The correct way to alter the view module is implementing hook_entity_view_mode_alter(), which is called before the entity content is rendered. For example, in node_view(), that hook is invoked from node_build_content(), which is the first function called from node_view().

  if (!isset($langcode)) {
    $langcode = $GLOBALS['language_content']->language;
  }

  // Populate $node->content with a render() array.
  node_build_content($node, $view_mode, $langcode);


See http://drupal.org/node/790416.  There is a Firefox addon called Poster which you can use or there is one for Chrome called REST Console.


Could not determine database connection parameters. Pass --db-url option when site-install

It appears, i passed one too few parameters to 'drush_invoke_process'. The documentation shows:

function drush_invoke_process($site_alias_record, $command_name, $commandline_args = array(), $commandline_options = array(),....)

In my case, I was not passing in the 'commandline_args' making the 'commandline_options' become 'commandline_args' instead of options including 'db-url'

Here, is the correct one:

$status = drush_invoke_process('@self', 'si', array('standard'), array(
                                                        'db-url' => 'mysql://'.$dbUser.':'.$dbPassword.'@'.$dbHost.':' . $dbPort . '/'.$dbName,
                                                        'account-pass' => $AdminPassword,
                                                   )
                              );

I hope this helps anyone


Right way to update a drupal distribution?

You should try it with drush.

drush dl commerce_kickstart
drush updatedb -y

(I have not tried it for commerce kickstart; I just got the answer on drupal.org.)


Print custom product variation field in order email confirmation

You should be able to get the product from the order which is available in the template.

I think that this will give you the products:

{% for order_item in order_entity.getItems %}
  {{ order_item }}// The product
  {{ order_item.FIELD_NAME.value }}// The field value
{% endfor %}

Otherwise you must add the product in a preprocess function.


How to change color and sidebar menu without using themes

There are 16 different departments so 16 different colors are needed. Create one theme for all of them. In your .css file create 16 classes and in each one set a custom background color. Like this

.dp—i{ background-color:#abcdef !important}

Now using preprocess functions, and based on the department add the css class to the page component. If it is a block use preprocess_block, if it is region use preprocess_region. By checking the department and adding approprite css class to the class array it will work


Views UI affected due to multiple modules

This might happen when you use jQuery Update, I faced the same and solved using CDN providers

Use jQuery CDN Provider in your jQuery Update Settings should solve this issue

Load your settings as yoursite.com/admin/config/development/jquery_update, You will see the option jQuery and jQuery UI CDN with None in the dropdown list.

Choose jQuery and Save Configuration


Consider using the Forena module, it comes with all sorts of reporting features. And all sorts of hooks if you want to use them in your own custom modules.
Here is an excerpt from its Community documentation:

Forena Reports is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

In this specific case: if you know in which Drupal table (or combination of tables) the info is stored that you are looking for (like your which tracks page visit count for taxonomy terms), then it's a matter of putting together an appropriate SQL statement to retrieve those data, and then format it in a nicely looking report (and even chart if you'd want).
Curious to hear if this somehow could work in your case ...
Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.


Change timezone display format in user edit page

You can do it with below code

    function yourcustomodulename_form_alter(&$form, &$form_state, $form_id) {
    if($form_id=='user_profile_form'){
 $form['#after_build'][] = 'yourmodulename_after_build';

    }
    }
function yourmodulename_after_build($form, &$form_state) {
      $options = array();
      foreach(timezone_identifiers_list() as $timezone) {
        //$options[$timezone] sets the value for date_default_timezone select
        //$timezone set the display for select
        $options[$timezone] = $timezone;
      }
      $form['account']['timezone']['timezone']['#options'] = $options;
return $form;
}


Drupal says "There was a problem creating field ZZZ: Table field_data_field_ZZZ already exists"

Problem

It's possible that something else could cause this, but it doesn't seem too likely.

The problem comes from using backup_migrate to recover or overwrite your database when there is some degree of disparity in the fields in the different databases.  Here's one example of how things can get out of sync:

I start by building out a complex set of content types on my local machine.
I copy the database over to a staging site periodically so I have a stable copy and so other people can do other things.
I forget that I added some fields on my localhost.
I use backup_migrate to grab the latest copy of the database.  (This is where things start to go wrong - it could happen without a dev/staging scenario too, if, for example, you roll-back to an earlier backup of your own database.  There are probably many ways things can get out of wack like this.)
I then see that my field is missing - doh.
When I try to recreate the field I get that rotten message.  You tell me it exists, but you won't let me add the rotten field??!?

What's going on

The problem is two-fold:

Backup_migrate doesn't drop all the tables when you restore a database so the field_data_field_zzz and field_revision_field_zzz tables are not removed.
However the field_config table and the field_config_instance tables are completely replaced. This is where Drupal keeps track of the fields that have been created, so now it has no idea that field_zzz ever existed.

The immediate solution:

Take a look at the known fields (the contents of field_config).  Any fields that are not listed there need to be cleared out of the database, if you want to recreate them.  Just drop the field_data.. and field_revision.. tables from the database.  Now you can go about your business as usual.

..and the haunting:

The problem is that fixing this on your local machine does not fix the problem on other instances of your website.  For instance, if you clean things up and push them up to a staging server, that server is not going to delete unused tables either.  Then at some point in the future you'll grab a copy of that database and experience the pain all over again.  You will google the same query, end up at this post again and call me rotten names for giving you a solution that failed.

The definitive solution:

Frankly, understanding the problem is the biggest step.  The second biggest step is to make sure you fix all instances of your site.  So once you have a nice clean version of your site, you'll want to

drop all the tables on your other site(s)
go to install.php and create a blank drupal site
enable backup_migrate
now when you restore your clean db, you won't have all that baggage
repeat on each site (we usually have multiple localhost/dev installs, then a staging and live site)

In reality, there are a lot of reasons this may not be feasible, but now you should know enough to create your own work-around.


How to share Drush code with the community?

If it's a useful Drush command, and one that you could see being used on a daily basis, the I'd suggest heading to the Drush issue queue and posting a feature request.  Then answer the feature request with a patch that adds the command.  Whether to not it's suitable for Drush core will most likely then be discussed and further action will be taken by the maintainers.

Another option as you mentioned, is to create a module form your command and submit it via the standard module submission process.

The last thing I would suggest it hassling the module maintainers on social media channels or e-mail.

Greg Anderson does sometimes frequent this site though, so he might be able to provide a preferred approach :-)


Either:

Build a view, taking a term argument, and returning the tagged nodes. Output it in Panels. This will give you the greatest flexibility.

Or:

Look for a "Term to Node" relationship under "Context" in the relevant variant. There might a suitable relationship to pull in the nodes that way, but you may find it hard to control what the nodes look like.


This is what I use (with Drupal 6 and Boost), most is self explanatory but I added additional comments here and there:

server {
        listen          80;
        server_name     IP.NR example.com www.example.com;  # Multiple hostnames seperated by spaces
        root            /path/to/drupal; # Replace this
        charset         utf-8;
        access_log  /var/log/nginx/example.com.access.log  combined;
        error_log   /var/log/nginx/example.com.error.log;

        index  index.php;

        if ($host ~* (^example.com|www.example2.com)) { # Redirect to www.example.com
                rewrite ^(.*)   http://www.example.com$1 permanent;
        }

    ## 6.x starts
        location / {
                #rewrite ^/(.*)/$ /$1 permanent; # remove trailing slashes - disabled
                try_files $uri @cache;
        }

        location @cache {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page  405 = @drupal;
                add_header  Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header  Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header  X-Header "Boost Citrus 1.9";
                charset         utf-8;
                try_files   /cache/normal/$host${uri}_$args.html /cache/$host${uri}_$args.html @drupal;
        }

        location @drupal {
                ###
                ### now simplified to reduce rewrites
                ###
                rewrite ^/(.*)$  /index.php?q=$1 last;
        }

        location ~*
        (/\..*|settings\.php$|\.(htaccess|engine|inc|info|install|module|profile|pl|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(Entries.*|Repository|Root|Tag|Template))$
        {
                deny all;
        }

        location ~* /files/.*\.php$ {
                return 444;
        }
        location ~* /themes/.*\.php$ {
                return 444;
        }

        location ~ \.php$ {
                try_files $uri @drupal;           #check for existence of php file
                fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
                include /etc/nginx/conf.d/php_fpm; # Includes config for PHP-FPM (see below)
        }

        location ~ \.css$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
            }
                error_page 405 = @uncached;
                #access_log     off;
                expires         max; #if using aggregator
                add_header      X-Header "Boost Citrus 2.1";
            try_files   /cache/perm/$host${uri}_.css /cache/$host${uri}_.css $uri =404;
        }

        location ~ \.js$ {

                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                    return 405;
                }
                error_page 405 = @uncached;
                #access_log  off;
                expires  max; # if using aggregator
                add_header X-Header "Boost Citrus 2.2";
            try_files /cache/perm/$host${uri}_.js /cache/$host${uri}_.js $uri =404;
        }

        location @uncached {
                #access_log  off;
                expires  max; # max if using aggregator, otherwise sane expire time
        }

        location ~* /files/imagecache/ {
                #access_log         off;
                try_files $uri @drupal;  #imagecache support - now it works
        }

        location ~* /files/backup_migrate/ {
                deny all;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
                #access_log  off;
            expires          14d;
            try_files $uri = 404;
        }

        location ~* \.xml$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.4";
                charset utf-8;
                types { }
                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

        location ~* /feed$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.5";
                charset utf-8;
                types { }

                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

#        error_page  404              /index.php;

        # redirect server error pages to the static page /50x.html
        #
#        error_page   500 502 503 504  /50x.html;
#        location = /50x.html {
#            root   html;
#        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}

        location /server-status {
                stub_status on;
                access_log off;

        }

     }

I'm using PHP-FPM (which is included in PHP 5.3 but I'm using 5.2) so I also include this file (...conf.d/php_fpm)

        fastcgi_pass   127.0.0.1:9000;    #php-fpm listening on port 9000
        fastcgi_index  index.php;
        fastcgi_param  QUERY_STRING   $query_string;
        fastcgi_param  REQUEST_METHOD     $request_method;
        fastcgi_param  CONTENT_TYPE   $content_type;
        fastcgi_param  CONTENT_LENGTH     $content_length;

        fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
        fastcgi_param  REQUEST_URI        $request_uri;
        fastcgi_param  DOCUMENT_URI   $document_uri;
        fastcgi_param  DOCUMENT_ROOT      $document_root;
        fastcgi_param  SERVER_PROTOCOL    $server_protocol;

        fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
        fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

        fastcgi_param  REMOTE_ADDR        $remote_addr;
        fastcgi_param  REMOTE_PORT        $remote_port;
        fastcgi_param  SERVER_ADDR        $server_addr;
        fastcgi_param  SERVER_PORT        $server_port;
        fastcgi_param  SERVER_NAME        $server_name;

        # PHP only, required if PHP was built with --enable-force-cgi-redirect
        fastcgi_param  REDIRECT_STATUS    200;

        fastcgi_connect_timeout         60;
        fastcgi_send_timeout            180;
        fastcgi_read_timeout            180;
        fastcgi_buffer_size             128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size   256k;
        fastcgi_temp_file_write_size    256k;
#   fastcgi_intercept_errors        on;

Just ask if you have any questions about specificities.


I believe you are looking for something like this module

  Rules: when Triggers won't do, use the event-condition-action paradigm of Rules. More complicated to set up than Trigger, but very powerful. Revisioning adds its own events and conditions to Rules, for example "content is about to be published" and "content has pending revisions".

and

  Revisioning is integrated with Rules, adding a number of revision-specific conditions and events.


Views issues are tracked in the Core issue queue. The VBO issue might make more sense in the VBO module issue queue, since it might need to be accommodated by the module itself.


Associate one item of content with one taxonomy term

It's possible, but not terribly easy in D6.

In Drupal 6 (unlike 7 and 8) vocabularies were not fieldable, so the approach you took is a reasonable one.  You probably do not need a relationship in the view, just adjust the filter to include content types of the new type, and then use sorting to move the to the start or end of the result set. You could sort by content type or use the usually ignored "sticky" field on the nodes if its not in use (set all your new images to be sticky and then sort the list to place them where you want).

You could also create a block that uses the same filter pattern as the original view, but limit to the new content type and the only 2 results. Then place that block on the page that's displaying the grid.

Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.


Print taxonomy term description onto product page

It depends a lot on how you're showing this page/information, most probably you're using Views lo list these products, so you can add a Relationship from the Product entity to the Taxonomy (from product variation or display, doesn't matter) to show the fields coming from your categories.

If it's in the product page, it might get trickier, I'd use Display Suite to show fields from other entities, Dynamic fields is an option included in DS and alows you to explore more information that is available for display contextually on your current entity view mode.


I think you need try this module: Workflow


adding a grid with specific class in adaptivetheme

AT does not use Grid classes embedded in markup (it does not use grid classes at all).

If you are asking this I assume you do not really understand how this theme works - you use the layout system (in theme settings, for the main container/page and panels layouts) and write content/element specific CSS yourself, aka use a semantic grid approach.

Grid classes in markup are a huge limitation - what seems so easy now, turns quickly into a massive roadblock later on.

answer by author of adaptivetheme http://drupal.org/node/1861948


How would you convert a link to a media item to the file URL in a menu?

I came up with a solution, where you add the link like this: '/media/1234'

And then add this code:

function mymodule_link_alter(&$variables) {
  $url = $variables['url'];

  if (!$url->isRouted() && $uri = $variables['url']->getUri()) {
    preg_match('/base\:media\/(\d+)/', $variables['url']->getUri(), $match);
    if (!empty($match) && !empty($match[1])) {
      $media = \Drupal::entityTypeManager()->getStorage('media')->load($match[1]);
      if (!empty($media) && $media->bundle() === 'document') {
        if ($file = $media->field_media_file->entity) {
          $variables['url'] = Url::fromUri(file_create_url($file->getFileUri()), $url->getOptions());
        }
      }
    }
  }
}

I hardcoded the source field.  You could make it more generic if you like.


How To Force Commerce Cart View To Update (Ajax?)

Implement a custom rules action and wire it to rules event Calculating the sell price of a product. The sell price of a line item can be forced to any value using the action Set the unit price to a specific amount. The missing piece is a custom rule action capable of retrieving the amount. As a starting point I propose the following (assuming the custom module is named acme):

/**
 * Implements hook_rules_action_info().
 */
function acme_rules_action_info() {
  return array(
    'acme_random_amount' => array(
      'label' => t('Generate random price (with params!)'),
      'group' => t('Examples'),
      'parameter' => array(
        'product_id' => array(
          'type' => 'text',
          'label' => t('Product SKU'),
          'description' => t('The SKU of a product.'),
        ),
        'account' => array(
          'type' => 'user',
          'label' => t('User'),
          'description' => t('A user account.'),
        ),
      ),
      'provides' => array(
        'amount' => array(
          'type' => 'decimal',
          'label' => t('Amount'),
          'description' => 'Return a random numeric amount, except for admin.',
        ),
      ),
    ),
  );
}

/**
 * Rules action: Generate and return random amount of money.
 */
function acme_random_amount($product_id, $account) {
  $amount = mt_rand(100, 1000);

  // Fix price for admin.
  if ($account && $account->uid == 1) {
    $amount = 420;
  }

  // Blue sells, let's boost the revenue.
  if (strpos($product_id, 'BLU') !== FALSE) {
    $amount *= 100;
  }

  return array(
    'amount' => $amount,
  );
}

The rule then looks something like this:

{ "rules_pick_random_price" : {
    "LABEL" : "Pick random price",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "acme", "commerce_line_item", "commerce_product_reference" ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "acme_random_amount" : {
          "USING" : {
            "product_id" : [ "commerce-line-item:commerce-product:sku" ],
            "account" : [ "commerce-line-item:order:owner" ]
          },
          "PROVIDE" : { "amount" : { "amount" : "Amount" } }
        }
      },
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : [ "amount" ],
          "component_name" : "base_price",
          "round_mode" : "0"
        }
      },
      { "drupal_message" : { "message" : "Set the price of [commerce-line-item:commerce-product:sku] to amount: [amount:value] for user [commerce-line-item:order:owner:name]" } }
    ]
  }
}

Note that in order to get at the product SKU, it is necessary to introduce a condition Entity has field checking for the presence of the commerce_product field on the commerce-line-item variable.

Please keep in mind that this rule will be executed on every page request for every item in the cart. Additionally it is executed whenever an add-to-cart form is displayed. If this is on a high traffic site, you probably need to think about an appropriate caching strategy.


For the record, if other people have a hard time figuring how the translation in Field Collection works, here's what I found out:

It does not work.

There is an issue here: https://www.drupal.org/node/2618016 that provides a patch to add support, but does not retroactively add translation support to existing field collections. If your site already has field collections you are SOL - and in my case the whole site becomes non-functional.

I'm now looking into migration towards paragraphs, but not sure how to migrate my data. Will update when I have a good solution.


How do I load external JavaScript before local JavaScript?

You can below preprocess function with scope and weight. You would need to set scope as footer and add the variable to html.tpl.php before body tag.

function paddle_theme_preprocess_html(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'paddle_theme') .  '/scripts/footer.sticky.js',
  array(
    'type' => 'file',
    'scope' => 'header',
    'group' => JS_THEME,
    'every_page' => TRUE,
    'preprocess' => FALSE,
  ));
}

Also for Drupal 6, you can check the following reference with Advance JS aggregation or LABjs which can do the parallel loading.

http://www.drupalden.co.uk/move-render-blocking-javascript-bottom-page


How to show directions on a map when using the Geolocation Field module

When you download the Get Directions module, it has a README.txt that explains how to set up the module.  Make sure to:

Make sure both modules are enabled, then configure the Get Directions module at: Administer > Site configuration > Get directions.

Go to Administer > User management > Permissions and set up permissions according to your needs.

Configure up a Geolocation field on a content type, then create a node of that type and fill in the field.  You should then be able to use this URL pattern to see Get Directions module work with that node by going to

  http://{hostname}/getdirections/location/to/{node_id}

or

  http://{hostname}/getdirections/location/from/{node_id}

where {hostname} and {node_id} are filled in with correct values.

Here is the full section on all the options from the README.txt:

  For instance, if you want to "preload" the getdirections form with information
  about the destination use a URL in this format:

  getdirections/location/to/99

  Where '99' is the node id (nid) of the location. The user will only
  have to fill in the starting point.

  To do it the other way around use getdirections/location/from/99

  You can also get a map with waypoints
  getdirections/locations_via/1,2,3,99

  If you have both the starting point and destination node ids then you
  can use getdirections/locations/1/99

  Where '1' is the starting point node id and 99 is the destination node
  id (note the 's' in locations)


How to change the positioning of Drupal blocks when a theme is enabled?

Only using Drupal core

Investigate the 'current theme of the user', to identify the 'region name' where the 'header block' (which contains the main menu) is positioned. Let's say that region is called "HeaderRegion".

Then in your own theme, make sure to create a region with the exact same name (like "HeaderRegion"), and position that region in the area that corresponds with what you describe as "left sidebar".

With this approach, the "main menu" will be shown in both themes in the block that is positioned in the "HeaderRegion"-region. And the actual theme that is selected will determine if it will be shown in the header (if using the current theme) or in the left sidebar (if using your own theme). Note: a "left sidebar" with a region name like "HeaderRegion" will sound a bit confusing, but that's a way to make it work ... (and maybe that region name in your current theme has a less confusing name, so you might be lucky and not suffer that confusion ...).

Using a contributed module

By using the Themekey module, you can implement content, user, or role -specific themes.

So if you can come up with the appropriate set of theme variations (which would differ by the location of your theme regions in which the blocks are displayed), this could be a solution that could work.


Can I extend the image field formatter without defining a custom one?

As an alternative, more flexible way, you could chose to use either File entity or Media entity, both give you a fieldable entity that you can add your additional fields, without having to write a single line of custom code.

File entity makes the files themself fieldable and adds file types, so images can have different fields than videos for example.

Media entity adds a separate entity that you work with, and works well combined with a number of other modules like Entity Browser and Inline Entity Form. There are some good tutorials out there:

http://www.annertech.com/blog/reusable-media-drupal-8-tutorial
http://flocondetoile.fr/blog/managing-media-drupal-8


node_publish_action is not publishing the node

Contrary to this comment on the API documentation, node_save() is required after node_publish_action() is called.

So the submit handler should look like this:

function mymodule_publish_submit($form, &$form_state) {
  $nid = $form['nid']['#value'];
  $node = node_load($nid, $vid = NULL, $reset = FALSE);
  node_publish_action($node, $context = array());
  node_save($node);
}

As pointed out by jimajamma, the previous code contains a hook_action() which allows integration with Actions. The following code does the same thing, but doesn't use the hook_action()

function mymodule_publish_submit($form, &$form_state) {
  $nid = $form['nid']['#value'];
  $node = node_load($nid, $vid = NULL, $reset = FALSE);
  $node->status = 1; // 0 = unpublished, 1 = published. There are no other states
  node_save($node);
}

Pretty simple.


AJAX - How to dynamically add options to select?

You need to build up the correct options directly in your form builder function, not in the ajax callback.

You can for example do so by converting your button to a submit type, add a specific #submit callback function, and then add something to $form_state and trigger a $form rebuild. In your form builder function you can then look into $form_state and build up the $options accordingly.

Logic always needs to be in the form builder/submit callbacks, the only thing that the ajax callback needs to care about is which part(s) of the form need(s) to be returned. The easiest way to correctly implement ajax in most cases is to build the form without ajax (which will just work with the method described above) and then add #ajax on top of it, once it works without.

You also don't need to set $form_state['rebuild'] in your ajax callback that only has an effect in the submit callback.


contact page with some texts, a form & google map

The best way is to use webforms to create your contact form. Make sure to use the option of creating the webform in a block. Create two more blocks. One containing the address and contact and the other containing your map.

And using like panels or a page. arrange your blocks on that page.


What's are the variables can be used from content.field_name with multiple values

{{ content.field_name }} is a renderable array. You are meant to simply print out {{ content.field_name }}.

If you need to change what is actually in the output, then you should create a field--field-name.html.twig or another applicable twig template suggestion name that works for you. Within it, you would have:

{% for item in items %}

{{ item.content }}

{% endfor %}

That way, any time you render either {{ content }} containing this field or {{ content.field_name }} it will use that template and render it consistently.

Here is a real world example. I am working on a project where one of the fields is a select list of about 20 options. These option values correlate to icons in the theme, and they can use this field to attach an icon to a title field for presentation purpose.

Here is my twig file for field--field-icon.html.twig:

{% for item in items %}
  <svg class="icon"><use xlink:href="/themes/custom/mytheme/build/img/svg-sprite.svg#{{ item.content }}"></use></svg>
{% endfor %}

item.content is just my field value, you don't have to do anything special here. So if the editor selects 'Alert', which the select list value is 'alert', item.content will print alert and the proper icon will display from the svg spritesheet.

Here is a similar question I answered which may provide further insight on theming fields.


Views Exposed Filter conflicting with default search

Not sure exactly what you have tried so far, but Can you check if Views: Better Exposed Filters can help you with this ?


How to insert the image field in the menu links

You can try using the module Menu Minipanels. This module will allow you to use views and custom blocks inside the menu.

Or you can customize the menu display as specified here.


Print module doesn't work with Panelizer module. Why?

The Print module uses hook_preprocess_node which is not used with panels_everywhere/panelizer. In a similar issue (with panels everywhere) I  used a patch 565856-panel_support_print-39.patch.

Background discussion and the patch you can find here:
https://www.drupal.org/node/565856

Hope this will help.


How can i access MySQL of a local Acquia Dev website using the command line?

The easiest way to access a CLI database on any site is with drush:

~$ drush help sql-cli
Open a SQL command-line interface using Drupal's credentials.

Examples:
 drush sql-cli                             Open a SQL command-line interface
                                           using Drupal's credentials.
 drush sql-cli --extra=-A                  Open a SQL CLI and skip reading
                                           table information.

Options:
 --database=<key>                          The DB connection key if using
                                           multiple connections in
                                           settings.php.
 --db-url=<mysql://root:pass@127.0.0.1/db  A Drupal 6 style database URL.
 >
 --extra=<--skip-column-names>             Add custom options to the mysql
                                           command.

If you don't give it any options, then it will use the normal drush magic to find the settings for the current site you are in or from the site alias that you are using.

$ cd /path/to/your/drupal/docroot
$ drush sql-cli

TL;DR, if you can drush to your site, you can instantly connect to it with drush sql-cli


Get all user profiles from list of users

Your first problem is that you send uids instead of pids. First argument of profile2_load_multiple is $pids which are profile2 ids.

Try this code:

$users = entity_load('user');
$arrayuids = array_keys($users);

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
    ->propertyCondition('uid', $arrayuids, 'IN');

$profile = $query->execute();

dsm($arrayuids);
dsm($profile);

I haven't tested it but it should work.


ImageBlock Module- Responsive/Fluid images

Figured it out. In order to make a image that is a part of a imageblock, responsive/fluid, you need to:

1.) Use firebug to find the image block class for the imageblock.
2.) For me I added this to CSS

#block-imageblock-### .imageblock-image{
    width:100%;

}

This will make your image that you've uploaded into a ImageBlock responsive/fluid to any screen resolution


How do I create a simple checkbox in a content entity?

Use type boolean_checkbox and display_label:

$fields[$open] = BaseFieldDefinition::create('boolean')
    ->setLabel(t("My Checkbox Field"))
    ->setDisplayOptions('form', array(
      'type' => 'boolean_checkbox',
      'settings' => array(
        'display_label' => TRUE,
      ),
      'weight' => '0',
    ))
    ->setDisplayConfigurable('form', TRUE);


From the EU Cookie Compliance module's project page on drupal.org:

If you want to conditionally set cookies in your module, there is a
JavaScript function provided that returns TRUE if the user has given
their consent:
Drupal.eu_cookie_compliance.hasAgreed()
For example, if you want to disable Google Analytics, you could do the
following: http://drupal.org/node/1648286#comment-6145800
Another example of how it can be used with Google Analytics is
provided by dagomar in this comment.
Here is another example showing how to set cookies after user clicks
the accept button: http://drupal.org/node/1624876#comment-6111688

I've personally used this to prevent third-party code snippets from loading until after compliance is granted, by making a custom module and including the call to hasAgreed() in my module's JavaScript behaviors.
But as the first example above shows, a custom module is not necessary for Google Analytics in particular. You can simply add the following code to the Advanced Settings->Custom JS in Google Analytics:
if (!Drupal.eu_cookie_compliance.hasAgreed()){
window['ga-disable-UA-xxxx-1'] = true;
}

EDIT (2020-02-23):
It seems that you want to enforce extremely strict GDPR compliance, and prevent the cookies from being loaded at all unless consent has been granted.
You can do this with a custom module, leveraging the same hasAgreed() JavaScript behavior provided by the EU Cookie Compilance module.
First you need to remove the code snippet from your site completely and replace it with a placeholder.
If it's just one script in your HTML head, you might just edit html.html.twig.
If there are multiple scripts you need to prevent from running, it will be more work.
In my case, I replaced dozens of different third-party forms with an empty
 element:

My custom JavaScript behavior looks for all the DOM elements with that class:
document.getElementsByClassName('thirdPartyFormWrapper');

The 4-digit number in the div ID corresponds to the unique third-party form ID for each form.
If consent has not been granted (or if the EU Cookie Compliance module is not installed or enabled, and hasAgreed() is not available) then my custom module uses the 4-digit ID to look up substitute content (saying, e.g., "Please accept cookies to view the Yoyodyne, Inc. Gnomovision Mailing List Subscription Form," or whatever that particular form is.)
If consent has been granted, then my custom module uses the 4-digit ID to inject the JavaScript snippet for each of the third-party forms into the placeholder
.
Once the form snippet is injected, you can figure out how to handle the cookies. If consent is withheld, neither snippets nor cookies will load.
You can also use this technique to handle cookies for extremely strict GDPR compliance, following this pattern:
/**
 * Cookie handling for strict GDPR compliance
 */
  Drupal.behaviors.customCookieConsent = {
    attach: function (context, settings) {
      if (!Drupal.eu_cookie_compliance || !Drupal.eu_cookie_compliance.hasAgreed()) {
        // Bail out if cookie consent not given
        return;
      }
      // If cookie consent is given, set cookie (unless already set)
      if (!$.cookie('customConsentTime')){
        var consentTime = new Date();
        $.cookie('customConsentTime', consentTime.toISOString(), {expires: 3650});
      }
    },
  };

This approach is a bit more work, but it will prevent scripts and cookies from being loaded at all before consent is granted.
Finally, I should note that based on your comments here and on Drupal.org, I think you should do some research on "Drupal Behaviors" for your JavaScript. This will help you to avoid the "Uncaught ReferenceError: Drupal is not defined" message you have been seeing.


hook_module_implements_alter() to put hook implementations into separate files - bad practice?

I just found the piece of information that was missing.
EDIT: And another one.

Problem with module_invoke()

module_invoke_all() always calls module_implements(), which checks the module include file by checking both hook_hook_info() and hook_module_implements_alter().

However, module_invoke() only checks hook_hook_info() and not hook_module_implements_alter().

module_invoke() is called e.g. in _block_render_blocks() for hook_block_view().
This means that hook_module_implements_alter() is not a good solution to split a hook_block_view() implementation into a separate file.

This has been a problem in Crumbs, see https://www.drupal.org/node/2328535.

For other hooks it generally works ok, but you never know if a specific module wants to use module_invoke() instead of module_invoke_all().

module_implements() cache polluted in bootstrap.

Another problem is caused by a core issue reported here:
module_implements_cache() can be polluted by hook_boot() implementations calling module_invoke_all() directly or indirectly

This applies only to non-boot modules, where it can happen that the implementation of hook_module_implements_alter() is never discovered.

An unexpected chain of events causes module_implements($hook) being called from hook_boot().
The $hook can be any random hook, it does not need to be related to the module we are working on.
This causes module_implements('module_implements_alter') to be called.
Drupal looks for all implementations of hook_module_implements_alter().
At this time, MODULENAME.module is not included yet.
Therefore, for the rest of the request, Drupal assumes that the implementation MODULENAME_module_implements_alter() does not exist.
Later in the request, implementations of other hooks are being discovered, but the implementations by MODULENAME are not being found, because MODULENAME_module_implements_alter() is not being executed.

Alternatives

require_once

Alternatives have already been mentioned. Instead of these tricks, one can include the file directly. There may be a tiny performance impact but this is probably overshadowed by a lot of other things in Drupal.

But, instead of using module_load_include(), I would suggest a more direct solution:

require_once __DIR__ . '/crumbs.block.inc';

Or to be PHP 5.2 compatible:

require_once dirname(__FILE__) . '/crumbs.block.inc';

Why not module_load_include()?

There is generally no need to call module_load_include(), it could even be detrimental, if the *.module file is included from you-dont-know-where (e.g. from settings.php), and you don't know if module_load_include() is available.

This function is mostly there to help you determine the location of other modules. But if you are including within the same module, it is generally safer and easier and faster to work with relative file paths and explicit require_once.

Call to helper function

As mentioned by Jimajamma, you can also implement the hook in the main *.module file, and then include another file and call a helper function from there. This is done e.g. in Display suite.

This solution is ok, although I think it still clutters the main file, and gives you even more places to look.

And here likewise you can use require_once instead of module_load_include(), if it is within the same module.


There is more than one way to migrate Drupal content. Usually if you assign a migration from a database into a different database the assumption is that it's about migrating content into a new structure, without any additional content considerations.
As mentioned in the comment you should export/import the second site content rather than migrate.
You can look into Feeds module to import from a CSV, for example, and you can use Views to create a list of your content then export it into a CSV file. This isn't the only way to go about it, just one suggestion. Try to research the export/import ways of content in Drupal ;)


I was able to get specific paged content using following code.

  $data = node_load($nid);
  $pages = explode('<!--pagebreak-->' , $data->body['und'][0]['value']);


Print out the contents of node object in a node template

Try below code

<?php
   print "
";
   print_r($node);
   print "
";
?>

Alternatively you can use below code too...

<?php
  drupal_set_message("
" . print_r($node, 1) . "
");
?>


Input field not submitted in form when added through JS

You can add a hidden field in buildForm() like below

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  :
  :
  $form['token'] = [
    '#type' => 'hidden',
    '#default_value' => ''
  ];
  :
  :
}

or, if you're not building the form yourself, i.e. you're altering an already existing form, you can add the hidden field via hook_form_alter or hook_form_FORM_ID_alter.

Then update value of it using JS if needed


Changing colors per page through drupal interface

You will probably have to add a "Background Color" field to the content type with some selections that map to CSS class names.

Then, depending on where you want to add the background (e.g. on the body or on just the main content area), to add a preprocessor function in your theme to add the selected class as a variable that can be used by the twig template.

E.g. for just the main content area, you would use something like:

function bartik_preprocess_page(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
    if (!$node->color->isEmpty()) {
      $variables['bg-class'] = $node->color->getValue();
    }
  }
}

Copy the page.html.twig file to your theme's templates directory and add the bg-class to the section you want that color.  E.g. class="{{ bg-color }}".


Check this example code:

/**
* Implements hook_token_info().
*/
function yourmodulename_token_info() {
  $info['tokens']['node']['city'] = array(
    'name' => t('Venue City'),
    'description' => t('Returns the Venue city (Location)'),
  );
  return

$info;
}

/**
* Implements hook_tokens().
*/
function yourmodulename_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    if (isset(

$tokens['city'])) {
      $replacements[$tokens['city']] = pathauto_cleanstring($node->field_location['und'][0]['city']);//here I retrieve the value of the city in the location field.
    }
  }

  return $replacements;
}


You probably want to change the global title used for the title block. This is retrieved from the route. The route for a view is built from the view configuration when you save a view  (or clear the cache). The title in the route is static. If you want to change it, modify it in the view configuration. You can do this in ui or in code.

If you want to make this dynamically, you can replace the static _title in the view route with a title controller _title_callback to provide a different title on every request.


How to export Views data in separate sheets/tables to Excel file?

You can do it by using Phpexcel

check out the above link.may it will help you.
i have customised my excel and csv files using phpexcel and it works great their.


How to access a selected label instead of value

Not sure if there is a better way but I got the value by getting the allowed values first.

$allowed_values = $state->getFieldDefinition('field_state')->getFieldStorageDefinition()->getSetting('allowed_values');
$state_value = $state->get('field_state')->value;
$info['state_name'] = $allowed_values[$state_value];


How can my eCommerce site only showcase products without an Add to cart option?

Yes, there is a possibility. You can achieve that by using the Views module.

Create a content type for Products (say products) or you can also use default content types Basic Page or Article .

Add fields whatever you want to show for products (say description, file for PDF).

Create a View for to display the Product content type nodes (products)

  You need Views if

  You like the default front page view, but you find you want to sort    it differently.
  You like the default taxonomy/term view, but you find you want to    sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain    type.
  You like the idea of the 'article' module, but it doesn't display    articles the way you like.
  You want a way to display a block with the 5 most recent posts of    some particular type.
  You want to provide 'unread forum posts'.
  You want a monthly archive similar to the typical Movable    Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts
  for that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.


Print commerce pricing attributes to email receipt

<?php

/**
 * Implements hook_token_info().
 */
function mymodule_token_info(){
    $info['tokens']['commerce-order']['line_item_detail'] = array(
        'name' => t('Line Item Product Detail List'),
        'description' => t('List all the Product Line Item Detail of the order')
    );
    return $info;
}

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if($type == 'commerce-order'){
    $order = $data['commerce-order'];
    $order_wrapper = entity_metadata_wrapper('commerce_order',$order);
    $lineItems = $order_wrapper->commerce_line_items->value();
    $lineItemArray = array();
    foreach($lineItems as $key => $value){
        $line_item_wrapper = entity_metadata_wrapper('commerce_line_item',$value);
        if($line_item_wrapper->type->value()=='product'){
            $product_title = $line_item_wrapper->commerce_product->title->value();
            $quantity = $line_item_wrapper->quantity->value();
            $lineItemArray[] =  $product_title.' x '.$quantity;
        }
    }

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'line_item_detail':
            $variables = array(
                'items' => $lineItemArray,
                'type' => 'ul',
            );
            $replacements[$original] = theme('item_list', $variables);
            break;
      }
    }
  }
  return $replacements;
}

This is the sample code.

You can modify the result you want at hook_tokens().

I hope this will help you.


You need to distinct those specific nodes using taxonomy or a custom field, like a boolean field, say, 0 means no vote and 1 means needs voting. Then use the the flag module to filter those nodes. like this

UPDATE :

The basic idea is, when user flags a content, you can set all of the 1s to 0 in this way no more content will be votable. To do so you need to use hook_flag_flag function. in this function use node_load to load the nodes of boolean value 1, set it to 0 then use node_save to save the node.


PDOException when populating file field programaticalily?

A file field item is not the same thing as a file object/array. You need to set the keys as defined in file_field_schema, which means fid, display and description.


If you use boost module "flushing all caches" maybe not work. Go admin > configuration and open boost configuration, there a tab named "cache expiration" then undo click "Ignore a cache flush command if cron issued the request." I think this usable for you


How to post to remote url on form submit

You can try something like this

$request_url = 'http://your-url.com';
$request_headers = array('Content-Type' => 'application/x-www-form-urlencoded');
$request_method = 'POST';
$request_retry = 2;
// form values you want to post
$form_values= array('apple' => 'red', 'banana' => 'yellow', 'pear' => 'green');
$data = http_build_query($fruits, '', '&');

// Send the request.
$response = drupal_http_request($request_url, $request_headers, $request_method, $data, $request_retry);

if ($response->code == 200) {
  $form_state['redirect'] = array('campaign/thank-you');
}
else {
drupal_set_message(t('There was a problem with your submission. Please try again later.'), 'error');
}

I haven't tried it but let me know if it works.


What module will show me all sql queries being run on the loaded page?

The Devel module has a query log option, which when enabled will show every query that's been run for a request at the footer of the page.

You can enable it at admin/config/development/devel once the module's installed.


Image Responsive Carousel like image Gallery

If you want a fairly simple responsive carousel in views I would recommend checking out Flexslider - it's pretty simple to setup and does everything you want I believe.


Incompatible Mail System setting detected

SMTP Authentication Support module works best with the Print module. I has an option allow sending mail in HTML format.

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


What is the correct way to render content from custom content type?

Option 2 is the preferred option.

Use the default node.tpl.php as a reference.

You can see it uses the hide() function to hide fields it doesn't want to render and the render() function to render fields.

This is because all the processing you are doing in option 1 with field_view_field() has already been done and is ready to render, so you don't need to do it again.

I recommend doing some reading on overriding themeable output, which involves overriding markup with theme functions and template files.


Blocks disappeared when I changed themes

Just click Place block and in the filter up top, search for them and place them again.


Save me from changing the look of CKEditor using Javascript

You can use a CSS override in your stylesheet to achieve this:

.cke_contents {
  max-height: 100px;
  height: 100px !important;
}

And, of course, if you only want to change one instance of the editor, just use an ID selector instead.


Only display content that belongs to User in admin/content

I created a sandbox-module for that called Content Admin Access
Maybe this is what you are looking for.

With Content Admin Access you can set permissions to show or hide others content in the admin/content overview.
Enabling this module will by default show only your own content in the admin/content overview.


Unsure how to define an entity type using Entity API

entity_extract_ids() raises an exception when $info['entity keys']['bundle'] is not defined, or is an empty string. If you don't want to explicitly set the bundle property, you need to set it to  value that is considered empty from PHP, but it is not an empty string, such as an empty array, or FALSE. In such cases, the bundle property is set to the entity type name.

The following is the code contained in entity_extract_ids(), and which raises the exception you are seeing.

if (!empty($info['entity keys']['bundle'])) {
  // Explicitly fail for malformed entities missing the bundle property.
  if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys'] ['bundle']} === '') {
    throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
  }
  $bundle = $entity->{$info['entity keys']['bundle']};
}
else {
  // The entity type provides no bundle key: assume  single bundle, named
  // after the entity type.
  $bundle = $entity_type;
}

Keep in mind that entity_get_info() caches the entity information it gets. If you edit an enabled module, you need to disable it, and re-enable it. This forces Drupal to clean the cache it uses, and call the implementations of hook_entity_info() to get a fresh definition of the entity.

  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
  }
  $entity_info = &$drupal_static_fast['entity_info'];

  // hook_entity_info() includes translated strings, so each language is cached
  // separately.
  $langcode = $language->language;

  if (empty($entity_info)) {
    if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
    }
    else {
      $entity_info = module_invoke_all('entity_info');
      // Merge in default values.
      foreach ($entity_info as $name => $data) {
      // …
    }
    // …
  }

Installing a new module has the same effect, as Drupal should clear its cache in that case too. If it doesn't happen, you can always force Drupal to clear its cache with cache_clear_all('entity_info', 'cache', TRUE).


admin/config page taking around 30 seconds to load; the rest of the website loads fast

The admin/config page can trigger a check of the site 'status report' which depending on the modules & services your site uses may check for the ability to connect to certain services. 30 seconds sounds like it is trying to use some service but throws a timeout after 30 seconds. Try checking the status report under working / not-working conditions to see if some services are being blocked.


How to update uber cart attribute pricing programatically in Drupal 7?

UPDATE uc_product_options set price = 333 where oid = 111


entity_load() not listing custom fields.

After banging my head for a while, I found the solution. On the module where that entity was defined 'hook_entity_info()', 'fieldable' property was missing which is set to FALSE by default. Therefore none of the fields were being attached to that entity.


entityFIeldQuery on user table, how can I add a condition for $user->data

The data column contains a serialized PHP string, which MySQL doesn't understand. As far as MySQL is concerned the data is just a string like any other.

Because of that you won't be able to query the properties of the serialized objects in that column without doing some seriously nasty work with SUBSTRING/regex/insert-other-unreliable-method-here.

If possible you should add a field to the user entity instead that represents the same data, and use the EntityFieldQuery with that field. It might not be ideal but it's probably the easiest solution.


How to fetch image from database in drupal

The style is an image style which is described a bit in Working with images in Drupal 7 and 8. I believe that you need to use Style_name as the 'style' in your code instead of 'public':

 $fid=$r['field_upload_photo_fid'];
 $file = file_load($fid);
 $variables = array(
 'path' => $file->uri,
 'style'=>'Style_name'
 );
 print theme('image_style', $variables);

But also, what is the data in $file->uri? If you start with bad data then the result is also going to be bad.


Load CKeditor with Simplified Toolbar on dynamically created page element

For better or worse, this is how I did it:

http://joe-riggs.com/blog/2012/11/drupal-ckeditor-load-configuration-settings-on-dynamic-page/


I managed to acheive it through hook_menu_alter. It just works great for me

<?php
/**
* Implements hook_menu_alter.
* @author Md Eqbal Ahmad <*****@******.com>
*/
function MODULE_menu_alter(&$items) {
  $items['comment/%']['page callback'] = 'MODULE_commentpermalink';
}

/**
 * Redirect comment permalink to their corresponding node paths
 * @author Md Eqbal Ahmad <*****@*****.com>
*/
function MODULE_commentpermalink($cid) {
  if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    // Now, rather than setting menu_executive_active_handler and changin $_GET valies, we redirect them to the actual node URL with fragments and pager set.
    if ($page > 0) {
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid",'query'=>array('page'=>$page)), 301);
    }
    else{
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid"), 301);
    }
  }
  drupal_not_found();
}

?>


First decide if this will be role based or user based. If it is Role based you can use the default permission system in Drupal.

If you want it per user consider using Content Access Module in conjunciton with ACL module


Prevent caching of variable in twig template

This seems a bit chaotic. You don't need an url context on a page, because this is set already. You don't need other cache data, if you have max-age = 0. If your message depend on the current user, you need a user context. And always add cache data, never replace it.

I would use a block for the message which, if it depends on the current user, can be auto-placeholdered. Then you don't need to disable page caching, which is better for performance, see https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


hello_world_page_attachments is not called

Libraries are refererred to as module_machine_name/library_name

If the other names in your post are accurate, in your case that should be:

$attachments['#attached']['library'][] = 'hello_world/hello_world';


In Drupal 7 how can I programmatically create a menu link to a view?

You can do it using hook_menu and views_embed_view in a custom module.

function yourmodule_menu() {
    $items = array();
    $items['duplicate-view-path'] = array(
        'title' => 'View Title',
        'page callback' => 'custom_render_view',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function custom_render_view() {
  $output = views_embed_view($view_name, $display_id = 'default');
  return $output;
}


Remove/hide title/subject from published comments

In your theme folder, if you do not have a comment.tpl.php file, create one. And customize yours to not have the title. Just take out the title from the file

Another option is to try removing it in your template.php file in the yourtheme_preprocess_comment() function


Block showing Parent Taxonomy Term of current Node

I think this is impossible with the Views module.

To achieve the goal, you can create a block with a relation to the "Holiday Cards" term. Under Filter criteria select Taxonomy term: Name (= Holiday Cards).

To display the block only with the content related to another taxonomy term, you can consider to use the Context module.

Instal the module and turn it on.
Go to /admin/structure/context/add and create your new context
Under "Conditions" choose your taxonomy term "Trees"
Under "Reactions" choose "Blocks"
Select your block created in views and place it in appropriate region
Save the context

That's it! Your block with relation to "Holiday Cards" will be displayed only with content which is related to "Trees."


Remove "Language Undefined" from content with Multilingual module

You can remove it from : admin - structure - content types - Article / Basic page "Manage Display" - set the language field from "visibe" to "hidden" - Save

Done!


How to diasplay stock quantity of goods in node-product.tpl.php

There is not much to uc_stock_level(). Check that you are supplying a model/SKU that is in the table and it is active. If that's the case, you might need to flush your cache to pick up new changes in your template file.


How do I change the name of the "view" node tab for a specific content type?

In your theme open file THEMENAME.theme, and the add code below:
function MYTHEME_preprocess_menu_local_task(&$variables) {
  if (isset($variables['element']['#link']['title']) && $variables['element']['#link']['title'] == 'View') {
    $node = \Drupal::request()->attributes->get('node');
    if ($node && $node->getType() == 'hotel') {
      $variables['link']['#title'] = t('Hotel View');
    }
  }
}

Clear all cache and see result.


How do I show multiple nodes on the same page without writing code?

I came to a similar situation of your question before. I need a page, divided to two parts. On left shows company info such as Google map, company address, phone number etc. On the right side, shows a "Webform-ed" Contact Us form. The single page is actually a Panel node of a combination of two other nodes.

My solution is use Panel modules.

Enable modules:

Create a Panel Node, pick a layout of the Panel node.

Add content to each place.

Select existing node you created. (e.g Company info node  & Contact us node)


Try Services Search & Services module. Using these module you can expose search results as JSON.

Another option is Views Datasource module. Construct a page view which accepts search term as an argument and displays search results in JSON format.


Hierarchy between terms from different vocabularies in Drupal 7?

You can make a term reference field on a vocabulary.
So on a the team vocab one of the fields would be "division".
So when you create a new team you would enter the team name and "tag" the division it is in using auto complete or a dropdown.


You can use the Address Field module.  To do just the country and city, you will have to define a plugin.  Look in the addressfield/plugins/format directory for examples.

To add the cities, you will have to define a list of cities for each country in the plugin.  You can then format the list and add it to your plugin and you should be good to go.

One advantage of using the Address Field module is that if you do not define a list of cities for a country, users will still be able to input the city themselves.


EntityRegistration: How do I show who is registered to other registrants/members

I've got it work by creating a View with a contextual filter for the event-id. Then in the event-page (using Panels) if added the event-id to the arguments when rendering the view into a pane.


If you have a backup of pre-upgrade version, how about your import your faulty view from there. The export-import feature in Views is usually very robust. If the import is successful, there is not point in banging your head as to why this error is coming.


There is a module just for this, where you can add and group fields together, as well as add multiple field groups: Field Collection


Why are there 2 ways to handle configuration?

This change record explains it all: Configuration objects by default are immutable.

  ConfigFactoryInterface::get() no longer returns configuration
  objects that can be saved. This is to ensure that configuration
  overrides do not get into active configuration. Configuration
  overrides are, for example, global overrides set in settings.php or
  translations provided by the locale module. If you need to get a
  configuration object that can be saved, use
  ConfigFactoryInterface::getEditable(). Objects returned by that
  method will not have overrides applied.

  Previously

// Just get the site name (with overrides).
$site_name = \Drupal::config('system.site')->get('name');

// Set the site name.
\Drupal::config('system.site')->set('name', 'My fantastic site')->save();

  Now

// Just get the site name (with overrides, same as before).
$site_name = \Drupal::config('system.site')->get('name');

// Set the site name.
\Drupal::configFactory()->getEditable('system.site')->set('name', 'My fantastic site')->save();

Are you also/alternatively asking why there's a Drupal::config method, but not a Drupal::configFactory method, i.e. why do you have to use the generic Drupal::service method for the second one?

If so, that's simply because the shortcut methods exposed on the Drupal class are for the most regularly used services. The config service is used in procedural code a lot more than config.factory, so there's no shortcut method for it. There are hundreds (thousands?) of services throughout the system so providing a method for each would be overkill


How to add multiple suffixes for an integer field type?

There are 3 options:

Install the Measured Value Field module.
In your custom module implement hook_form_alter and add your dropdown there with markups.
Create actual dropdown and work with just markup.


Is a MySQL statement from an external script possible?

Drupal does use SQL statements to communicate with the database, however it does so through a built in abstraction layer. That said, you can write regular old SQL from any PHP script to query the information you need, as long as you have the database connection info. Personally I would build whatever functionality you're after into a custom Drupal module, and then use that to interface with whichever external service you're working with. We would need a bit more information on exactly what you're trying to achieve to provide more specific feedback however.