How do I bulk switch specific content from one content type to another?

I know I can bulk switch a content type using this module, but I don't want to switch a whole content type, just specific articles in one content type to the Spam content type all at once. It would make sense to to this from the admin content dashboard.

Node Convert lets you create a custom action to perform this task. You may cherry-pick any items you want to convert and convert them. You need not convert all content from 1 content type.

This feature is in Admin -> Content.

Be sure you have tried installing the various dependencies. In this case probably Rules and maybe VBO:

  The module integrates with Actions, Rules, Views Bulk Operations and Admin Views nicely. It has support for exporting templates into Features using CTools Exportables.


Drupal default login URL format,

example.com/user


How can I select which tags should be stripped from the footer?

I assume you are talking about a custom block that you add in the footer region of the site. In that case, you need to include all the HTML tags used to create a map image, which are <area>, , and <map>.

I have tried with a block contained the following HTML.

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun">
  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury">
  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus">
</map>

Once I enable those HTML tags for the Filtered HTML input format, the HTML added to the page for that block is the following.

<map name="planetmap">

  <area shape="rect" coords="0,0,82,126" href="http://www.w3schools.com/tags/sun.htm" alt="Sun" />

  <area shape="circle" coords="90,58,3" href="http://www.w3schools.com/tags/mercur.htm" alt="Mercury" />

  <area shape="circle" coords="124,58,8" href="http://www.w3schools.com/tags/venus.htm" alt="Venus" />

</map>

Keep in mind that, since the function Drupal used to filter out HTML tags is filter_xss(), the HTML you pass to the Filtered HTML input format is altered to:

Remove characters and constructs that can trick browsers
Make sure all HTML entities are well-formed
Make sure all HTML tags and attributes are well-formed
Make sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

Then, also _filter_xss_attributes() is called; that means also tag attributes are filtered.


Drupal 8 installation (bash) script. I want the latest stable v8 version each time. But how?

As mradcliffe said in the comment, if you don't want to use composer (which I would really recommend you look into), you can simply use drush. You just need this:

drush dl drupal

This defaults to the latest stable Drupal 8 version. If you want to have a git clone (which is way slower), you can tell drush to do that too:

drush dl --package-handler=git_drupalorg drupal


As is my nature, I was totally overthinking this. Here's what I had to do in ThemeKey:

First, for the File field:

drupal:path = imce-filefield/%

Basically, this is matching the first section of the URL path with imce-filefield and then whatever else comes after it is matched with /%.

This solves the problem for file/image uploads. The IMCE file browser used in the WYSIWYG editor (in my case, CKEditor) has a different URL path, so its interface is still broken. That one is simply:

drupal:path = imce

So far so good...


If your entity_lookup is searching Users then the bundle, I think, should also be user since there is no people bundle.


Rules scheduler and views- how to show normal users the schedule?

Why not add a user profile field that stores the ban removal date? Then you could use the "Time ago" formatter with the "Time hence" setting and then just set or unset it using the rule (and it's associated de-ban rule). You can show that field using Views and/or on the user's profile page. Or panels. Or custom code... etc.


You could define your own formatter with hook_field_formatter_info() and then select that in the Manage display screen of the content type/view mode you want to be displayed like that.

For reference, have a look at what taxonomy.module is doing: taxonomy_field_formatter_info(), taxonomy_field_formatter_prepare_view() and finally taxonomy_field_formatter_view().


Acquia Desktop & MAMP: No Drupal site found, only 'drush' cache was cleared

To fix this answer I created a new Alias called adrush which points to the Acquia DevDesktop Version.

In my .bash_profile file in my home directory I added

alias adrush='/Applications/DevDesktop/drush/drush'

now when running drush commands for sites that are in my Acquia DevDesktop environment I enter adrush cc all


How can I automatically make term relations between all the terms with same term name?

I don't think you really want to just display the related terms. Thats a complicated band-aid to a problem you probably would be better off actually solving.
This type of problematic data is often encountered as part of a migration so it is definitely do-able in a migration like process.
Steps:

Decide which tid is going to be authoritative.
Find all duplicates of that term.
Re-assign all references to that duplicate term to the
authoritative term.

Install the Taxonomy dupecheck module so you don't get in this kind of trouble again. Some details from its project page:

Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.
The module provides a configuration screen allowing administrators to choose which should be unique: taxonomy terms, vocabularies or both. It defaults to case-insensitive comparisons, with an option to change to case-sensitive. Both stored and input terms/vocabularies are trimmed before comparison to handle cases such as 'foo ' and 'foo'. Based on the settings, the user will see an error message when adding a duplicate value.
Caveat: due to the inability of hook_taxonomy_term_presave() to stop the saving process, this only works in the taxonomy term and vocabulary forms. If you want to prevent duplicates through other entry points, this module will not prevent that. If someone knows a way around that I will happily add that in, as that was the original plan.


How can I import special characters using Feeds?

Consider using the Feeds Tamper module. Here is a quote from its project page:

  ... provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below. Additional plugins can be added in separate modules or through the issue queue.

It allows for HTML encoding / decoding of feeds content before saving.

PS: Feeds Tamper doesn't know anything about taxonomy terms (you cannot use it for "Terms", as mentioned in a comment to this answer, which the original question didn't mention though).


But my problem is when I edit this room and I add New members, I want
  to send an email only for new.

As hook_entity_update mentions

  Get the original entity object from $entity->original.

$entity->original gives you access to the values before the update.

So all you gotta do is compare the original members to the updated members to find out who are the new members.

$og_members = array();
$og_members = $entity->original->get('field_members')->getValue();

$up_members = array();
$up_members = $entity->get('field_members')->getValue();

$new_members = array();
// use array_diff() to find the difference.
$new_members = array_diff($up_members, $og_members);


What can be put in 'Full HTML' node/fields?

You technically can use <meta> tags, since they will not be stripped out of the content that you place into a textfield that uses the default "full HTML" input filter. However, this content will be output in the <body> of the HTML document, which means using <meta> tags here will cause invalid HTML and most likely be ineffectual.

If you are looking for a way to customize the <meta> tags used on your Drupal site, there are many modules available to help with this. The Meta Tags module is the most popular, but that project's page also lists some other meta tag-related modules.


Access CCK Fields on Content Type EntityFieldQuery()

EntityFieldQuerys are for querying entities, with the option to filter on their field values. They don't have the capacity to return any field data.

What you might be looking for is something like this, using field_get_items() and field_view_value()

...
$output = [];
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // Get the field items
  $items = field_get_items('node', $node, 'field_rfqs_received');

  // Truncate to the necessary number (your logic will probably change here)
  foreach (array_slice($items, 0, 5) as $item) {
    // Add to the output array.
    $output[] = field_view_value('node', $node, 'field_rfqs_received', $item);
  }
}

print render($output);


Use hook_views_pre_render() to change field to url link

I have not been able to figure out how to conditionally change field to link using hook_views_pre_render(), but I did figure out how to do it within the Views UI:

Fields->Parent ID->Rewrite results->Override the output of this field with custom text:

{% if parent_type == 'paragraph' %}
{{ parent_id }}
{% else %}
{{ parent_id }}
{% endif %}


Show a sale price and discount percentage in Commerce 2

Easiest way for me was to create my own FieldFormatter for the price and make it extend Drupal\commerce_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter.

Once you did that, flush the cache of your website, go to the manage display of your Product variation type, select "My Custom price calculated formatter" for Price field and in the parameters, check "Apply promotions to the calculated price". And voilà!

Here is an example code for the custom FieldFormatter:

<?php

namespace Drupal\my_custom_module\Plugin\Field\FieldFormatter;

use CommerceGuys\Intl\Formatter\CurrencyFormatterInterface;
use Drupal\commerce\Context;
use Drupal\commerce\PurchasableEntityInterface;
use Drupal\commerce_order\AdjustmentTypeManager;
use Drupal\commerce_order\PriceCalculatorInterface;
use Drupal\commerce_price\Plugin\Field\FieldFormatter\PriceDefaultFormatter;
use Drupal\commerce_store\CurrentStoreInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\commerce_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter; // This is the FieldFormatter we want to extend

/**
 * Plugin implementation of the 'my_custom_price_calculated_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "my_custom_price_calculated_formatter",
 *   label = @Translation("My Custom price calculated formatter"),
 *   field_types = {
 *     "commerce_price"
 *   }
 * )
 */
class MyCustomPriceCalculatedFormatter extends PriceCalculatedFormatter implements ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   * This is the function we want to extend
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    if (!$items->isEmpty()) {
      $context = new Context($this->currentUser, $this->currentStore->getStore(), NULL, [
        'field_name' => $items->getName(),
      ]);
      /** @var \Drupal\commerce\PurchasableEntityInterface $purchasable_entity */
      $purchasable_entity = $items->getEntity();
      $adjustment_types = array_filter($this->getSetting('adjustment_types'));
      $result = $this->priceCalculator->calculate($purchasable_entity, 1, $context, $adjustment_types);
      $calculated_price = $result->getCalculatedPrice();
      $number = $calculated_price->getNumber();
      $currency_code = $calculated_price->getCurrencyCode();
      $options = $this->getFormattingOptions();

      // Check if there is any adjustment for the price
      // If so, get the BasePrice (without adjustment) and format it
      if(!empty($result->getAdjustments())) {
        $adjustments = $result->getAdjustments();
        foreach($adjustments as $single_adjustement) {
          // Get the discount percentage off
          // NB: there could be many other discounts applied but this example catches percentage discounts only
          if($single_adjustement->getType() == "promotion" && $single_adjustement->getPercentage() !== NULL) {
            $discount = $this->t('@discount off', ['@discount' => $single_adjustement->getPercentage() * 100 . '%']);
          }
        }
        $base_price = $result->getBasePrice();
        $base_price_number = $base_price->getNumber();
        $base_price_currency_code = $base_price->getCurrencyCode();
        $base_price_formatted = $this->currencyFormatter->format($base_price_number, $base_price_currency_code, $options);
      }

      // This is our calculated price with the promotion
      $price_display = $this->currencyFormatter->format($number, $currency_code, $options);
      if(isset($base_price_formatted)) {
        // Set the base price (old-price), the percentage off and the calculated price within $price_display
        $price_display = '
' . $base_price_formatted . '

' . $discount . '

' . $price_display . '
';
      }

      $elements[0] = [
        '#markup' => $price_display,
        '#cache' => [
          'tags' => $purchasable_entity->getCacheTags(),
          'contexts' => Cache::mergeContexts($purchasable_entity->getCacheContexts(), [
            'languages:' . LanguageInterface::TYPE_INTERFACE,
            'country',
          ]),
        ],
      ];
    }

    return $elements;
  }

}


If I understand your question correctly, I think you need the Auto Entity Label module. Using this module, you can automatically generate labels by a given pattern for the taxonomy term names.


Date module not showing Text with Date Popup widget

I think "Date Popup" module is not enabled. You have to enable it, then it shows the Pop-up calendar option in the select list.


Use another language than "default" as standard

Drupal 7?

The language negotiation is extendable, you just need to implement hook_language_negotiation_info(). In there, you can do whatever you want, like always default to swedish for now. It also looks like you can limit to what languages you can switch to, I am not sure how that exactly works, though.

Not sure what to do once you add more languages, but you could for example call other negotiation callbacks in yours and fallback to swedish if it not one of the languages you want displayed.


Duplicate Meta description on shared node across multiple subdomains

I haven't used that module (looks cool!), but it does depend on metatag, which is probably what's providing the title & description fields. The metatag module saves its configuration in a database table metatag_config, which is probably shared across all of your subdomains.

It looks like you can have tokens in your config, so for example, we use [node:title] [site:name] for our page title config. And if you wanted an unique title for each subdomain, you could just specify a separate site name for each one.

We use subdomains (www, m, staging, dev, etc) and we're fine to share the node's title & description across all of them. The thing we do want unique is the canonical meta tag, so if a search engine comes across duplicated content on a subdomain, it won't take anything away from the original. So we'll specify the full domain in the canonical url like this:

https://www.example.com/[current-page:url:path]


Config Export: How to store default value of taxonomy field?

I figured out the solution.

The value stored in the config/sync is not the tid of the taxonomy term, but the uuid. Because of this, I can just change the value of uuid column in taxonomy_term_data row of the dev's term to that of the stage's server without affecting the tid column.


Where can I find the form API reference?

Many of the form element properties are listed in the documentation for the FormElement class. The properties described there are:

#after_build
#ajax
#array_parents
#default_value
#description
#disabled
#element_validate
#field_prefix
#field_suffix
#input
#parents
#process
#processed
#required
#states
#title
#title_display
#tree
#value_callback

Then, as Form and render elements says:

  Each form and render element type corresponds to an element plugin class; each of them either extends \Drupal\Core\Render\Element\RenderElement (render elements) or \Drupal\Core\Render\Element\FormElement (form elements). Usage and properties are documented on the individual classes, and the two base classes list common properties shared by all render elements and the form element subset, respectively.

(Emphasis is mine.)

There isn't a single page describing all the form element properties, but there is a page for each plugin class that implements a form element.


Popular Content with statistics module incorrect

There are many reasons the counts from different web counters are off (I had a former boss drive me nuts with that back in 1998 ...):

statistics module increments page counts on every reload
when a page is cached it might not increase the statistics counter, depending on the caching used. GA does increase because it's based on browser page loads
GA doesn't increase when bots are visiting your site (because they don't execute javascript)

I usually rely on GA for my business reports and just use statistics to show counts for my users.

You could also use the Google Analytics module to import GA numbers back into Drupal.


Why do my files get lost when migrating a CCK Filefield?

Have a look at the Video about Upgrade Drupal6 to Drupal7 using the MIGRATE module. You're probably familiar already with many of the things shown in it, but it also provides some other interesting tips about things like:

Before starting the migration, make sure your current Drupal 6 site is in good shape (like update your contributed modules to the most recent D6 version first).
If you have a lot of files (attachments) to be upgraded also, it might be possible to do that part without using the migrate module.
If you have a possibility to create a (temporary) subdomain for your Drupal 7 version, that will speed up the migration execution quite a lot.

Especially bullet nr '2.' above may be worth experimenting with. In the video it is shown starting from about 12:05 (and the "Step 4: Files" screen provides some more details about what your options are here). Later on in the video, starting from about 15:45, you can see that the "image placeholders" (pointing to some files) are already OK. So afterwards you just need to copy those files to the right spot, using FTP or something.

So try running migrate with that option for Step 4 "unchecked" (turned off)!


How to show related nodes in a view block based on taxonomy terms?

SOLVED

Add a Contextual Filter->Has Taxonomy Term ID
When the filter value is NOT available:

Provide default value Type: Taxonomy term ID from URL
Check only: Load default filter from node page, that's good for related taxonomy blocks; Limit terms by vocabulary; Vocabulary: my-vocabulary; Filter to items that share my term.

When the filter value IS available or default is provided:
Check only: Reduce duplicates.


Using the DB API to test against a trimmed value?

You can use SelectQuery::where() for more complex requirements:

$query->where('trim(my_field) <> :val', ['val' => '']);


How to cache custom controller markup for logged-in users?

One thing that you can do is the same as the entity view builder is doing, use a #pre_render callback.

If you look at \Drupal\Core\Entity\EntityViewBuilder::viewMultiple(), you can see it doesn't really do anything except prepare the render array and add a #pre_render callback to the whole thing.

The reason for that is that the pre_render callback will only be called on a cache miss. So you return your array with the cache keys/tags/contexts/max-age, the renderer service will attempt to load from the render cache. On a cache hit, it will return the previously cached HTML, on a miss, it will call the pre_render callback and you can do the things you want to do there.


How can I create a friendship that must be approved with the Relation module?

Rules is just a handy "programmatic tool" (and API) to encapsulate things. Relation is a way to express -- well Relations.

In my opinion, using just relation and either Views or RelationQuery or EntityFieldQuery you can come up with what you need.

You just need more than 1 Relation.

Something like 1 relation of:
UserA <- are_friends -> UserB

to express a global "friends list" of users within your site. You could make another relation a_user <- has_friends -> user(s) which could be 1 users friends list.

Another relation:
UserA <- is_a_friend_request -> UserB (1-way relationship)

The is_a_friend_request relation could have an attached field of 'request_status' which is a "select list" field type for instance with "approved" and "denied" or "ignore" as options.

A view could be made to show to any user of their "friend_requests". Acting on a friend request adds a recipient user to a given user's "are_friends" relationship.

I'm not sure if this is a naive way of looking at your problem ... you could definately use rules in there somewhere ... but its not a necessity.


I just did this with the imagefield extended module and a small custom module. After enabling the imagefield_extended module, I add this code to my custom module.

/**
* Implementation of hook_imagefield_extended_widget().
*/

function MYMODULE_imagefield_extended_widget($element, $extra_values) {
  // If you need the field or widget to conditionally add a FAPI field, use these.
  $field = content_fields($element['#field_name'], $element['#type_name']);
  $widget = $field['widget'];
if($element['#type_name'] == 'occupancy_status' && $element['#field_name'] == 'field_task_files'){
  return array(
    //This will Replace the Textfield with dropdown select for the description
    'description' => array(
      '#type' => 'select',
      '#title' => t('Document Description'),
      '#options' => array(
         'Occupancy Flyer' => t('Occupancy Flyer'),
         'Personal Property Release' => t('Personal Property Release'),
         'Introduction Letter' => t('Introduction Letter'),
         'Notice of Rights' => t('Notice of Rights'),
         'Miscellenous' => t('Miscellenous'),
      ),
      // this makes b the default value when the value is not set.
      '#default_value' => isset($extra_values['description']) ? $extra_values['description'] : 'Miscellenous',
    ),
  );
  }

   if( $element['#type_name'] == 'property_gallery' && $element['#field_name'] == 'field_gallery_images' && arg(1)!=='add'){

  return array(
    //These are stored in the 'data' column of the cck imagefield's db table
    'revised' => array(
      '#type' => 'checkbox',
      '#title' => t('Revise This Description'),
       '#default_value' => isset($extra_values['revised']) ? $extra_values['revised'] : 0,
     '#attributes'=>array('class' => 'revise-check')
       ),
    'revisedby' => array(
      '#type' => 'textfield',
      '#maxlength' => 64,
      '#title' => t('Revsied By'),
      '#description' => t('Replace your name with the current name if you are making a new revision.'),
     '#default_value' => ($extra_values['revised']==0) ?  NULL : $extra_values['revisedby'] ,
       ),
       'revisedon' => array(
      '#type' => 'date',
      '#title' => t('Date Revised'),
     '#default_value' => ($extra_values['revised']==0) ?  NULL : $extra_values['revisedon'] ,

       ),

  );
  }
} /*End function */

You have the ability to add or modify the filefield or the imagefield field widgets. The only problem that I'm stuck at is making this work for fupload_imagefield.


What is the difference between renderPlain and renderRoot?

renderRoot() is for rendering the final result returned by a controller. renderPlain() is for rendering HTML which is not part of a page and is used for other purposes like emails. In your case the correct method would be render(), because this is the only render method which can bubble up metadata to the page. But you don't need to render at all, because you can put the unrendered form build array in a template variable and it will be rendered automatically when printed in TWIG.


Programmatically rendering a Views pane with arguments from context

I got it to work with

$selected_type = 'views_panes';
$selected_subtype = 'persona_display-panel_pane_1';
$context = array(
  'context_taxonomy_term_1' => ctools_context_create('entity:taxonomy_term', $fully_loaded_taxonomy_term);
);
$config = array(
  'context' => array('context_taxonomy_term_1');
);
ctools_content_render($selected_type, $selected_subtype, $config, array(), array(), $context);

So, in order to render a Views Pane display with contextual filters coming from the pane's context you to populate $context and inform the display handler on which entries of $context to use for each contextual filter with $config['context'].


Update Two select box when change another select box

Try one of the following module

Simple hierarchical select

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Hierarchical Select

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

Or you can also achieve that by writing a custom module :)


This line is using the deprecated pass-by-reference:

    $block['content'] = zillow_form($form, &$zinfo);

You can fix that with no ampersand:

    $block['content'] = zillow_form($form, $zinfo);

And I think your submit function should be named zillow_form_submit instead of zillow_submit_info.


How do I check if an image field is empty in a template file?

Use the method isEmpty() on the image field:

  {% if node.field_image.isempty %}

Field "field_image" is empty.

  {% endif %}

Although in this case you might need to check the user entity of the node author:

  {% if node.uid.entity.user_picture.isempty %}

Picture of the node author is empty.

  {% endif %}


Advance Search form $form is not the same when invoked a second time?

As I understood from your question you need to add additional style when no results found.

The file search-block-form.tpl.php in search module folder is responsible about displaying the form you could copy it to your theme folder and alter the markup as you need (You have to clear cache in order to flush theme registry).

Also take a look at the two files search-result.tpl.php and search-results.tpl.php the same could be done depending on your needs and use case.

For more clarification about theme suggestions read


Gmap Error "Javascript is required to view this map" when embedding the node in another node

GUnload is part of the Gmap API. Are you loading the Gmap js files served by Google?

The error would happen if the JS file from Google is:

Missing.
Has not been parsed when the code giving the error is executed.

To give a more thorough answer more details are needed.

Update

The Gmap module is a bridge to the Gmap JS API that Google has created. The actual Gmap JS API is not included in the module itself but is served by google. It's included using the following line:

drupal_set_html_head('<script src="'.
  check_url(url('http://maps.google.com/maps', array('query' => $query))).
  '" type="text/javascript"></script>'
);

The error you are getting, it is caused by the lack of the above JS file, or because it's loaded after the gmap module JS code is run.


How do I programmatically load an order by its properties?

The best way to do this is by using by loadByProperties based on Token field:

$orders = \Drupal::entityTypeManager()
  ->getStorage('commerce_order')
  ->loadByProperties(['field_token_id' => 'TOKEN VALUE']);
$order = reset($orders);
$state = $order->get('state')->value;
$total_price = $order->getTotalprice()->getNumber();
$currency = $order->getTotalprice()->getCurrencyCode();

Here assuming token as a unique value.


How to use Sort By desc by default with toggle link enabled?

I didn't found any suitable way to do this. What I actually did, I changed the link using jQuery.


How can I reduce the granularity of login time ago in Views (from minutes to days)?

In the "dull ax" approach to things, you could do a combination of things here.

In the Views UI, under the Date Format, there is a If "Custom", see the PHP docs for date formats. If "Time ago", enter the number of different time units to display, which defaults to 2. Set this to 1.
Now, Views will only output 13 sec ago 13 min ago 1 hour ago etc instead of 1 day 13 hours etc.
This still doesn't get rid of your specificity of the time of the day if today, eg it is going to output 1 sec ago, 12 min ago or 3 hour ago, etc.
To take care of that, you can create a views template for that field, eg, here in D6 World it would be something like views-view-field--NAMEOFVIEW--login.tpl.php.
In there, do something along the lines of:

if (strpos($output, 'sec') !== FALSE || strpos($output, 'min') !== FALSE || strpos($output, 'hour') !== FALSE) {
  print t('Today');
}
else {
  print $output;
}

which will print out Today if it sees a sec, min or hour, or the default if not, eg, it sees day, week, month etc.


How to get map widget for location selection with Location / GMap

Have you checked out the Geolocation Field Module? It works with the Google Maps Api v3 and does exactly what you are trying to do. You add the map as a field/widget within your content-type. The Field stores lat/lon values.


How do I programmatically retrieve the inputs from a form?

You can use the element_children() function to grab all of the child elements within a particular element (including a form element). The thing with Drupal forms is that often all elements are not on the same level of the array, so you'll need to make a recursive function to get them all reliably. This is untested but should give you a place to start:

function _element_children_recursive(&$element) {
  $names = array();

  foreach (element_children($element) as $element_key) {
    $names[] = $element_key;
    $names = array_merge($names, _element_children_recursive($element[$element_key]));
  }

  return $names;
}

$all_element_names = _element_children_recursive($form);

There's even one further caveat to this...since form elements can be on different levels you might well end up with two identically named keys. This is perfectly valid in Drupal so you'll probably want to do a bit of checking in the recursive function to avoid duplicates.


Invoke a camera to start in Drupal 7 Forms API

Have you tried the webcams module ? Even if it's dev I'd say it's worth trying.

Do a search on webcam on Drupal and try out some of the modules listed.

Else if you want to develop your own module then the best way is probably doing the integration of an existing webcam jquery module. (See some jquery plugin examples here)


How to alter the value used to sort a view?

you can change query of view by this
hook_views_query_alter(&$view, &$query)

This hook is a core hook of views api but you can override it in you custom moduel like MYMODULENAME_views_query_alter

In this hook you can get parameters by exposed filter's and change views query based on these parameters.


How to Modify Views output on every 10th item?

Views by default wraps each View in a div with a class based on the View's name, eg,

and each row in a div with a views-row-# class, eg,

So, quick and dirty, you could change the first 5 of these with css along the lines of

.view-NAME .views-row-10,
.view-NAME .views-row-20,
.view-NAME .views-row-30,
.view-NAME .views-row-40,
.view-NAME .views-row-50 {

   /* different CSS here */

}

You can cascade down from there if you need or want to change the CSS of any of the fields in the row as well.

If you want to get fancier, you can also add classes to each row based upon modulo arithmetic inside of the Views theme templates or via a pre_process hook and then base your css off that class.

ADDITION BASED ON COMMENTARY:

Can you do something like this with the first/last classes?  Immediately out of the box it sort of does what you want, eg:

creates output like this:

and where last-tenth in this quick and dirty copy and paste is every 10th row?


Displaying fields from my content types in a module

The best way would be to grab just the node ids from the table, and use the node_load_multiple() function to load the node objects.

The field data will be attached to those objects, and you can use other API functions to extract the data/build the display HTML (field_get_items() and field_view_field() respectively).

Some sample code that should help:

function photo_gallery_contents($display){
  $max_num = variable_get('photo_gallery_max', 3);

  $query = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('status', 1) //Published.
    ->condition('type','portfolio') // Only want our photos aka Portfolio content type
    ->orderBy('created', 'DESC'); //Most recent first.

  if ($display == 'block') {
    // Restrict the range if called with 'block' argument
    $query->range(0, $max_num);
  }

  // Fetch the results for the nid field into an array
  $nids = $query->execute()->fetchCol();

  // Load the node objects and return
  return node_load_multiple($nids);
}

function _photo_gallery_page() {
  $result = photo_gallery_contents('page');

  //Array to contain items for the page to render.
  $items = array();
  //Iterate over the resultset and format as links.
  foreach ($result as $node) {
    // Build a render array based on the field's display settings.
    $image = field_view_field('node', $node, 'field_image');

    // Render the array down to the image HTML
    $image_html = drupal_render($image);

    $items[] = array(
      'data' => l($image_html, 'node/' . $node->nid, array('html' => TRUE)),
    );
  }
}


Just thought I'd give an update: this problem actually had to do with Clean URLs, once I migrated the site, I had to disable Clean URLs directly in the database since I couldn't access any of the sub-pages of the website so I couldn't get to the admin area, then I replaced the custom htaccess I got from the remote server with an htaccess from a fresh Drupal 5 installation, and that basically solved it! Wow, what a relief, thought I was going to go crazy trying to figure this one out!


Figured it out and required SSL via phpmyadmin admin interface for my users.

There are my Drupal database params

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'AWS RDS Endpoint',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
        PDO::MYSQL_ATTR_SSL_CA => '<path to>/rds-combined-ca-bundle.pem',
      ),
  ),
);


The problem is that this will work as OR, not as AND, so one or the other will make it pass:

'#states' => array(
  'visible' => array(
    ':input[name="type"]' => array(
      array('value' => '29'),
      array('value' => '30'),
    ),
  ),
),

This will do AND, however because you cannot have 2 array keys the same, you run into trouble:

'#states' => array(
  'visible' => array(
    ':input[name="type1"]' => array(
      array('value' => '29'),
    ),
    ':input[name="type2"]' => array(
      array('value' => '30'),
    ),
  ),
),

Since the array keys you see there are just jQuery selectors the key is to use 2 different selectors that apply to the same field. For example, something like this might work:

'#states' => array(
  'visible' => array(
    ':input[name="type"]' => array(
      array('value' => '29'),
    ),
    '.form-item :input[name="type"]' => array(
      array('value' => '30'),
    ),
  ),
),

This assumes your type field is in a .form-item div.
There would be a number of possibilities here depending on your markup.

However, making something show when 2 different radio buttons are checked at the same time is impossible because you can only check one at a time.

If you were using checkboxes you could make it so that line only showed if type was 29 AND 30 by doing this:

$form['type'] = array(
  '#type' => 'checkboxes',
  '#options' => array(
    '10' => '10',
    '29' => '29',
    '30' => '30',
  ),
  '#title' => '',
);

$form['line'] = array(
  '#type' => 'radios',
  '#options' => array(
    '1' => '1',
    '2' => '2',
    '3' => '3',
  ),
  '#title' => '',
  '#states' => array(
    'visible' => array(
      ':input[name="type[29]"]' => array(
        array('checked' => TRUE),
      ),
      ':input[name="type[30]"]' => array(
        array('checked' => TRUE),
      ),
    ),
  ),
);


How can I display sql query from database?

From the error, I assume your code is in a controller? In that case, take note that you should return a render array or an object inheriting the Response class, not HTML.

In your case, just do:

return $items_array;

instead of

return render($items_array);

But wait!

The table render array should be constructed this way:

$items_array = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
);

For a reference of what you can pass in, check out https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21table.html.twig/8.1.x

Other notes

The way you are querying data is not wrong per se but definitely not the "Drupal way". To perform queries using Drupal's DBAL, check out https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!database.api.php/group/database/8.2.x


How do I disable Twig and block cache for a specific module?

You can control the cache in the render array with the #cache element.

To disable the cache add:

$build['#cache']['max-age'] = 0;

In this case the block will not be cached for logged in users or anonymous users with a session.

If you want to disable the cache for anonymous users without a session:

  Disable it either by uninstalling the page_cache module completely or
  by triggering the kill switch, see
  How can I prevent a particular page being cached? for example.

The caching of the twig code is not connected to this, the twig code is only cached once, the first time it is used after you cleared the cache.

(edit acc. to comments of Berdir)


Where are the "Publishing options" for a node stored in the database?

It's the status field in the node table (in Drupal 7).


How to programtically queue a function for 48 hours (to change webform Author)

Implement hook_webform_submission_insert() such that it saves $node->nid, $submission->sid and the current time to a designated table (e.g. newsubmissions).

Implement hook_cron() such that it goes through all records in the newsubmissions table, that are more than 48 hours old. For each such record, you should

load the submission by calling webform_get_submission(),
change the owner of the submission,
save the submission by calling webform_submission_update(),
delete the record from the newsubmissions table.

Implementing hook_webform_submission_presave() the same way as hook_webform_submission_insert() will not work, because

$submission->sid is not yet set and
hook_webform_submission_presave() is also called for old submissions.


Using Bootstrap theme and anonymous user, ajax form submit results in "call to undefined function bootstrap_form_process"

This is similar to https://www.drupal.org/node/2369635, i.e. you need to include /path/to/bootstrap/includes/process.inc in your codebase.  The easiest way IMHO is in a hook_init() somewhere.


How to create a user with field collections programmatically?

I think following code should give you an idea.

    //Create a field collection entity
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_personal_details'));
    $field_collection_item->field_firstname[LANGUAGE_NONE][0]['value'] = "Yassin Tahtah";
    //$field_collection_item->field_firstname['und'][0]['value'] = "Yassin Tahtah";
    $field_collection_item->setHostEntity('user', $user);
    // Save the entity.
    $field_collection_item->save(TRUE);


Sort related nodes in block views based on a score calculated with common vocabulary

To place the php code to calculate the score there are several approaches:

Add an extra field for the score to your content type and calculate it in submit or
presave.
Add a custom views field plugin:
http://enzolutions.com/articles/2015/10/11/how-to-include-php-code-in-drupal-8-views/ or a custom sort plugin: https://chromatichq.com/blog/create-custom-views-sort-plugin-drupal-8
Use the module Computed Field.

With (1) you save the value in the database. This is best for calculations that don't change after saving the content.

A custom views plugin (2) is more dynamic and needs no space in the database, but it has to be recalculated each time.

The extra module (3) can do both, but it is not ready for production, still in alpha. If you read the linked how-to for views field plugins in (2) there are some good points that in D8 plugins are often more powerful than contrib modules to extend Drupal with custom php code.


How to rename a view returned by REST API

The answer was already in the question.  Turns out the option to add aliases is exactly the same for other fields...it's just a little counter intuitive. Go to Administration-->Structures-->Views--> Constants view --> Edit --> then select "Constants" from the "Displays" Then select "Settings" next to Show... All the aliases can be entered there.  Then save the changes.  Now you can reference the view by alias rather than the view_[ID] reference.


Can I override/modify an existing hook_widget_info for an existing CCK field type

You can do that with hook_field_widget_form_alter

hook_field_widget_form_alter(&$element, &$form_state, $context)

  Alter forms for field widgets provided by other modules.

The function parameters there allow you to check and target specific cases as needed.


How to Begin a French Version of My Site?

Drupal support multi-language websites and creating a multi-language site is very easy.

You can configure a Drupal website to use a language other than English and you can configure a site to use multiple languages.

If your site requires the interface to be displayed in multiple languages or if you need to customize the interface of a single language site, the first step is to enable the multilingual capabilities of Drupal.

You can also configure a Drupal site to allow your users to switch languages and you can translate content into multiple languages.

Helpful Resources:

Multilingual Guide Tutorial
Building a Multi-Language Site
How To: Basic Internationalization Setup
Translating Site Interfaces
Translating Content Contributed Modules for Localization and
Internationalization
Core Modules for Localization and
Internationalization
Cookbook: Build a Non-English D7 Website
Localization API
Internationalization (i18n) module
Book: Drupal 7 Multilingual Sites (Kristen Pol)

Videos:

Building a Multilingual, Multidomain Drupal Site
Multilingual Site Setup and Management
Multilingual Module Madness! Which i18n Modules Do You Really Need?

Getting Started:

Localized Drupal Distribution: A small distribution to install Drupal with user interface translations pulled automatically from localize.drupal.org. It is suggested you use this distribution to start off with Drupal if you'd like to set up a localized site.
Internationalization: This is a collection of modules to extend Drupal core multilingual capabilities and be able to build real life multilingual sites.
Internationalization (i18n) Submodules: A collection of submodules that provides extended multilingual support for Drupal. Each module addresses a specific functionality.
Apache Solr Multilingual: The goal of this project is to cleanly extend Apache Solr Search Integration to provide: better support for non-English languages, support for multilingual search, cross-language information retrieval (CLIR), and an easy-to-use administration interface. Apache Solr Multilingual does not replace Apache Solr Search but is based on it.
Related Modules: A list of additional contributed Drupal 7 modules that extend Drupal's multilingual features


Drupal 8 uses twig templates so variables are handled/printed in different way.

Node links sections is handled separately because of which we can not hide/remove statistics in node.html.twig file. So to print node statistics count in submitted area, you'll first need to add that to base level of node template like content, author_picture, etc. You can do this by implementing template_preprocess_node() in your theme. Below is sample code which adds new variable containing node statistics count.

function [THEME_NAME]_preprocess_node(&$variables) {
  // Get statistics count for current node.
  $statistics = statistics_get($variables['node']->id());
  $variables['node_stats'] = \Drupal::translation()->formatPlural($statistics['totalcount'], '1 view', '@count views');
}

Change THEME_NAME with theme you're using. This will add node_stats variable which you can use inside node.html.twig file for printing node statistics count. Below is how you can print it inside template file.

{% if display_submitted %}

    {{ author_picture }}

      {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}

      {{ node_stats }}

    {{ metadata }}

{% endif %}

This will print the node statistics count in submitted area of content. Links section will still show the node statistics count, to remove this, you will need to create new template file (if not already created) named as links.html.twig. You can copy existing file from "Core => themes => classy => templates => navigation => links.html.twig". After which you can exclude the statistics count from printing. Make sure to rebuild cache after adding new template file. See sample output below:

    {%- for key, item in links|without('statistics_counter') -%}

        {%- if item.link -%}
          {{ item.link }}
        {%- elseif item.text_attributes -%}
          {{ item.text }}
        {%- else -%}
          {{ item.text }}
        {%- endif -%}

    {%- endfor -%}

We've removed statistics count from links while printing using without() function links|without('statistics_counter')


This is more or less the default behavior, depending on your Languages Detection and selection configuration.

In Drupal 7 every translation of a node is a new node, with its own node ID. So when you call for that node it will be displayed (call it by node/[nid] or a path alias).

Interface language (menus etc) is calculated separately from content, by the Detection and selection settings (/admin/config/regional/language/configure).

The most common setting is to only enable the URL Detection method and configure your default language not to use the Path prefix language code or Language domain and set one for all the other languages.

This way if you have an English node and you want to open it with a French interface the link should be constructed as:

/fr/node/[englishID]

or

/fr/[french-path]/[english-title-pattern]

So whatever method you're using to display node lists you have to adjust their URLs output to follow that logic.


Saving a field of type 'text_format' as a theme settings variable

Text format fields are considered to be a compound field (meaning that multiple values are stored for the one field -- the value and the format).

If you inspect the value of mytheme_texte_presentation, you'll find an array that looks something like this array => ['value' => '<val>', 'format' => 'html_restreint'].

If you look at the docs for text_format, you'll see that there is a #format attribute.

Your code should look something like this:

$texte_presentation = theme_get_setting('mytheme_texte_presentation');
$form['mytheme_texte_presentation'] = array(
    '#type'          => 'text_format',
    '#title'         => t('Test theme settings'),
    '#default_value' => $texte_presentation['value'],
    '#format'        => $texte_presentation['format'],
    '#description'   => t("lorem ipsum"),
  );

Note: This is untested code. You may need to tweak this a bit to make it functional.


Installation profiles: add module/theme search path?

Currently, there is no way to "inherit" that way between profiles. My team uses a small script that symlinks the modules directory from the base profiles into the modules dir of the subprofile, to solve this.

So the structure becomes

profiles/base-profile/modules
profiles/base-profile/modules/ctools
profiles/sub-profiles/modules/modules         <-- Symlink to base-profile/modules
profiles/sub-profiles/modules/modules/ctools  <-- From symlink
profiles/sub-profiles/modules/views


How to add prefix (label) and postfix to commerce price field

I'm not 100% that I understand your question correctly but I assume you need to add prefix & suffix to your commerce product prices. In that case, Drupal Commerce Extra Price Formatters does exactly that, have you tried using this module?


How to access jQuery plugin added through libraries API

Found the problem - this library comes with two separate files, one that is a straightup javascript library and another in jquery that registers the file as a plugin (smallworld.jquery.js)

  $.extend($.fn, {
    smallworld: function (options) {
      var opts = $.extend({}, $.fn.smallworld.defaults, options);
      return this.each(function () {

      $(this).data('smallworld', new Smallworld(this, opts));
      return this;
    });

To get this to work, I had to take the whole 'register' script and add it to the jquery file script I created for the module, ex:

(function ($) {

  Drupal.behaviors.smallworld = {
    attach: function (context, settings) { ...


How to migrate data from custom user account fields to a single new field?

Step 1: Create a Rules Component

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

{ "rules_search_and_replace_values_in_some_user_account_fields" : {
    "LABEL" : "Search and replace values in some user account fields",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "user" ], "field" : "field_accept_boolean" } },
      { "data_is" : { "data" : [ "user:field-accept-boolean" ], "value" : "1" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "user:field-accept-list" ], "value" : "yes" } },
      { "drupal_message" : { "message" : "Boolean field converted to list field for user with id \u0022[user:uid]\u0022 and name \u0022[user:name]\u0022." } }
    ]
  }
}

Some more details to further explain the above above example:

This Rules Component will be used in the subsequent step.
In my case I have a boolean field with machine name field_accept_boolean (values true or false, of course) and a list field with machine name field_accept_list (values yes, no, later).
If field_accept_boolean = true, then the value of the field with machine name field_accept_list will be set to yes.

Note that I also added the Rules Condition Entity has field to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of the fields to match the machine name of your fields, and then you can simply import this Rules Component in your own environment.

After you did this, you can navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some User identifier and hit the Execute mode. Depending on the user id you selected (if it has that field, and if the Rules Condition is satisfied), your user will be updated.

After you're confident your rule works perfect for all variations of your users, move on to the next step below.

Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your users to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

Attention: to process many users at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Step 3: 2nd iteration

With the previous Step 1 and Step 2, all users who have field_accept_boolean = true will have their field_accept_list will be set to yes.

If appropriate, just adapt your rule in Step 1 (or clone it to a 2nd Rules component) so that all users who have field_accept_boolean = false will have their field_accept_list will be set to no. Then repeat Step 2 (with this updated Rules component).

After doing so, ask yourself if there could be any users with a value for that field_accept_boolean which was never assigned either value. For those users, you may want to use yet another variation of Step 1 and Step 2, to have their field_accept_list will be set to later.

Of course, you could have multiple fields similar to field_accept_boolean, which you might either migrate to the same field_accept_list (maybe with another value?), or a yet another field. For all thee variations it's just a matter of tuning the Rules component in Step 1, and then performing Step 2 again.

Step 4: Straight forward variations

There are dozens (hundreds?) of straight forward variations of this question that can also be solved using the above combination of VBO and Rules. To just mention 1 of them, have a look at my answer to "How to bulk delete selected content/nodes?" ...

Happy VBO-ing while Rules-ing!


The template you have overwritten looks like this (in Drupal 6):

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

As you can see, it's purely used to print out the rows in the view; you should instead use one of the other templates available, if you want to alter the fields. Take a look at the theming information button in the UI that will give you a complete list with previews.


Modify user submitted form data before it is saved an emails are sent

You maybe able to add a submit handler or validate handler.

How do I add an additional submit handler in commerce checkout form?

https://stackoverflow.com/questions/15375616/how-to-use-form-validation-in-drupal-7

See the form examples >  https://api.drupal.org/api/examples/form_example!form_example_tutorial.inc/7


Move Drupal site from localhost to remote production server

You can follow this steps and move your site to production server:
On your local site

Install Backup and migrate, which will take the backup of the database (admin/config/system/backup_migrate).
Install Backup and migrate files which will enable you to take a backup of your public files in the directory defined at admin/config/media/file-system.

On the production server

Install fresh copy of Drupal.
Copy the modules and themes from localsite's sites/all/modules and sites/all/themes to the respective folders on the fresh install of dev server.
Enable the Backup and migrate module and backup and migrate files module.
Go to admin/config/system/backup_migrate/restore and restore the backed up database and public files which you exported at your local site.


Webform Build Tab not displaying correctly

You need to enable the Webform UI module.


I use webform 7.x-3.20 it doesn't give text box option for date field rather it show select list except for year. If in your case it showing textbox make sure the configuration is as followed.

You can create new date format under date and time settings, Go to admin/config/regional/date-time/formats

Add new format in the form j/n/Y it will show date as 30/7/2014.

Under webform date field setting choose the Default value timezone to "Website timezone"

P.S If you want to reorder select boxes then see: Re-ordering the elements of a Drupal Webform Datepicker


How to create content type programatically

To create a node type, call node_type_save(). Have a look at the documentation of the Fields API for information on how to attach fields to the node type.


how to set complete site background to a color or image?

Try applying same for body tag !

body {
      background: yellow;
    }


Dynamically create fields based on integer value

you should look into
Licensing

This module is useful for people that plan on integrating a software
licensing system on their site.
Features Out of the box, it provides the following:

Ability to generate, edit & delete unlimited unique license keys.
Ability to export your keys into a CSV document, which you can mail merge and distribute with physical copies of your product.
Ability for users to 'register' their key when they sign up for a drupal account, or by visiting a page when logged in.
Users can have multiple keys registered to one account, and they are all displayed on their user page.
Provides views functionality for default and custom reports.
Brandable license keys like XXXX-BRAND-XXXX-XXXX-XXXX
This module does provide functionality out of the box, however - it's power is in the hooks it provides which allow you to extend this
further.

Commerce Product Key

This module lets sites implementing the Commerce module, attach
product keys to orders. Product keys / Vouchers are strings of text
that are used to unlock or activate a piece of software.


How can I exclude links to untranslated pages from Google search results?

When using i18n xml sitemap, and when you have a menu set to be included in a sitemap (using xmlsitemap menu), even if that menu is set to display only for one language (localized to Japanese or English in my case using i18n_menu), it will still get added to the sitemap for both languages.

So, in this case, one solution is to avoid using xmlsitemap_menu and instead use xmlsitemap_node and add the node links individually.

Painful but it works.


Commerce minimum quantity and purchase multiplier

Ryan's answer on this question is the approach you'd want to take:

Install Commerce Custom Product.
Create a new line item type that has new quantity select field and widget. Expose this to the add to cart form.
Hide the regular quantity selection to the add to cart form.
Use a rule to take the value in the field you created in step 2 and set the quantity field to that value on the line item.


Updated >= Drupal 8.0.5+: Rendering forms/entities programmatically on theming level

I'm still new to drupal but here is what i did to render a form in node.html.twig:

//file themename.theme
function themename_preprocess_node(&$variables) {
  if(isset($variables['node'])){
    $node = $variables['node'];
    if($node->getType() == 'application') {
        $message = \Drupal::entityTypeManager()
            ->getStorage('contact_message')
            ->create(array(
            'contact_form' => 'webentwickler_job', //ID(Machine name) of form
        ));
        $form = \Drupal::service('entity.form_builder')->getForm($message);
        $variables['application_form'] = $form;
    }
  }
}

//file node--application.html.twig
{{ application_form }}


Thanks for asking...monymirza.
 finally i find the solution .

After adding the product instead of save click save and continue it will lead to edit page whre we can add stock numbers..


Charge user after status of order is changed with eCommerce

You can use a payment gateway that allows for Authorization Only transactions. This will authorize a certain amount, but will not actually charge the credit card.  This is what gas stations, hotels, etc. do. They charge a preset amount, and then finalize the actual amount later.

commerce_authnet offers this capability. In the settings for the payment gateway you just set Authorize Only.

Once the administrator is ready to finalize the payment, they would go to the Orders page, and choose Payment on the Order.  You then 'capture' the amount to finalize the payment.

You can fine tune who has access to the Payments page on the Permissions page.


The login step creates a user via the Drupal API, and logs in by manually submitting the form.

When you run from within the Vagrant machine, the process presumably has access to bootstrap Drupal, and create users. When you're running from your local machine, I think only 'blackbox' tests (eg, ones that don't require API access) will work.

One potential workaround for this would be to specify in your local behat file:

api_driver: drush
drush:
  alias: 'vagrant'

and then ensure your local machine had a drush alias @vagrant setup so that you could access your vagrant Drupal instance from your local machine.


What is the difference between State API vs UserData API?

You find real world examples for State API in the key_value table under the collection state:
comment.maintain_entity_statistics
field.field.deleted
install_time
locale.translation_last_checked
search_api.index.default_index.has_reindexed
system.cron_last
system.maintenance_mode
update.last_check
webform.version

The first part of the name is usually the module. In these examples they are core and the popular contrib modules Search API and Webform.
In contrast UserData API is obviously specific to the user, not the entire system. You would use it for data you don't want to store in a user field. Because it is easy to add user fields in code and config this service is rarely used in Drupal 8+.


Inconsistent behavior with user_logout function

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

  no_cache: TRUE


Why is theme.inc looking for view template in calendar module

I cannot reproduce this myself but take a look at

https://www.drupal.org/node/1091376

It is an old ticket but is for the  7.x-2.x-dev branch and basicly it says disable your module remove the module directory and reinstall it so something like

Will disable the module.

 drush dis calendar

Will uninstall the module (if the module has a uninstall hook)

drush pmu calendar

Remove the directory

rm -rf __custom_path__/sites/all/modules/calendar

Most likely not necessary but wont hurt but will rebuild the registry and clear all cache

drush rr
drush cc all

Download the newest version of the module

drush dl calendar

And enable it.

drush en calendar

It should remove all traces of the old calendar and add a clean copy/install.

I would also do a drush updatedb just to double check if after all that everything is still in order.


Login fails due to loop on localhost. Any ideas why?

You could find out for sure by adding some logging code in drupal_goto() to backtrace what function fired the redirect. Then inspect why that function fired the redirect and work back from there.

Or, some more "guesswork" approaches -

Check you don't have $base_url set in settings.php.
Clear your cache tables after installing to copy (or don't back up the cache table contents).

drush cc all

Disable modules which might be confused by relocation - securepages, canonical_url, logintoboggan (guessing here).

drush dis securepages canonical_url logintoboggan

Check your variables table for (and delete) any entries with values like '%http://your.old.domain%'.

drush vget | grep your.old.domain

drush vdel some_variable_name


Module dependent on field configuration in another module

Updating Drush solved my problem...
I went from 8.1.16 which I used deliberately due to it's compatibility with D7 & 8 as I'm still working with lots of 7 sites. After updating to 9.4.0, the field's storage config in the site's configuration directory gets imported no problem.


Remove a content type from search results

Drupal's contrib module Search Restrict is a lightweight module that just does the basics - it allows administrators to restrict by role who can search for each content type. It may be a better option than Search configuration in that it only does what you're asking for - restrict content types from search results based on a user's permissions. If you're looking for something more configurable, Search configuration may be the way to go.

From the module's page:

  Approach of this module is to re-write the search query, so that
  content is indexed and available as search results to users in role(s)
  that have permissions to view it, but not displayed to other roles.
  Integrates with Apache Solr to exclude results based on the role of
  the person searching.

Simply download, install, and enable the module. Then to restrict (by role) which users can search which content types, edit each Content Type individually and there will now be a 'Search Restrict' section option (below the Display Settings). It allows you to specific, for each content type, which roles can search nodes of that content type.


Admin menu for client, each menu for each content type

Since you just need a few links, I would use the Shortcut module which is a Drupal 7 core module. The documentation on this is pretty good: https://drupal.org/documentation/modules/shortcut.

You can configure under user permissions whether the user can edit the menu themselves or not. You can have different shortcut menus for different users.

Out of the box, you can only have 7 shortcuts on the shortcut bar at one time. There appears to be a patch for this, but I haven't tried it yet myself: https://drupal.org/node/682000#comment-6493066

However, to display the shortcut toolbar, it appears you have to expose the Admin toolbar to that user. You can make the admin toolbar pretty minimal by just giving the tool bar and create content permissions to the user.

If you really don't want to expose the admin toolbar to this user at all, then you might want to go with a menu block that only this user sees (set under block config>Roles). Your user would need to be given a unique role for this (which other users are not given). This assumes you have the Menu, Block and Menu Block modules installed.


Different rankings in a view based on geolocation

I think Smart IP module is help you to solve your query.

OR

Check IP Geolocation Views & Maps or Session Cache API module.


how to resize image programatically with theme image

You need to use theme_image_style() for that one:

$image = theme('image_style', array(
  'style_name'=> 'small',
  'path' => $file->uri,
  'alt' => 'user picture'
));


This depends on the purpose of the content. Provided that it is just administrative content, you could just use the admin user (UID = 1). If the content needs to relate to another user, then you should use them as the author.


"Theme info" checkbox not showing on non-admin pages

Apparently, someone wrote a module in the project to unset the default Drupal JavaScripts. Just had to remove that code to make everything work the way they should.


Is Drupal 8 with views in core stable enough to be used as a simple blog?

The real question is: what's the Drupal core lifecycle look like?

First, we have feature thaw. During this time it's really a bad idea to even try to build anything on it. It's likely to be broken, buggy, and so on. (Although now we have extensive test coverage so it's less broken than you'd think.)

Then there's a feature freeze. People with some knowledge, patience and not too important sites -- say, a blog :) -- could start testing. It'd be great if this happened. You need to understand that there is still no guarantee that your data can stay intact from one git pull to the next. (This is where we are now.)

The next step is beta. From beta and on we support upgrades. So while it's not the quality you'd expect from a released product, it's time to begin serious testing. If you start testing when release happened, your problems will take a lot longer to be fixed.


How to programmatically add content to a group in the Group Module?

Given you have the group entity and node entity, you can simply create a GroupContent entity.

$groupEntity = ... The group entity.
$node = ... The node entity.

$type = $type = $groupEntity->getGroupType()->id() . '-group_node-' . $node->getType();

$groupContentEntity = \Drupal\group\Entity\GroupContent::create([
    'gid' => $groupEntity->id(),
    'entity_id' => $node->id(),
    'type' => $type,
]);
$groupContentEntity->save();


How to rewrite Views filter URLs when based on an aliased node URL?

Have a look to Query Parameters To URL, I believe it fits your need :

  This module provides the ability to rewrite URL query parameters into Clean URL components on specified paths.

  An example of a dirty URL like that could be:
  example.com/events?field_category_id[0]=100&field_category_id1=101&field_author_name[0]=John

  Using this module you can transform the URL into:
  example.com/events/p/field_category_id/0__100--1__101/field_author_name/John


In Commerce 2, how can I load an order item's 'purchased entity' object given its ID?

If your $order_item is an instance of the OrderItem class you should be able to do:

$product_variation = $order_item->getPurchasedEntity();
$title = $product_variation->getTitle();

If you have an $order you should be able to do:

foreach ($order->getItems() as $order_item) {
  $product_variation = $order_item->getPurchasedEntity();
  $title = $product_variation->getTitle();
}


I saw a similar post.

Just a quick behind-the-scenes tidbit here: Drupal Commerce separates out its internal Order ID from what you see on the front end as the Order number. The Order ID is a serial numeric value that increments with each order created (including orders that are still shopping carts). The Order number can be any alphanumeric string, but it initialises to be the same as the Order ID. (Some sites then update orders upon creation to use a special alphanumeric order number format instead of the regular integer format.)

What you want to change is the AUTO_INCREMENT value on the commerce_order table. This will make it so the next created Order ID will start with the increased AUTO_INCREMENT value. By default when you create a new site, this will be set to 1, but feel free to set it as high as you need it to go. This is especially important if you're migrating an old site but using the same payment gateway, as they sometimes don't support the same order number being used twice.

The query to update this is:

ALTER TABLE  `commerce_order` AUTO_INCREMENT = 1000;

Where 1000 is replaced by whatever number you need the next created order to start at. This won't affect any existing order, just the next order to be saved to the database.


Product reference add to cart form shows only add to cart button

First be aware that Commerce is still in Alpha, so behavior might change between versions!

I suppose you are looking for something like this from the Drupal Commerce Blog.

I have no idea how to get there as I am awaiting a more stable version of Drupal Commerce, but I suppose the breadcrumb in the image should give you some directions on where to find these settings.


Passing current node ID to the block template

The proper way to do this would be use contexts. Plugin contexts, not cache contexts.

Similar to NodeType condition plugin, put something like this in your plugin annotation:

* context_definitions = {
*  "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }

And then get the node using $this->getContextValue('node').

This has two advantages:

Your block doesn't rely on global state directly. It could for example be used also in page manager, with a different node.
Drupal automatically understands that your block varies by whatever node is passed in. If using the current node, it will vary by route, if it would e.g. be a node from a static page manager context, it wouldn't. It will also include cache tags, in case the node is changed in a way that would affect your output.


Make variable available in template file

You can override template_preprocess_views_view_table() in your own THEMENAME.theme file

function THEMENAME_preprocess_views_view_table(&$variables){
   $variables['node1'] = "value from node 1";
}

in your twig file you should have the variable available

{{node1}}


How to display a colorbox only one time when a page loads

I would suggest writing a cookie after showing the login form and checking if the cookie exists before that. For cookies there's a nifty jquery plugin as well - no big programming involved on your side.
HTH


Taxonomy Access Control - access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.


How to display unpublished contents in views for all the users?

Add Permission - Workbench Moderation : View all unpublished content.


It's the abstract way of referring to the node table in the database.  This notation is converted by Drupal to the real name of the table right before the query is executed (in most cases, for most configurations, {node} will simply become node at execution time).  Using this notation allows an instance of Drupal to use table prefixes without the code generating the queries having to know anything about those details.

The table name has the appearance of being repeated ({node} node) so that the table name {node} gets mapped to an alias node that can be used elsewhere in the query.  Consider if you have configured your site to use a table prefix of "dev_" then SELECT node.status FROM {node} node... would get translated to SELECT node.status FROM dev_node node..., thus allowing your node.status field to refer to the correct table without the code generating the query having to know anything about the fact that there's a table prefix configured for the site.  For this simple example it's silly because you could just write {node}.status, but for more complex examples, particularly with multiple joins it can be useful to set up the alias.


How to add sorting option to a field in views bulk operation

This has nothing to do with VBO. It is simply a setting in the "Table" format. To achieve this:

Click "Settings" besides "Table" format.

And select which field you need to make sortable.


How to modify display of image form metadata after upload on node edit form?

Here's the answer, which I discovered after some further research:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an an image on a slideshow
  if (isset($context['form']['type']['#value']) && $context['form']['type']['#value'] == 'slideshow') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = '_MYMODULE_image_field_widget_process';
    }
  }
}

function _MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the way metadata form fields are displayed;
  unset($element['title']['#description']);
  unset($element['alt']['#description']);
  $element['title']['#weight'] = '-4';
  $element['alt']['#title'] = 'Description';
  // Return the altered element
  return $element;
}


Drupal View Filter Criteria "Contains Taxonomy"

Add a Relationship of type "Terms in node"
Add a filter "Taxonomy term: Name"

Now you can set "Contains" has an option for your filter


Passing arguments into hook_block_view in custom module

If you need to pass a variable into a block, maybe you should try using template_preprocess_block ?

Inside this function you define your variable and afterwards in your block you use it.


I have found the solution.

Initially, my site is in English(source language).

We have to switch the language to other languages on the site(in my case it is Dutch) using this path admin/config/regional/language. Then, we have to view the page which is consists of t(). Then only the t() strings would register for translation.

Now go to admin/config/regional/translate/translate and search your t() string, it will be available and add translation !!!


Modify/Alter Password Policy Constraints Text

Short answer:

Of course there is a module for that.

Actually, more than one:

https://www.cmsdrupal.com/blog/how-implement-custom-password-policy-drupal
https://dev.acquia.com/blog/password-policies-and-drupal/03/04/2017/17856

Longer answer:

Since you don't just want to change the policy (you want to change the form markup too) you might also need to use hook_form_user_login_block_alter(&$form, &$form_state, $form_id).


D6 to D7: How can I get all the migrated content to have the "Text format" of "Full HTML" for the body

You should try to set the input format on the body field in this way:

$this->addFieldMapping('body', 'body')
 ->arguments(array('format' => 'full_html'));


How to know node/entity ID from a submit handler?

I would recommend not to use extra submit handlers on node forms. Forms are not the only way that you can create a node. Modules like Feeds, Migrate, etc can create nodes programatically.

If it's a node, and you don't want to alter data that the node itself, implement hook_node_insert and you have access to the whole $node object!
$node->nid would be the node ID if you name your function's first argument as $node.

If you prefer an extra submit handlers, you can access node or entity that is being created/updated in $form (I can't remember the exact key name though).

Install Devel module. Then, you can see what's in the $form array in your submit handler like this:

function mymodule_extra_submit_handler($form, &$form_state) {
  dpm($form); // pretty-prints the entire form.
}

Usually $form['#node'] is the node object, so nid is $form['#node']->nid


Why Are Changes / Updates to User Account Fields Not Persisted (Lost on Page Refresh)

Turns out it was down to Clientside Validation modules. I disabled the following and it now works as expected:

clientside_validation_fapi
clientside_validation_field_validation

The other clientside validation modules work fine, just these two seem to block updates to user accounts with no errors, warnings or notices.


Contact form block with data from the page the blocks featured on

If you don't want to write custom theming and you want less coding, you need to create a custom page with 2 columns using panels module.

Install the panels and ctools modules if you don't have.
Enable Chaos tools, Page manager and Panels.
Create a custom page at admin/structure/pages/add with the path "estate/%node" which will be a new mirror page of the existing path "node/%node".
Assign Node: ID context to the argument %node.
Choose two column layout.
Add Existing node to the left column. To use a NID from the URL, use %1 in the title box.
For the right column, add the contact form from Widgets.

To get node information in the contact form, you need to write a hook hook_form_FORM_ID_alter in your custom module using the argument NID.
You can study custom moduling here.
Here is the example code snippet.

<?php
/**
 * Implementation of hook_form_alter().
 * @see http://api.drupal.org/api/function/hook_form_alter
 */
function yourmodule_form_contact_mail_page_alter(&$form, &$form_state, $form_id) {

    if(arg(0) == 'estate' && is_numeric(arg(1)){
        $node = node_load(arg(1));
    }

}
?>

You can also see how can you customize the contact form here:
http://www.metaltoad.com/blog/how-add-field-drupal-contact-form
http://www.isegura.es/blog/modifying-contact-form-drupal-how-add-field
http://www.pensamientosdivergentes.net/blog/modifying-contact-form-drupal-how-add-field

The drawback of this solution is you have to use the new path "estate/%node" to the node view page instead of using the default existing path "node/%node".
Any better answer is welcome.


To remove the And title you need to implement hook_form_alter(). It would look something like this.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state){
  if ($form['#id'] == 'views-exposed-form-search-page') {
    unset($form['field_price1_value']['max']['#title']);
  }
}

You will also need to find out the $form['#id'] so that your code doesn't attempt to change all exposed forms generated by views. Install the Devel module and run.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  dsm($form['#id']);
}

The devel module will now set a message with each views exposed form and it's #id. Copy that and replace views-exposed-form-search-page in the first code example. After that you can add a dsm($form); to find out what your field name is called in the array (to replace field_price1_value).


What is wrong with this drush command in Drupal 7 Ubercart 3 to delete orders in bulk via command line?

You've to use double quotes instead of single quotes, so variables retain their special meaning.

Read more:

https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash


How to skip creating records with blank fields when migrating from csv file?

in your prepareRow function test to see if a field is empty and if it is, return FALSE.  For example:

public function prepareRow($row) {
  if ($row->data == '') {
    return FALSE;
  }
}


limit validation button on visible state textfield?

I would personally prefer a form-validation-function, which seems for me the ideal solution...
But since you're using custom validators, you can check the value of your unit-field in there:

The second argument in your custom element-validation-function is the form_state-object, with that you have access all form-values. (eg. $form_state['values']['unit'])
Check the value of the unit-field in both validation-functions, depending of it's state do or skip the validation.

Example:

   function price_percentage_validate($element, &$form_state, $form) {
        if ($form_state['values']['unit']>0) {
            /* your validation code */
        }
    }
   function price_validate($element, &$form_state, $form) {
        if ($form_state['values']['unit']<1) {
            /* your validation code */
        }
    }


for D8, How to skip (don't update) some fields from existing entity during import if this field already has a value

To import only a single field, or possibly multiple, use "overwrite_properties".

  overwrite_properties: If the migration has specified a list of properties to be overwritten, clone the row with an empty set of destination values, and re-add only the specified properties.

destination:
  plugin: 'entity:node'
  overwrite_properties:
    - field_name

Source:  Drupal\migrate\Plugin\migrate\destination


Drupal - block deleted - how to retrieve

The problem was that the new block the user created had a block number of "8", whereas the original block that was deleted had a number of "2". The fix was to go into custom themes for the homepage, edit page.tpl.php, and change the "module_invoke" to refer to the correct block


How can I replace a value already present in the database?

As @kiamlaluno mentioned db_insert() inserts a new row in the table. You can use db_update(), to update the row if it already exists. You can use db_merge(), to combine both of them.
See the example (taken from the documentation):

db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
    ))
  ->execute();

  In the above example, we instruct the query to operate on the "example" table. We then specify one key field, 'name', with a value of $name. We then specify an array of values to set.

  If a row already exists in which the field "name" has the value $name, then fields field1 and field2 will be set to the corresponding values in that existing row. If such a row does not exist, one will be created in which name has the value $name, field1 has the value $value1, and field2 has the value $value2. Thus at the end of the query, the end result is the same regardless of whether or not the row already existed.


Rather than use a field for polling, I would recommend using a polling entity created by a module specific to polls. There is a core poll module.

There are also many contributed modules, the choice would depend on your use case: Advanced Poll, Poll Improved, Poll Extras -- and Poll Blocks provide a block for every core poll.

Then add some theming to make the selections draggable. I have created front-end doodads that populate a hidden element on the page - even an entire node body - so you could register the selections that way if you cannot theme the actual poll items.

You may need to use panels/views/context or template file to add the poll to your page.

My favorite place to search for Drupal contributted modules is http://drupalmodules.com/search/node/poll


If you want to create tabs use this module: http://drupal.org/project/tabs

else you can modify the tab wrapper in your page.tpl.php and then costumize your tabs with the api functions, to see more read:
http://api.drupal.org/api/drupal/includes--menu.inc/function/theme_menu_local_task


How can I make my Drupal website automatically reflect the changes when the DB values change?

The settings you are referring just tell Drupal to use the cache_page table.
See drupal_page_footer() that contains the following code.

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

For the fields, there is the cache_field table (cleared by field_cache_clear()), which is used from the field CRUD API, but also from the field attach API, which includes functions like field_attach_load() or field_attach_update(). If you are writing a field table without using one of the field API functions, such as in your case, then you need to clear the field cache; if you look at the code of field_attach_update() you can understand exactly which cache ID you should pass, to avoid clear all the cache for no reason.


Ok, now with this code I have my image doing the animation/transition that I wanted, moving down smoothly:

CSS:

.penduricalho{
  background-repeat: no-repeat;
  position: relative;
  top: 0px;
  left: 200px;
  margin-bottom: -500px;
  display: block;
  position: absolute;
  z-index: 2;
  height: auto;
  margin-right: auto;
  margin-left: auto;
  overflow: hidden;
}

.penduricalho:hover{
  -moz-transform: translateY(50px); /* Firefox */
  -webkit-transform: translateY(50px); /* Safari | Chrome */
  -o-transform: translateY(50px); /* Opera */
  transform: translateY(50px);

  -moz-transition-duration: .5s;
  -webkit-transition-duration: .5s;
  -o-transition-duration: .5s;
  transition-duration: .5s;
}

HTML:

Run it here if you want to see the result:

https://jsfiddle.net/sn1hs9hp/


How to create a separate theme for a custom page?

To create a custom template for node/123, copy your theme's default page.tpl.php to a file named page--node--123.tpl.php (D7) in your theme's or subtheme's templates/ directory, and then edit it to do any customization.

To do custom theming, add custom classes where you need them in the custom template, and then add the CSS to style those classes.

Btw.: I usually do this by creating a sub-theme, to avoid any customization from being overwritten when the super-theme is upgraded.

PS: If your page really has the path example/123, the name of the template overide file should be page--example--123.tpl.php

Remember to clear the cache after doing this.    Until you do, your override will not be visible.


Commerce discounts by day-of-week and by age

You can use rules for first requirement. You will need to add PRODUCT PRICING rule & check the day in condition. Just multiply the base price by .5 & you can apply what you wanted..
Anther things are user role based, so if a user has role of student in condition then do the same in another PRODUCT PRICING rule.

Add one more rule for senior citizen, check their user type & apply the new price.

These will work for sure..


How do I hide some fields to registered users?

Though I haven't used profile2 for any commerce site, but the mechanism behind the checkout process for asking profile info for anonymous user is to create account for him on site.
If some information in the profile is mandatory then it will be asked on the time of checkout..& register user won't get those fields at time of checkout.

I use address-field for collecting address for shipping as well as billing, which always keep the old address and its possible to make some address default...so that registered user doesn't find it irritating..

If you must have to use profile2 field then please check whether its required field & if it is...then why some registered users profile is not filled with those information...


Show exposed filter entry with match number

It can be achieved with the help of hook_form_alter().

You just need to override the $form['type']['#options']

Example

An exposed filter with content types and the number of nodes attached to each select option.

/**
 * Implements hook_form_alter
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form['#id']) {
    case 'views-exposed-form-[YOUR-VIEW-NAME]-page':
      foreach ($form['type']['#options'] as $option => $name) {
        if ($option != 'All') {
          $query = "SELECT COUNT(*) amount FROM {node} n "."WHERE n.type = :type AND n.status=1";
          $result = db_query($query, array(':type' => $option))->fetch();
          $name.= ' (' . $result->amount . ')';
          $form['type']['#options'][$option] = $name;
        }
      }
    break;
  }
}

If you don't want to run the query every time when the filter is being displayed, then you need to create a variable with these numbers. The query might be then performed only once, during your module installation, and the variable would be updated only when the node will be created, updated or deleted.

An example with the custom variable

Custom function to create or update our custom variable.

function update_node_numbers() {
  $node_numbers = array();
  $node_types = node_type_get_types();
  foreach ($node_types as $type => $object) {
    $query = "SELECT COUNT(*) amount FROM {node} n "."WHERE n.type = :type AND n.status=1";
    $result = db_query($query, array(':type' => $object->type))->fetch();
    $node_numbers[$object->type] = $result->amount;
  }
  // set variable
  variable_set('node_numbers', $node_numbers);
}

The function should be fired only during administrative tasks (install module, create, update or delete node)

/**
 * Implements hook_install.
 */
function YOURMODULE_install() {
  update_node_numbers();
}

/**
 * Implements hook_uninstall.
 */
function YOURMODULE_uninstall() {
  variable_del('node_numbers');
}

/**
 * Implements hook_node_insert.
 */
function YOURMODULE_node_insert($node) {
  update_node_numbers();
}

/**
 * Implements hook_node_update.
 */
function YOURMODULE_node_update($node) {
  update_node_numbers();
}

/**
 * Implements hook_node_delete.
 */
function YOURMODULE_node_delete($node) {
  update_node_numbers();
}

Now we can alter the form with the help of our custom variable, without using any query.

/**
 * Implements hook_form_alter.
 */
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch($form['#id']) {
    case 'views-exposed-form-[YOUR-VIEW-NAME]-[DISPLAY-ID]':
      $node_numbers = variable_get('node_numbers');
      foreach ($form['type']['#options'] as $option => $name) {
        if ($option != 'All') {
          // some options may have been just created.
          if (!isset($node_numbers[$option])) {
            $node_numbers[$option] = 0;
          }
          $name.= ' (' . $node_numbers[$option] . ')';
          $form['type']['#options'][$option] = $name;
        }
      }
    break;
  }
}


It could help, yes. Your site will be faster, and easier to manage.

less elements means Drupal uses less memory
with less elements, it takes less time to read them all (unused elements are still active)


How do I run Drupal SimpleTest example from Examples for Developers from the CLI?

It seems that SimpleTest requires a version number in the .info file. I added testing_api = 2.x in the .info file and now it works.


How to fix Drupal commons 7.x-3 OgException

A bit too late maybe but...

...check answer #8 at Organic Groups issues place: https://drupal.org/node/2063479#comment-7882345

I've followed it and solved (at least apparently) the issue.

Hope it helps. Have a nice day!
hip


multiple entity type in entity field query

This should work:

$query->entityCondition('entity_type', array('profile2','user'))
      ->entityCondition('bundle', array('user_profile','property'), 'IN');


This is how Display Suite does it:

// Get layouts defined in the default theme and base theme (if applicable).
$theme = variable_get('theme_default');
$themes = list_themes();

$base_theme = array();
$ancestor = $theme;
while ($ancestor && isset($themes[$ancestor]->base_theme)) {
  $ancestor = $themes[$ancestor]->base_theme;
  $base_theme[] = $themes[$ancestor];
}


What version of Drush is compatible with Drupal 6 / PHP 5.2

A list of Drush versions and their compatibility can be found here. Appears Drush Version 5.x is compatible with php5.2.

Here is the current compatibility table reproduced from the link above


How do I get the default billing/shipping customer profile in code?

You can get default user profile address with

commerce_addressbook_get_default_profile_id($uid, $type)

Returns the default profile id for a specific uid and profile type.

@param $uid
    The uid of the user whose default profile id should be returned.

@param $type
    The type of customer profile to look up.

@return
   The id of the default profile if set, FALSE otherwise.

An example if want get  current user shipping addresss use below code :

global $user;
$default_pid=commerce_addressbook_get_default_profile_id($user->uid,'shipping');


How to execute the code at certain time without relying on Cron

Running cron every minute is perfectly acceptable. But if you really want a different solution you could (for example) create a Drush command to do what you want and then call that every minute with something like Jenkins or RunDeck. If you really need this command to run at the exact times users specify and only at those times, then you could write code to publish out the time (and other contextually relevant info) to some external system which is constantly running with some Daemon.

This solution will work but it is:

a) hard because there is a lot of custom work to do
b) tricky because you have to worry about publishing, but you also have to worry about updates and deletes in case your users ever make changes to the time or the contextually relevant data
c) unnecessary since frequent cron runs sounds like it can solve your problem.


Warning: Cannot modify header information - headers already sent

In my own case, I've found that this was due to modules that attempt to return a 404 by mistakenly calling drupal_not_found() instead of returning the MENU_NOT_FOUND constant. This causes drupal_deliver_page() to be called twice in a single page request.

Views is the biggest culprit right now; see https://drupal.org/node/1414068 (comment #16) for a patch that resolves it. You should grep through your modules directory for "drupal_not_found" to find other modules with this problem.


Allow editing of own content but not show 'node settings' block

I think that this is quite easy using hook_form_FORM_ID_alter like this,

function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  if (in_array('YOUR_ROLE', $roles)) {
    unset($form['...']);
  }
}

if you don't know what the name of the element is called, try to find it using kint($node) if you have devel installed.

Hope it works for you.


Yes, the code inside hook_form_alter() or hook_form_FORM_ID_alter() will be run when the $form array is being built, and before it is rendered.

All active modules that implement one of these two hooks will have their implementations called before the $form array is rendered. (They will be called in sequence according to their weights).

If you need to alter or manipulate the values being submitted by the form, you can use one of these two mentioned hooks to include in the $form array your custom #validate or #submit functions, where you can perform any kind of code processing you need.

A good source for finding examples of all these functionalities is the examples module, specifically around here.


How to get width and height of user pictures?

You can add an image field to the user entity. Then you can create a custom field formatter that can check if images are over a certain size and display a link to the larger size if they are. Here is an article on creating a field formater in Drupal 7: http://www.computerminds.co.uk/articles/creating-new-field-formatters-drupal-7