shopping cart is empty when I programmically create order

Here's an example on how to programmatically create an order and add a product to it, then redirect to checkout.

/**
 * Create new commerce_order with product
 * based on $_GET['pid'] from URL
 */
function MODULE_commerce_order_new(){

  global $user;

  // Sanitize just in case
  $product_id = filter_xss($_GET['pid']);

  // Load product
  $product = commerce_product_load((int)$product_id);

  if((empty($product->product_id)) || (!$product->status)){
    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }

  // Attempt to load existing order for user from session
  $order = commerce_cart_order_load();
  if(!$order){
    $order = commerce_cart_order_new($user->uid);
  }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;

  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  // Save new line item to get line item id
  commerce_line_item_save($line_item);
  // Add line item to order wrapper
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

  if(!empty($order->order_id)){
    drupal_set_message(t('Thank you, your %product is ready for checkout.',
                         array('%product' => $product->title)));
    drupal_goto('checkout/'.$order->order_id);
  }else{
    drupal_set_message(t('Sorry, there was a problem building your order. Please try again later.'), 'error');
    drupal_goto(); // frontpage
  }

}


Add a views with fields of nodes added from admin in the user profile

With views you can display tables of items which are related to each other, like content users have created or fields of specific nodes of content.

Your question is not entirely clear. If you want to only show specific fields of a content type to a specific user those fields must be filtered by user ID, using a contextual filter.

If you want admins to be able to specify which fields are shown to which users you may want to use flags, and then filter your view of content on the flags which have been set.

If you can explain in more detail exactly what you are trying to do I may be able to help more.


PHP code to add a link to the configured default home page

If you mean you want programmatically get the value in your Site Configuration, then this works for me: <?php print variable_get('site_frontpage', url()) ?> although I'm not sure this will work in multilingual environment.


Which page are you on when it does not show and is that page in the menu? Also Are you using a block for the menu or printing it in the theme template file? That could be the cause. I'd recommend switching to a block if that's the case and make sure the expanded check-box is checked.


Create a view to show nodes tagged with certain terms next to each other in comparison table

The way I would implement this in Views is to create a node (of type 'Products Feeds') for each product the way you suggest.  Then I would add an additional field (field_unique_product_code) and make that field a taxonomy term (term reference) of a vocabulary named 'products'.  That vocabulary would contain unique products codes for all the products your system will process.  The shops need to use the same unique product code (or you need to translate shop-specific SKUs in the incoming products feeds to this unique product before saving the node).  Note that while the product codes may be strings (e.g. sony-kdl-46R473a, each term gets an unique numeric id in the vocabulary (for instance, the term for this particular Sony tv model may have the numeric id '42'.  Take a note of this number, because you're going to need it later.

Now, perform the following steps:

Create and save a new View named 'Comparisons' and make it a view of type 'Products Feeds'. Press 'Save & exit' to save and exit.
Go back and edit the View:

Make the format for the View 'Grid'.
Click on Show: Content, and change the radio button from 'Content' to 'Fields'.
Add the fields you want to display (shop name, price, description), rearrange the sequence and remove the display of labels.

If you look at the auto preview (bottom of page) at this point, you'll see that you have a nice grid display of the shop name, price and description, but for all the products, rather than for a single product.

To narrow down the display for a single product, you need to add a contextual filter.

Expand the Advanced section (to the right in the Views UI), click on 'Add' next to  Contextual Filters, and add the field_unique_product_code as a contextual filter.

Now, look up the numeric ids for your unique product codes. Let's say your database contains a product with product id 42.  Type in '42' in the textfield with label 'Preview with contextual filters', and click 'Update preview'.

Now, the preview should be restricted to a comparison between the shops, restricted to a single product.  Click 'Save' (top right) to save the View.

Now, you can produce comparions of specific products just by including their numeric product ids in the URL.  For instance:

http://example.com/comparison/42

will produce the comparison grid for the product with numeric product id 42.

This should give you the basic functionality you're looking for.  A lot of refinement is possible.  For instance, if you want to use products names in the URL for contextual filtering, you need to create URL aliases for the numeric ids (you do this with Administration » Configuration » Search and metadata » URL aliases).

For more refinement, you can use templates to get a nicer layout of the table grid, and add a left column with labels.

(But if you need help with these refinements, ask separate questions after you've got the basic grid with the contextual filter working.)


Add an html snippet some within body of the theme using preprocess

You should add hook_node_view() into your module. See the given example on how to add HTML markup.

function mymodule_node_view($node, $view_mode, $langcode) {
  $node->content['my_additional_field'] = array(
    '#markup' => $additional_field,
    '#weight' => 10,
    '#theme' => 'mymodule_my_additional_field',
  );
}


Taxonomy inline with several category types?

Option 1: Pure CSS. Assuming that you have your Content type's display options are set so that all the taxonomy reference fields are next to each other, you would simply display each of the divs that wrap each taxonomy field as an inline element, then use the + selector and :before pseudo-element to add your separator between each field.

These two special selectors are supported in most web browsers, but you might want to check whether they can be used in older browsers your site may need to support.

For example, if each taxonomy field is wrapped with a div having the class "field-type-taxonomy-reference" and your nodes have a div with the class "node-type" wrapping them, your CSS would look something like this:

//make the taxonomy fields and their contents display as inline elements
.node-type .field-taxonomy-reference,
.node-type .field-taxonomy-reference * {
  display: inline;
}

//add a pipe separator between two taxonomy fields
.node-type .field-taxonomy-reference + .field-taxonomy-reference:before {
  display: inline;
  content: " | ";
}

Option 2: edit the HTML with a custom field template. Copy the field.tpl.php file from Drupal core into your theme and rename it field--taxonomy-reference.tpl.php. This would affect all taxonomy reference fields across your entire site, which may not be desirable. You can also implement  template_preprocess_field() in your theme's template.php to add a new template suggestion for only the nodes (and fields) that you want to have affected by this template.  For example:

function YOURTHEME_preprocess_field(&$vars) {
  $variables['theme_hook_suggestions'] = array('field__' . $element['#field_type'] . '__' . $element['#bundle']);
}

This would allow you to use a field template named field--taxonomy-reference--news-article.tpl.php to affect all taxonomy reference fields on a node type named "new article". One the documentation page for template_preprocess_field() you can see a few other variables that are available for you to check (such as field name). You could make multiple fields with different names (and types) across multple node types use the same field template like this:

function YOURTHEME_preprocess_field(&$vars) {
  $field_names = array('field_name_a', 'field_name_b', 'field_name_c');

  if(in_array($element['#field_name'], $field_names) {
    $variables['theme_hook_suggestions'] = array('field__inline-style');
  }
}

This would allow you to use one template named "field--inline-style.tpl.php" for the fields named "field_name_a", "field_name_b", etc.


The delete query will return a query object for all methods except ->execute(). Methods can be chained until the query has been assembled. Execute() completes the chain.

Try:

$count = db_delete('node')
  ->condition('uid', 1)
  ->execute();


How do I define a template file for a specific node paragraph ID?

This can be easily achieved by implementing hook_theme_suggestions_HOOK_alter from within a custom module or your theme. After that you can override paragraphs by adding templates like paragraph--123.html.twig to your theme's template directory.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE/MYTHEME_theme_suggestions_paragraph_alter(array &$suggestions, array $variables) {
  $paragraph_id = $variables['elements']['#paragraph']->id();
  $suggestions[] = 'paragraph__' . $paragraph_id;
}


Why drush "assume yes" -y option do not work for some commands

The solution is to pass all global options like -y or -n before drush command:

drush -y rsync @staging:sites/all/themes @production:sites/all/themes

This allows you to pass options to a shell command run with drush without getting in conflict with drush options:

drush [global options] command [command options]

This will pass [global options] to drush, and [command options] to a shell command.

Take a habit of passing -y and other global options right after you type drush.

Run drush topic docs-strict-options to get a help on that case.


It is possible that the patch was rolled before the days of Git on drupal.org.

For old patches:

patch -p0 < thepatch.patch

For new patches that mysteriously fail with git apply:

patch -p1 < thepatch.patch


How can I show a block on a specific page if a custom PHP function evaluates to be true?

By enabling core PHP Filter module, you will see another option "Pages on which this PHP code returns TRUE (experts only)" under Show block on specific pages of the block configuration page. Select the option and write the following code in the box.

<?php
  if (mymodule_is_iOS()) {
    if (arg(0) == 'node' && arg(1) == 'add' && arg(2) == 'profile-picture') {
      return TRUE;
    }
  }
  return FALSE;
?>

Your module must have a lower weight than the core PHP filter module to allow this code snippet to call mymodule_is_iOS().


Hide node title on front page using template.php not css

Your close with hook_preprocess_page() but as you want to hide the node title (and not the page title) you need to use hook_preprocess_node() instead.


where can I find the login block to modify?

Here are the steps for customizing login block available in Drupal.

1) Go to your template.php file for the theme you're working on. Should be in the root of the theme folder for your theme

2) Now check for the below mentioned function in your template.php file. if its not exist then create it and if its exists then append the below mentioned code in the same.

function yourthemenamehere_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }
function yourthemenamehere_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

Now save and close!

3) Now in side your theme directory there will be a folder called "template". if its not there please create it there only and then create a php file inside that folder called: "user-login-block.tpl.php"
Inside this file, put the following code:

    <?php print $name; // Display username ?>
    <?php print $pass; // Display Password ?>
    <?php print $submit; // Display submit ?>
    <?php print $rendered; // Display hidden elements (required for successful login) ?>

    Singup OR Forgot Password

4) IMPORTANT STEP , navigate to "admin/config/development/performance" and click "clear all caches" -- this is critical because only after deleting cache you can able to see the changes in your login block.

Now you can change the stucture of user-login-block.tpl.php as your wish.

I hope this can help you.


Get the taxonomy term field in Views 3 override title

I was able to solve a very similar issue in which I needed to override the view title with a field from the first result.

I used hook_views_pre_render() to accomplish this in drupal 7.

function tag_views_pre_render(&$view) {
  if( $view->name == 'flex' ){
    if ( count($view->result) ){
      $view->build_info['title'] = $view->result[0]->node_title;
    }
  }
}


Is it bad practice to track all in the configuration module

I have tried it in Drupal7 (not on Drupal8).

Logically it should be good practice to track all the configurations. However, not all the "configurations" are actually configurations. For example there are persistent variables or cached values that have nothing to do with the configuration. So, tracking all of them would undermine the aim of configuration tracking.

Besides this, the UI becomes infinitely slow and unresponsive when you select all the configurations. I guess it is because it tries to find out dependencies of each configuration and does it in an inefficient way. You can try to handle them from the command-line (with drush) but I doubt that it would be more efficient.

So, I think that the best option is to cherry pick the relevant configurations. But once you start cherry-picking them, you might as well use features, configuration management loses its meaning.

This is basically what I did on a project of mine: I started with configuration management, and ended up using features, which by the way was a tedious process.


How to create and display user content submission form?

The create content pages are separate from Drupal's admin section. You can set up the permissions so users can add content of a specific content type but don't have access to any other content types or the admin section.

There's also a permission 'View the administration theme' if this isn't set for a particular role, but they can add content, then the Create Content page will use the default theme. There's also a setting at the bottom of the appearance page, if you deselect 'Use the administration theme when editing or creating content' then everyone who accesses the create content pages will use the default theme also.


Can you export a list of registered users who've registered for an event via the registration module?

Out-of-the-Entity-Registration-box you will (to my knowledge) not get such export facility that you are asking for, so the short answer is NO.

But Sales starts when the customer says no ...: have a look at the Community documentation of the Entity Registration module, especially to this part of it:

  Not happy with the default tabular list of registrations? No problem,
  registrations and their fields are all Views friendly. You can override the default event registrations list, create additional ones, etc.

In other words, if you're willing to accept, as a compromise, to get other modules involved, then it should be pretty forward. However with only views you still don't have the "export" function yet, and you'd need another module on top of that, like the Views data export module (or any of the "similar modules" mentioned on that project page).

Unless you're open to an alternative module for this views-and-some-other-module(s) approach ... I.e. if you'd be willing to only consider the Forena module (disclosure: I'm a co-maintainer), you'd have your 1 stop solution (only 1 extra module, that can do everything you are asking for). Have a look at it's community documentation to get the idea about it (or look at the answers to some of the forena questions). Or post a followup question like "How can I do this with the Forena module?" (to avoid you'd have to change your question here to a chameleon question).


How to print URL arguments in headers VIEWS

You can use arg() function to access the url parameters.

Returns a component of the current Drupal path.

When viewing a page at the path "admin/structure/types", for example, arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns "types".


Split an array of ids and save it as individual rows in table

You can use db_insert in your module OR drupal_write_record

E.g: drupal 7 code

 //Assuming your array is like
 /*
   $ids = array(1,2,3,4,5,6,....);
 */

  // Traversing ids by using foreach loop
  foreach($ids_array as $key=>$value){
       $custom_table_data = array(
            'id'=>$value,// id value
            'column1'=>'..'
        );

       // INSERT INTO {table_name} (field_1, field_2, ...) VALUES ('ABC', '123', ....)
        $nid = db_insert('table_name') // Table name no longer needs {}
        ->fields($custom_table_data)
        ->execute();

        // OR using drupal_write_record...
        drupal_write_record('table_name', $custom_table_data);
  }


Per-item commerce shipping rules working but charging for same item twice

OK - I figured it out. I don't know if this is the best way to do it, but I added an action to my rule, but not as part of the Loop - just beneath it (not indented). This new action is "Subtract an amount from the unit price." For data selector I entered commerce_line_item. For amount, I entered the amount of one additional item (50 for the 50 cents in my domestic shipping example).

So now my rule basically takes the base rate of $3, adds 50 cents for each item including the base item, so then the subtraction action removes that extra 50 cents. Hope this makes sense.


How to use picture element as background image?

Found that we can modify the responsive-image.html.twig to do what we need. We used a combination of the following links:

Responsive images
Responsive images (MDN Web docs)


Though you have custom solutions in place, but a try for views_dependent_filters can be worth, this might be hint as well for your custom solution.

views_dependent_filters module:

  Allows the presence of exposed filters on a view to be controlled by
  values in another exposed filter. Dependent filters are hidden when
  not relevant, and their values are not considered when the exposed
  form is submitted.

  The module is compatible with both the Views basic and the Better
  Exposed Filters form plugins.


Is the issue just with the hide-show js script or is it with jquery in general? In other words, are you experiencing jquery issues all over the site after you enable the module or is it just on the page where your hide show js needs to be activated?

Overall, your question is a little vague. Just include more details and we can give you a better answer.

Lastly have you looked at the developer tools in whatever browser you are in to make sure there are no errors?


Display block content in current language

Added language condition in Filter Criteria to fix it.


How to sum value of a field of all entries in a View?

Though I have never had this requirement but your question look interesting & I did some googling.

I found two related modules. I think you should try them & see what they offer.

Views Calc
Views Aggregator Plus

Note :- This is not an exact answer but helpful for these kind of situations :)


How can I extend the webform #states conditions to save a custom set of conditions for webform fields?

There's a hook for that: hook_webform_element_configuration_form_alter(), webform_example_element_properties.module provides a simple example too.


Navigate to /admin/config/content/formats. For each text format, you can enable the Limit allowed HTML tags and correct faulty HTML filter, which is configurable with the Allowed HTML tags text box at the bottom of the configuration form.

This is how input formats are supposed to be changed.


Is it possible to make site_email an i18n variable?

Your current solution is actually a very bad practice, as you will be rebuilding the variable cache on every page request, which is a big hit.

You can set the site_mail variable as translatable by installing the Variable module (http://dgo.to/variable), then implementing hook_variable_info() and declaring the site_mail variable.

function hook_variable()
{
  $variables['site_mail'] = array
  (
    'title' => t('Site Email'),
    'description' => t('The email addresses site mails are sent from'),
    'type' => 'string',
  );

  return $variables;
}

You then need to go to Admin -> Configuration -> Regional and Language -> Mutilingual settings -> Variables, and set site_mail as being translatable. You will then be able to visit the site information page and set a different value for the site mail in each language.


Customize the HTML of a link field from a custom theme

Try this:

{% for item in items %}
  <a href="{{ item.content['#url'] }}" class="btn-circle btn-circle--blue js-open-modal">
    {{ item.content.text }}
  </a>
{% endfor %}

Found it in a video from 2015, where MortenDK is showing off
It's about 25 min. in

DrupalCon Los Angeles 2015: Drupal 8 Theming with Love


Views Group By how to display only group headers with COUNT of rows

I solved it. The problem with my View was that it was by default sorted by post date. Displaying the underlying SQL query showed that it selects the Post Date to be able to sort by it and that's why it displays each row.

So in this case, getting rid of detail rows means getting rid of the default sort. After that, the view displays only the Group Header row and one "Group By" row per group.

Blue
  Blue
Red
  Red
Green
  Green

To get rid of the Group Header row, hide it in CSS or in a relevant template tpl.php

In order to display the count, add the same field to the FIELDS section again, but this time with Aggregation Settings set to Count. It will look like this:

Blue
2
Red
3
Green
1

To add parenthesses, add Prefix and Suffix to the Field format. To display inline, check both fields in FORMAT->Field Settings->Display inline.


How to programmaticaly serve a 404 in template.php

My personal advice is to return the "No results found" message from Views instead of issue a 404. Why? Because if you ever wind up adding products or changing the name of a product, what used to be a 404 is not anymore. I feel like from an SEO perspective you would have an uphill battle. Anyway.

One way to do this would be from a custom module. Do not do it in template.php.

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(&$view) {
   if ($view->name == 'myview' && some_other_conditions) {
     if (empty($view->result)) {
       drupal_add_http_header('Status', '404 Not Found');
       drupal_not_found();
       drupal_exit();
     }
  }
}

Bonus, Drupal 8:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
 function mymodule_views_pre_render(ViewExecutable $view) {
   if ($view->id() == 'myview' && some_other_conditions) {
     if (empty($view->result)) {
       throw new NotFoundHttpException();
     }
  }
}

Is the view generating the page at products/%? Why do you need to know the $node->nid?


How to link to files using a relative path?

Did you try file_create_url() ?

$file_uri = file_create_url(file_build_uri('images/example.jpeg'));

The above snippet will give the file URL. Besides, I recommend transliteration module for the sites that deals with file uploads.


overriden term name not translated on a taxonomy overriden views page

Install Internationalization Views module.

then select this,
Advanced > Contextual filters > Content: Has taxonomy term ID (with depth)" > select the validator "Taxonomy term (i18n)"

See here


The Future of Image in Drupal 7 reports the following text:

  Image module is being put into core, but not in its current incarnation. Drupal 7 has already made several major improvements that will make handling images (and files in general) much easier, eliminating a lot of the existing code from image.module.

  The Drupal 7 core plan is as follows:

  Move ImageAPI into core to provide better support for toolkits such as ImageMagick (done).
  Move ImageCache into core to provide thumbnailing abilities as part of image.module (in progress).
  Move FileField into core as file.module.
  Move ImageField into core as part of image.module.

This means that most of the functionality of those modules are already integrated in Drupal 7.
ImageAPI still contains code that has not been merged with Drupal 7 code; you should install it if you need the ImageMagick toolkit it implements, or the unsharpen mask action.

As gallery modules, you can try:

Galleria
Fast Gallery
Galerie


You can use the Custom sitemap for achieving this

  The Custom Sitemap module allows users/site admins to add custom
  sitemaps to a site, unlike currently available module that binds users
  to build a sitemap using the primary menu.

  This module enables you to add or promote random URLs from SEO
  viewpoint. It also facilitates you to add independent sitemaps for all
  domains in a multi domain Drupal setup. This also helps you to have a
  domain specific custom sitemap.


How do I deploy a Page Manager page using code?

aha. This problem was caused by a forgotten dependency within the Page Manager page. Instead of using a default layout such as 'two column,' I'd used the Bootstrap layout provided by the Panels Bootstrap Layouts, and then forgot about it. Features didn't add Panels Bootstrap Layouts as a dependency, it remained disabled after deployment, and the dependent page content didn't show. After I enabled Panels Bootstrap Layouts, the content items showed right up within the variant's Content tab.

So if your feature or your Panels/Pages import doesn't recreate the entire setup, review the original for any options that might be provided by another module.


Allow users to annotate content in Drupal 7

The book Pro Drupal Development is probably the most popular book for learning how to build Drupal modules. In the 3rd edition, which covers Drupal 7, the author uses the Annotate module as an example of how to build a module from scratch.

If you read the first chapters of the book you could easily write the module yourself, or even better, try to port the module you mention to 7.x. By the way, remember to check Errata of the book first.


Updating to a newer dev version of a module using Drush (ignoring point/recommended releases, without trashing version control)

I found your question just now because I had the exact same question. Didn't find an exact answer, but this worked for me:

#svn rm <module>
#svn commit -m"removing the module... whatever you want to write"
#drush dl <module>-6.x-2.x-dev
#svn add <module>

For some reason, not doing the commit between the rm and the dl caused a problem with svn. I do not know enough about svn to know why, but would be grateful if someone could elaborate!


Create Node and related Node at the same time?

The Inline Entity Form module will get you that functionality (assuming your reference field is provided by the Entity Reference module).

Provides a widget for inline management (creation, modification, removal) of referenced entities.
The primary use case is the parent -> children one (product display -> products, order -> line items, etc.), where the child entities are never managed outside the parent form.
Existing entities can also be referenced.


You can use BaseFieldDefinition::setCardinality() for that, e.g.:

$fields['fichier'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Fichier attaché'))
  ->setSetting('file_directory', 'messagerie/fichier') // dossier d'upload
  ->setSetting('max_filesize', '10MB') // taille max du fichier
  ->setSetting('file_extensions', 'pdf doc txt xls zip rar mp3 mp4 csv jpeg jpg ppt') // extensions autorisées, à séparer par un espace
  ->setSetting('description_field', FALSE) // si on veut activer un champ « description »
  ->setDisplayOptions('form', [
    'label' => 'hidden',
    'type' => 'file_generic',
    'weight' => 0,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);


The create() __construct() pattern does make testing easier, but not by much. A new container can be very easily generated and populated with the required services for unit testing.


How to create a parent content type which consists of other child content types?

For Drupal 8, it sounds like you are describing reference fields. You would want to:

Create your two content types
Add a reference field to one of them. The refence field would be of the type 'content'.
(Optional, but probably) Limit the types of content that can be referenced to only the other content type.


How to display View contents in a drop down select list?

Sure this is all possible:

If you just want a select list assure you have the Ctools module installed on your site and use the Jump Menu views style output for your Partners content type. Alternatively use the Jump Menu module which you may find more helpful.
Want this embedded into a block you say? Use the Views Field View module to place your output of (1) into a second view that is a block. If you go this route you likely want to enable caching in your Views.

Be sure to see the project page(s) for these modules.


Why is this property of the Cron service initialized in this manner?

It's backward compatibility.

Strictly speaking, constructors are excluded from BC, but the reality is that it is fairly common that one has to override them to inject additional dependencies.

The fallback to the global service means that if such a child class calls the constructor without that argument, it is not going to fatal.

That's especially common for base classes like ContentEntityForm, ControllerBase and other base classes that are specifically designed to be subclassed.

It can also be helpful during updating from an old version, because when running update.php in the UI, the class might be instantiated before Drupal has a chance to rebuild the container and provide the new arguments.


With the following line of your code:

$username = $user_profile['field_username'];

It always gets executed and check index field_username. So in case if the index doesn't exist it throws error.

If you replace your code with the following

if(empty($user_profile['field_username'])) {
  echo 'Please enter an user';
} else {
  print render ($user_profile['field_username']);
}

It will not always check field_username index but only if it is not empty.


$base_url set to an external domain causes problems when logging in

You can set action on after login user.

And that action could trigger through set a perticular trigger.

please use these url to solve this issue in your site.

www.example.com/admin/config/system/actions
www.example.com/admin/structure/trigger/user

Hope this works for you.

Thanks
Sanjay


You can have a complete custom HTML for a particular field by defining a #theme and setting #theme_wrappers with an empty value.

$form['control'] = array(
  '#title' => 'Some title',
  '#type' => 'textfield'
  '#theme' => 'YOURMODULE_control_field',
  '#theme_wrappers => array(),
);

Then Drupal needs to know about this new theme by implementing the HOOK_theme. You can either work with a template file or generate the HTML within the theme callback function

function YOURMODULE_theme()
{
    return array(
        'YOURMODULE_control_field' => array(
            'template' => 'templates/control-field', // if you want to have a tpl file, templates/control-field.tpl.php using the $element variable for your textfield element
            'render element' => 'element',
        ),
    );
}

// If you dont want to use the template file
function theme_YOURMODULE_control_field($variables)
{
    $element = $variables['element'];
    // $element is here your form textfield element, this function return HTML to generate
}


Optimize image that does not have an image style

Assuming background-image refers to the example: <img src="" style="background-image: url(path/to/image);" />.

Background images are different when written as: style="background-image: url(path/to/image);", they do not necessarily use Drupal's render service.

A couple of options to try depending on your use case:

• Try preprocessing your image field URI and then printing out the Image Style image path.

use Drupal\image\Entity\ImageStyle;

$imagePath = 'public://images/image.jpg';
$variables['imageStyleURL'] = ImageStyle::load('style_name')->buildUrl($imagePath);

url({{ imageStyleURL }})

• Change the output format of the field to "URL to image", then just print out {{ image_field }} in the url().

url({{ image_field }})

The problem to your question, is how would Drupal (or contributed module) know that an image URL should be processed by an image style? It would not seem an issue with the modules, more they don't have a chance to do their thing.

Also, Twig Tweak, beyond being a great module for many cases, provides a Twig method for applying an image style in Twig:

{{ field_image_path | image_style('image_style') }}

*Note, manual image URL's that contain an image style path will use that image style: /sites/default/files/styles/image_style/public/pictures/2019-03/file_name.jpg_11


How to determine the route for the add node page of a custom entity type?

You're looking for the node.add route, which has a node_type parameter.
$form_state->setRedirect('node.add', ['node_type' => 'question']);


What's wrong in my rule for sending e-mails using VBO?

Obviously "something" is wrong in what you're trying to get to work. I suggest you enable the typical the Rules debugging (to find more details about what's happening and causing your error), as detailed in "How can I display the value of a variable inside a condition?". If needed, add a copy of the Rules execution log as an update to your question.

Maybe also checkout the tutorial "How to process the results of a VBO enabled view via Rules?".

Plan B

A possible alternative that should work also, is to get the Views Rules module involved in the puzzle you're trying to solve (instead of using VBO). Some details about this module (from its project page):

  Provides Views directly as Rules actions and loops to seamlessly use view result data.

If you're not familiar with Rules (yet), the previous quote may seem a bit cryptic (it may make you think like "so what, how can this help me?"). Therefor some more details about how to move forward using these modules:

Create a view (using Views) so that you have 1 Views result (row) for each user to be eMailed, whereas that view has fields (columns) for each of the fields that you want to use to create your eMail. So your existing view could already be pretty close (if you just remove the VBO field). Important: use a Views display type of "Rules".
Create a custom rule in which you use the Views Rules module to iterate over each of these Views results in a Rules action, using the Rules technique known as a "Rules Loop".
For each iteration step in your Rules loop, perform a Rules Action to ... euh ... right ... Send an eMail. At that point you'll have all data from each column of your Views results available as so called Rules Parameters. So at that point it's a piece of cake to create an appropriate eMail.
The only remaining thing is to decide about the Rules Event to use for this rule to be triggered. But that's up to your own imagination (any Rules Event will do). In your case: your existing Rules Event should also be fine. Optionally, you may also want to add whatever extra Rules Condition(s), also up to your own imagination.

Easy, no?

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


403 Error - Unable to create Paragraphs via REST with ?_format=hal_json

Check on permission Paragraphs Type Permissions -> Bypass Paragraphs type content access control was missing here.
There was also a problem with the JSON request payload of the video paragraph, here the correct version:
    {
        "field_video": [
            {
                "target_id": video_id
            }
        ],
        "parent_id": [
            {
                "value": parent_id
            }
        ],
        "parent_type": [
            {
                "value": "node"
            }
        ],
        "parent_field_name": [
            {
                "value": "field_paragraphs"
            }
        ],
        "type": [
            {
                "target_id": "video"
            }
        ],
        "_links": {
            "type": {
                "href": base_url + REST_TYPE_PARAGRAPH_VIDEO
            },
            base_url +  REST_RELATION_PARAGRAPH_VIDEO_FIELD_VIDEO: [
                {
                    "href": base_url + "/media/%d/edit" % video_id + FORMAT_HAL_JSON,
                    "lang": "en"
                }
            ]
        }
    }

And a correct/working version of the text paragraph JSON payload:
    {
        "field_text": [
            {
                "value": text,
                #"format": "full_html" - getting error "full_html" not recognized
            }
        ],
        "parent_id": [
            {
                "value": str(parent_id)
            }
        ],
        "parent_type": [
            {
                "value": "node"
            }
        ],
        "parent_field_name": [
            {
                "value": "field_paragraphs"
            }
        ],
        "type": [
            {
                "target_id": "text"
            }
        ],
        "_links": {
            "type": {
                "href": base_url + REST_TYPE_PARAGRAPH_TEXT
            }
        }
    }


I've found a solution that you can use the Replacement Tokens to this effect. In order for the field you want to show up as a possible Replacement Token, it must be in the Fields list. So I did:

Set Format to "Unformatted List"
Set Show to "Fields"
Add the "Term ID" field to Fields list.
During creation (or edit it afterward), check the "Exclude from display" box.
Create a new Footer element that's a "Global: Text Area" type.
Check the "Use replacement tokens" box
Insert More Info... in the box.


Can a site be put in maintenance mode without a database?

What you're describing should work: the maintenance-page--offline.tpl.php template should be called when the database is unavailable.

Drupal does not bootstrap completely when there is no database, but does so partially. When the bootstrap process fails to contact the database, it calls _drupal_log_error() in include/errors.inc, which (indirectly) calls _drupal_maintenance_theme() in includes/theme.maintenance.inc. This is enough to allow hook invocations to work, and to load the theme specified in your $conf['maintenance_theme'] setting.

First, I would verify that _drupal_maintenance_theme() is being called and that it's finding your theme. If you're using a debugger, set a breakpoint there. If not, add this line at the end of the function:

  echo "
Custom theme: $custom_theme
";

If all is ok up to this point, try starting off with the simplest possible maintenance page in maintenance-page--offline.tpl.php, e.g.

Hello world

If that works, and your maintenance page does not, perhaps your maintenance page contains something that attempts to access the database, or invokes a hook that attempts to access the database? Can you post your template and any errors you are seeing?

If the simple maintenance page doesn't work, more debugging would be needed.


How do I add a customer ID field in Ubercart?

You want to add a field to the checkout process? There are two modules that do that. uc_webform_pane allows you to create webform nodes that integrate into the checkout process. uc_cck_pane allows you to integrate cck nodes into the checkout process.


How can i access only the text of a comment?

Install devel and try dpm($content);

This will give you an easy way to browse that array.


What's good form for calling views within a module (template, etc)?

I prever to use this small helper function:

function mymodule_embed_view($view_id, $display_id, $arguments) {
    $view = views_get_view($view_id);
    $view->set_display($display_id);
    $view->set_arguments($arguments);
    $view->pre_execute();
    $view->execute();
    return $view->render();
}


Drupal 7: When using the Features module and the database (e.g content type) is different than the matching Features component

If the Feature is overridden, then what you have stored in the database is what Drupal will be using until you revert either the whole feature, or the item in question (such as your View for example).

As an example, if you have an exported View and you make some changes, it will be read from the database. If you either update or revert your Feature, then it will go back to being read from code.


Creating a sub-theme is pretty basic:

Create a sub-dir for your themes in your configured sites dir (e.g. sites/default/all/my_subtheme).
Copy over the .info file of the theme you want to subtheme (e.g. themes/seven/seven.info) to your new theme directory with it renamed to match your directory (e.g. sites/default/all/my_subtheme/my_subtheme.info).
Edit your sub theme .info so that it also contains the line base theme = seven. You can optionally give it another name or description.

From there you should be able to enabled it and start using it. You can copy over other resources that you'd like override in your subtheme. In your example, you can create templates subdirectory (e.g. sites/default/all/my_subtheme/templates) and copy the simplenews templates that you wish to override.


how to show file counter using file_download

The module's project page gives these instructions:

Download to modules directory
Enable module
Apply formatter to any file or image field
Apply settings for title, currently either filename or nothing

Did you apply the formatter?  To apply the formatter, you need to go to "Manage field display" for your content type, choose the image/file field, and then change the formatter.


What is the best-practice for managing Aegir sites in Git?

Here's the recommended way for Barracuda/Aegir by Omega8:

  The recommended (and also more advanced) way to manage your Sites code
  is to use Makefiles (and then Drush Make) to build your Platforms,
  apply patches to contrib or custom modules etc, then using Profiler
  module to create your custom Installation Profile and manage in your
  Git repo just your Makefiles, your Installation Profiles and only your
  custom modules and patches – in a separate repo per module and per
  theme.

Source: http://omega8.cc/managing-your-code-in-the-aegir-style-110.


Redundant log settings between Drupal and Apache

There's a good drupal.org page on how to switch from dblog to syslog module: see Syslog: using the operating system's logging facility.

  "Because the Database logging module writes logs to the database it can
  slow down the website. By using Syslog you can improve the performance
  of the site."

Combine that with a log rotation strategy of some sort.  And then you'll soon be knee-deep in sysadmin-esque territories.  But probably not neck-deep though if you catch my drift.  Lots of good documentation online for log rotation.  Also, I've not done this on D6, only D7, but that page referenced above does have instructions for D6.


Limit which roles can view a node basing on its content type

You need to install Content Access module to add this access control.

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type.


How can I disable single option of checkboxes in drupal 8

You can use Form Options Attributes module.

Then in form alter add below code

  $form['field_domain_access] ['widget'] ['#options_attributes']
  ['your_option_key']  = ['disabled' => 'disabled'] ;


The stage_file_proxy module is what you're looking for.
You can configure this module to download images on the fly, i.e. as they're needed, or have your local environment serve them straight from your remote environment.
From the project page on d.o, the simplest install:
composer require drupal/stage_file_proxy
drush en stage_file_proxy
drush config-set stage_file_proxy.settings origin "https://www.example.com"

The module's INSTALL.md file goes into more detail about all of the module's options.


Is it good practice for a module to add fields to a certain content type?

Not only is it a good idea, it is the result of the generally recommended workflow when working with custom content types. If you have other business logic that depends on those fields, I would definitely make them available at install time to make deployment painless.

The Features module can be used to export fields, content types and other configuration into a separate module for you to download, so you do not have to write this yourself. By exporting your configuration to code, it becomes possible to check it into revision control, providing the basis of more complex Drupal modules and distributions.

The KIT specification referred to by Letharion provides a standard for how feature modules (those exported by Features) should be structured for maximum interoperability and portability, but it is the Features module that does the heavy lifting (note, however, that modules created by Features do not name Features as a dependency). Obviously, not every feature you create has to be KIT-compliant, though it does provide a good starting point with a series of sane best practices.

Whether it makes more sense to simply modify the feature module (it is a module like any other, after all!) or make it a submodule of another project depends on the specific use case. If I understand yours correctly, both your supporting module and your content type are used in conjunction to satisfy the same single use case, so I would consider merging them together. Generally, you would make the feature module stand-alone if it could be used independently and satisfies some use case on its own, which does not appear to be the case.

If you have any questions, I would be happy to clarify my answer.


How to have users set a value for a flag field upon flagging?

You need to read the flag admin options more carefully.
On /admin/structure/flags/manage/MYFLAG, under Display options, choose "Field Entry Form".  This will give users the options to enter flag fields before the flag is saved.


I am dealing with the same question here for a 2 location store, one in the US and the other in EU.
Because i also don't want to interfere with functionalities and UX of present stock validation and control modules, my thought went also to manage inventory levels in separate entities.
I have this workflow/checkout in mind :
- product nodes show the availibity of a product(variation) based on total stock of all inventories
- after entering delivery address in checkout, shipping rates will be calculated from both inventory locations
- customer will be presented a default inventory based on rate, estimated delivery time and last but not least stock level for the chosen products in that inventory.

The matter of splitting up the order comes in mind with this solution if product a is only available in EU inventory and product b only in US inventory, or when ordered quantity of product c needs to be shipped from 2 inventories.

So before thinking about setting up a multiple stock location solution, you should think about it's consequences to the workflow, especially in checkout and feasible splitting of shipping arrangements and related dues.

If you came up with something already, let me know.
Hope my feedback helped you making the right choices.


It's difficult to answer because I don't have enough information on what is happening, but here are some suggestions:

Give your views page a url alias of /news if you haven't already and in the block configuration make sure "news" is not listed there. Then you don't have to use "?q="
Make sure your spelling is correct so it's not q?=news and is ?q=news in your block configuration.
Views pages are not great to work with, personally I don't like them for a number of reasons. Instead, I use the insert_block module and I insert a views_block into my node, I get less problems like that and more flexibility.
The context module is also a good module for placing blocks in regions based on any type of page, but it's more difficult to manage.

EDIT: More things to check:

Make sure no styling is hiding those blocks. Check the markup loaded on the page and see if the markup for those blocks is loading on the page or not.
Make sure that the region you assigned those blocks to is actually loading on the views page.


Accidentally changed the path of an RSS feed page in Views to refer to a menu link item and cannot access Views menu anymore

You can export your configuration to files, then edit the file that holds wour faulty view, edit the URL, save it and import the configuiratin again.

To do this:

Go to /admin/config/development/configuration/full/export and click 'Export'. Your browser should donwload tar.gz file.
Uncompress the file to see all your site configuration splitted in multiple files.
The file that holds your faulty view file should be views.view.NAME_OF_THE_VIEW. Edit it and look for a line with the view path. It should be:

  path: {wrong path}

Change to the right path and save the file.
Compress again all files to get again a tar.gz file. Is the same that you downloaded but with the file you have just updated.
Go to /admin/config/development/configuration/full/import and upload your tar.gz file with the new configuration.

Drupal should update the configuration and change that view url.

Udpate

Unfortunately it seems there's a bug with views that can arise when editing file in Windows (an probably Mac):
Importing tar file causes Archive_Tar error

  I had the same problem and I found that I could not open the tar
  neither. So I tryed other exports. I found that when I don't export
  views settings, the tar is good. It's only when I put some specific
  views in the export that the tar does not work.

Second update
As @user3531869 says, it's possible to update one single file of configuration to avoid the mentioned bug. To do this go to /admin/config/development/configuration/single/export and select the element you want to export (in this case select View as configuration type, Aggregator RSS Feed as configuration name), copy the the code that Drupal returns, edit to fix the path and the go to /admin/config/development/configuration/single/import, select View as configuration type, paste the edited code in the text area and clicj Import.


How can I change the 'type' of Drupal script tags from text/javascript to text/plain?

I solved, mostly by implementing the theme_process_html_tag method in the template.  Note the PROCESS not PREprocess.

In my case, the theme was extending the 'zen' theme, which was actually removing all 'type' attributes from scripts in the header (I don't know exactly why).  But I was able to overwrite this behavior in the theme hook mentioned above.


Add custom image styles to media browser display options

This tutorial ended up answering my question:
http://figure-w.co.uk/drupal-how-do-you-make-a-new-image-style-appear-in-the-media-browser/

Install the Entity View Mode module
Add new view modes
Configure display settings for view modes


How can I disable the form confirmation message?

There is no option in Drupal's core that gives you the ability to disable messages but there is a module for that: disable_messages.

Still, I like this approach, which uses drupal_get_messages function implemented in hook_form_alter:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  // Define the $form_id for the form which you want to suppress messages for.
  if ($form_id == 'hide_messages_form_id') {
    $form['actions']['submit']['#submit'][] = 'my_module_submit';
  }
}

/**
 * My custom submit handler.
 */
function my_module_submit($form, &$form_state) {
  // Hide drupal 'status' messages. Equally use 'error', 'warning' or 'NULL'.
  drupal_get_messages('status');
  // Or display your own message.
  // drupal_set_message(t('My message.'));
}


What is the best workflow to migrate a site using domain access?

Can you be a little more specific, are you just wanting to migrate the whole database to a new installation or are you migrating content into an existing installation

In the first case it should be fairly simple,

Put your site in maintenance mode and then flush all the caches.
Take a backup of your sites directory.
Copy the database to the new server.
Upload the drupal installation and then the sites directory to your new server
Modify the settings.php to connect to the database on the new server.
Using a DB admin tool such as phpmyadmin modify the "domain" table in the database on the new server, there is a field in this table called "subdomain" this relates to the url of your domains so just modify this to suit your needs.


I am posting here in return, my block configuration, you will see that your contextual filters differ from mine, and for that matter, from what the tutorial describes.

Whatmore, the tutorial from Kristin Brinner describes in "Part 4. Create A-Z list" how to set up this block, which is what I did and got the expected result.

I would suggest you go through that part in the Tutorial again, the block you have at the moment is not configured according to the instructions of the tutorial.

And a useful quote from the Views 3 Handbook (accessible via Advanced Help):

  Each display can have its own settings, but when created, a display
  will take all of its basic settings from the default display which all
  Views must have. For most settings, there is an override button that
  will override that single setting for the current display. Overridden
  settings will have a mark in the summary for that display. All
  'default display settings' are shown in the other displays in
  'italic'. When you override a setting, then it is shown 'normal'.

Will keep an eye on this post! Best of luck!


Is there any hook or event that is fired when user data is set/updated/deleted

hook_entity_presave (hook_ENTITY_TYPE_presave)

  Act on an entity before it is created or updated.

  You can get the original entity object from $entity->original when it
  is an update of the entity.

hook_entity_update (hook_ENTITY_TYPE_update)

  Respond to updates to an entity.

  This hook runs once the entity storage has been updated. Note that
  hook implementations may not alter the stored entity data. Get the
  original entity object from $entity->original.

Here's a sample implemented by system.module:

/**
 * Implements hook_ENTITY_TYPE_presave() for user entities.
 */
function system_user_presave(UserInterface $account) {
  $config = \Drupal::config('system.date');
  if ($config->get('timezone.user.configurable') && !$account->getTimeZone() && !$config->get('timezone.user.default')) {
    $account->timezone = $config->get('timezone.default');
  }
}


Create different URL alias based on CCK field

I'm assuming you're well-versed in the settings that Pathauto gives you (like it's own "automated alias" checkbox, and the settings that change what happens when a node is updated).  I'm assuming those settings don't meet your needs.

This should be possible, but not in the theme layer.  You'll need to write a module, probably a relatively small one.  You'll need to implement hook_nodeapi in D6 or one of the hook_node* family in D7, and maybe hook_pathauto, to make sure the right thing happens.

Drupal 6

hook_pathauto()
hook_nodeapi()

Drupal 7

hook_pathauto()
hook_node_presave()


Can a title of a node not be associated with a url?

When I create multiple nodes for the main node

What exactly are you trying to accomplish here? How do you create multiple nodes of the "main" node, how are they related to each other?

CCK has a node reference field, you should use that to make the relationships explicit and go from there.


An all in one solution I think is hard to find/make for drupal.
There's a module, where you can import and edit spreadsheets. I've testet it briefly for a project, that never go further than prototyping, but the module simply worked:
http://drupal.org/project/sheetnode

There might be similar projects for word processors. Or you might have it made :)

For a Google drive alternative, where you are in control, have a look at http://owncloud.org. They have calendar, contacts, and many other things, but I don't think they have editors.


Any kind of sorting gives duplicate results in Views (Search API)

Bleh what a horrible bug.

I solved it by re-creating the search index (and therefore the view as well).

Why did it happen?

I think it's possible to have certain things saved into the Search Index (possibly when it's created?) and then it's impossible to remove them without just starting afresh.

I discovered this bug while trying to debug this.

After re-creating the new index the only difference I can find between it and the original is that I can now sort by an un-related taxonomy field (see the bug). Presumably this is an indicator of something as it doesn't seem relevant, but I have no idea what.

Second EDIT:

Actually just re-creating the index wasn't enough to solve this problem, I then continued to find duplicates after.

Deleting and re-creating the field with a new ID however did work. I never worked out why, but I'm presuming something was corrupted.


CKFinder - Clicking 'send it to the server' when uploading an image does nothing

The answer to this, as inspired by Nikit's comment, was to not use CKFinder at all.

CKFinder / CKEditor combination has to be one of the most frustrating experiences in all of Drupal, and it is the one thing I dread on each project. I have no idea why it has to be so complicated.

I kept CKFinder and used IMCE as suggested. The recipe works great; no complicated configuration; and is a much better module, in my opinion, for managing user images and file content.  I would suggest trying it as well if you find CKE and CKF as frustrating as I do.


How to limit what is available for a role in Administration menu ?

Check if this user role is marked as the "Administrator Role" on User Settings.

There is also an option to rebuild the menu tree on Admin Menu settings...


calculated field in views based on another view

One way to do this would be to create a field template for that specific field.  Then you could first print the value of the seller price, and then do the calculations in php and print the difference.

You can specify that the field template only be used for a specific field in a specific display of a specific view by naming it correctly.  You'll find the pertinent names in your view edit page under Advanced -> OTHER -> Theme: Information.  The default contents of a template file are also available there by clicking on the field name.


Drush 9 pulling incorrect site information on Multi-site

I don’t know how your setup is now but you need to have something like this.

 sites/site-name-1/settings.php

Containing

$databases['default']['default'] = array (
  'database' => 'gtest2018',
  'username' => 'gtest2018',
  'password' => '54352432346greg433',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

And then the same for the other instances.

Then when you want to install a module in one instance run drush en MODULE_NAME -l site-name-1.

For more info look here: Multisite folder structure in Drupal 8.


Try to implement following code

function myid_user_page_form(){
$form = array();
$form['myphoto'] = array(
  '#type' => 'managed_file',
  '#title' => 'File Upload',
  '#upload_validators' => array('file_validate_extensions' => array('png gif jpg jpeg')),
  '#upload_location' => 'public://my-folder/'
   );

$form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Save',
 '#attributes' => array('id' => 'myid_save'),
 '#submit' => array('formsave_action'),
 );
 return $form;
}

function formsave_action($form,&$form_state) {
    $file = file_load($form_state['values']['myphoto']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
}


Is there a way to set only the "Full HTML" input format for the administrator role?

User #1 is a special user that gets all permissions, always. Its access privileges are not controlled by the administrator rule. You can read more about it here: Securing user #1

I haven't tried this, but the following should work: you could create a new admin user with the administrator role, and give it access to Full HTML only. If you want you can then disable user #1 completely. Before you disable user 1 make sure that the administrator role really does have all permissions. I don't know about D8, but in D7  the administrator does not automatically get all permissions when contrib modules are installed.


Conditionally show fields viewing a node (not in the node add form)

If you haven't solved this yet, the Webform Conditional module might help.

  This modules enhances the existing Conditional Rules of the Webform Module. It adds the ability to make components dependent on select components(i.e. listboxes, radio buttons, and checkboxes) that appear on the same page.


I haven't met this problem before. I did Google search and found this link Classes being stripped in CKeditor. Maybe your problems come from CKeditor and you just configure the allowedContent for CKeditor.


How do I manually update without using Drush nor Composer?

The official update method is described in UPDATE.txt:

http://cgit.drupalcode.org/drupal/tree/core/UPDATE.txt?h=8.4.x

This is basically what you've described in the question. You don't need composer to update core.

If you want to switch your existing installation to composer a risk free way would be to start a new project, see Updating core with Composer doesn't work.


"View unpublished content" permission for non-author

If you're ok writing a very small custom module you could use a combination of hook_permission() and hook_node_access() to do this:

function MYMODULE_permission() {
  return array(
    'unconditionally view unpublished content' => array(
      'title' => t('Unconditionally View Unpublished Content'),
      'restrict access' => TRUE
    )
  );
}

function MYMODULE_node_access($node, $op, $account) {
  // We're only bothered about the 'view' operation at the moment
  if ($op == 'view') {
    // If the user has access to our new permission, let 'em at it
    if (user_access('unconditionally view unpublished content', $account)) {
      return NODE_ACCESS_ALLOW;
    }
  }

  // For everything else let the system decide.
  return NODE_ACCESS_IGNORE;
}

Any role you assign the new permission to should now be able to view any node, regardless of whether it's published or not.


Recaptcha not working in user register form

After some browsing, i found the Patch for the Recaptcha module that enables it to be used in ajax register form.

Please find the link to the node  here

Cheers.


Views provide to the template the html output of the field and not the actual value or a means to detect if it is empty or not. You will thus need to compare the field->content value with the expected html output. Assuming that you use Drupal 7 and you haven't overriden the field output or you haven't set the field as hidden ("exclude from display" option), the default field output is:

opendiv class="field-content"> ... html output here ... closediv>

Steps to achieve what you're trying to:

1) Add a function like the following: (replace "opendiv" and "closediv" with html open and close div tags, I couldn't get the editor not to filter them)

function mymodule_views_field_compare_value($field, $expected_value) {
      if ($field->content == 'opendiv class="field-content">'.$extected_value.'closediv>') {
          return true;
      }
      return false;
  }

2) To check if a field is not empty do:

if (!mymodule_views_field_compare_value($fields['field_ba_before'], '')) {
}

3) To check the value of the image positioning:

if (mymodule_views_field_compare_value($fields['field_image_position'], 'image_position_default')) {
}

This should help. You can use dpm($fields['field_image_position']) (if you're using the devel module) or var_dump($fields['field_image_position']) to check the actual output of the field, in case it is different than just 'image_position_default', I don't know what type of field it is.


How to implement some type of private messaging to arbitrary groups of users?

Using the Forena module, you could start from one of the Sample reports and solutions that come with it. I.e. the Active Users Email, which is a demo of the ability to send email to all active users of a Drupal site.

The idea is that those users who have access to it, actually get a FORM to have Drupal send an eMail to all users selected via the query. To do so, you just have to "submit the report".

The easiest way to see the out-of-the-box example at work, is to (temporary) install the module in some dev environment you have available (for obvious reasons this sample report is NOT available to anonymous users in a Forena demo site ...).

Here is what would be needed to transform (clone) this sample to fit your needs:

Adapt its data block (an SQL query) to list "all persons to be eMailed" (instead of all "active users of a Drupal site").
Adapt the actual content of the delivered eMail template to fit the actual eMail content (message).
Optionally you may want to make the "group" to be selected a report parameter.
Secure "access" so that only authorized users can send such eMails. Depending on how your security is setup, you may want to adapt the Forena permissions accordingly.

The above approach can be used for all sorts of eMails towards any set of users of a Drupal site. Whereas that "set of users" is just a matter of writing some (basic) SQL statement to select the users you want to target. E.g:

Users with a selected role or
Users who didn't login for X days anymore or
Groups of users that are either pre-defined or ad-hoc selected (as in your question), whereas you'd need 'something' to actually indicate that ad-hoc selection that you can retrieve via some SQL query, like:

a taxonomy term.
some flag (using the Flag module).
all members of a group, created using either Group or Organic Groups .
etc.

...

And the actual eMail content (message to be delivered) is actually anything you can format as an XHTML document.

Disclosure: I'm a co-maintainer of the Forena module.


It turned out that some of the migration processes were stuck after the first attempt. Here is how I solved the problem and completed the migration of my multilingual site:

Download and enable the Migrate Tools module and Drush 8
Run drush help to verify that new migration commands such as migrate-status and migrate-import are enabled
Run drush migrate-status and check the migration processes; all statusses should be Idle, but in my case some were stuck on Importing
Use migrate-stop to stop any running processes; according to the documentation, this ''cleanly stops a running operation''
Use migrate-reset-status to set the status of stopped processes back to Idle; according to the documentation, this ''sets a migration status to Idle if it's gotten stuck''
Continue the upgrade via the web browser or Drush


I have fixed this, just for other guys who are facing the same issue, I thought to post this.

created a Taxonomy Page with tag selected
save and edit
FIELDS -> add your necessary fields
FILTER CRITERIA -> add: Taxonomy term: Name (exposed)
click on Advance tab to the right side
RELATIONSHIPS -> add : Taxonomy term: Content with term
CONTEXTUAL FILTERS -> add : Taxonomy term: Name

I'm using exposed form "Exposed form in block:Yes" to be displayed as a block and can be assigned to the page.

Search Result in URL : drupal-7/search-new-1?name=tag


You can do a hook_form_alter of your form, and add your own validation to it.

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'NAME_OF_FORM') {
    $form['#validate'][] = 'YOURMODULE_VALIDATE_FUNCTION';
  }
}

function YOURMODULE_VALIDATE_FUNCTION( $form, &$form_state ) {
  $mobile = $form_state['input']['field_MOBILE']['und'][0]['value'];
  $is_valid_mobile = YOUR_AWESOME_MOBILE_VALIDATOR($mobile);
  if( !$is_valid_mobile ) {
    $error_msg = 'Mobile is invalid. Please enter a valid mobile number e.g xxx-yyy.';
    form_set_error('field_MOBILE', t($error_msg));
    return false;
  }
}


overlay does not work after enabling my custom module

I figured (googled) it out. :)

I added my custom js in my custom module's info file instead of using drupal_add_js in my module directly.

scripts[] = my_module.js

and added drupal behaviors in my js file as well, so now my custom js looks like below

(function ($) {
Drupal.behaviors.my_module = {
attach: function (context) {

// my js code

 }
};
})(jQuery);

I spent many hours figuring this out but it was as simple as could be be.

Hope this helps someone! :)


Get content of current user + Of the users that are flagged or followed

In the relationship's settings, uncheck the setting that restricts content to that flag.

Use the regular view filters instead and have two filters with OR between them. They would probably be author: current and author: flag.


Change the display mode of your field with the image style you want. And it's ok

But If you want do this with a custom module, you can do this:

$imageFile = Media::load($media_mid);
$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$imageThumbnailUri = $style->buildUrl($imageFile->get('thumbnail')->entity->getFileUri());


Rules: get content created by user account being cancelled?

You can use the Views Rules module, as further detailed below.
1. About the Views Rules module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of your "node of type XYZ authored by this account" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

3. Create a rule using the view of display type 'Rules'
Adapt your Rulew Actions, using these guidelines:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each node contained in your Views loop (I seem to understand you will only have one), perform whatever Rules Action that fits your requirement, using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed).


How to create links which pass arguments to a page?

You can use l() function, Like
Suppose You are showing some data in table format as you mention in your question and using some query you get some data from databse in $result variable,

$header = array(t('Approved By'), t('Role'), t('Points'), t('View
More'));
foreach ($result as $row) {
    $rows[] = array($row['user_name'], $row['user_role'], $row['date'], l(t('View'), 'node/' . $row['row_id']));
}
return theme('table', array('header' => $header, 'rows' => $rows));

Now above code create a page showing table

Approved By    Role                    Points    View More
Eve            content writer          94        View    -> url: my-page/1

John           content manager         80        View    -> url: my-page/2

Adam           manager                 67        View    -> url: my-page/3

Jill           admin                   50        View    -> url: my-page/4

function my_module_menu() {
    $item['my-page/%'] = array(
        'title' => 'my page',
        'page_callback' => array()
        'page callback' => 'my_page_callback',
        'page arguments' => array(1),
        'access arguments' => array('access content overview')
    );
return $item; }
function my_page_callback($row_id) {
    // Get some data from database using $row_id
    // show in table
}


Let's suppose your nodes titles for Category content types are Category N and for Item Content Type are Item N.

Create a view on content filtered by content type = category, then in views advanced section in  Relationships add relation on your entity reference field on category content type, then in the field section again add a title but in Relationship section of the field settings choose your relation created before and then Group Results by Category title field.


Twig Views Embed

  This module allows to embed views with a twig function.

{{ views_embed_view('view_name', 'view_id') }}

The above module was depreciated in favour of

Twig Tweak

  Twig Tweak module provides a Twig extension with some useful functions
  and filters that can improve developer experience.

Ex:    <dd>{{ drupal_view('view_name', 'view_machine_name') }}</dd>

You can find the view_machine_name over here


How to get the values of an array in the options list (hook_rules_condition_info ()) instead of array index?

You just need a reliable array key so you can load the data up again somewhere else; since you're going into the users table, uid seems appropriate:

function list_all_users() {
  return db_query('SELECT uid, name FROM {users}')->fetchAllKeyed();
}

That will turn the options into an array with user IDs as keys and names as values. As far as the front end is concerned, nothing changes.

Now when you receive the selected option value in the validation function, you can just load the user up and get the name from the entity:

$account = user_load($the_value);
$name = $account->name;


Pathauto , Using Body Value for URL Alias

Without questioning why you would want body text in a URL alias you should be able to access this by using:

[node:body:value] for the value
[node:body:summary] for the summary


How to export 'Content-Type' data into JSON?

You could use the Forena module (disclosure: I'm a co-maintainer of it) as your 1-stop-solution (using only 1 contributed module) to:

Build your custom query to fetch the data, whereas these data can be retrieved directly from your Drupal database. Obviously, in this case it's be an SQL to retrieve your CONTENT_ID, CONTENT_NAME, LARGE_THUMBNAIL, ZIP_FILE ...
Format the look and feel of your results (the report) using xHTML (and/or charts if you'd like).
Download the results in any of the typical formats, such as PDF, XLS, CSV, XML, JSON, etc. For any report that you create (using Forena), just add .csv as an extension to the report (output) URL. That contains the CSV equivalent of that report (similar for the other formats).

Example

As a sample, consider the sample report located at /reports/sample.states in your own site (one of the samples shipped with Forena) or in the Simple Table of States in the demo site. Change the URL to /reports/sample.states.csv (= just add .csv to it) to get the same report in .csv format. By adding such .csv to the URL, the result is like so ...

Same technique applies for other supported extensions (export formats), such as:

the PDF version.
the HTML version.
the XLS (MS Excell) version.
the DOC (MS Word) version.
... there are more.

Remark: when building a report, you can also specify for which of these Document Types an hyperlink should be made available in the report.

Direct access to data blocks

All data blocks are also accessible directly via their url, provided you have permission to access that block. Here are a few samples of that (from the demo site), for the sample report located at /reports/sample.states:

in JSON format.
in XML format.

More info

To get an idea how its Custom Queries (SQLs) and/or Report Specifications look like, refer to the example in my answer to "How to retrieve data directly from a Drupal database".
The Forena Video demos and tutorials contain quite some links to live demos.

Getting started

To actually install/configure Forena, make sure to look at the various steps in the Setup Guide that comes with it, which you can find at /reports/help.setup in your own site also after you enabled Forena (similar to what you can see in the demo site). Missing (forgotten) "permissions" and/or "text formats" configurations (if you don't follow the Setup Guide) or the most common showstoppers if you"re new to Forena ...
If you run into "PDO driver support for sqlite not installed", then head over to comment nr 7 in issue #1061436. Here is a summary of it: you only need that for using the "sample database" (the one you can also see in the demo site), which is delivered in SQLite format. So you can use Forena without that support, eg to access your own Drupal database (in MySql fmt). And/or you might want to look at the "drupal admin samples" instead ...


This post on stackoverflow describes how to do this programmatically.

Just call check_markup and pass in your text and the filter id.

check_markup($text, $format_id = NULL, $langcode = '', $cache = FALSE)

  Run all the enabled filters on a piece of text.


How to do Test Driven Development (TDD) in Drupal?

Since Mark's blog is offline, I'll mention some of the tools his team has implemented:

Functional testing: Selenium
Unit testing: Simpletest
Build server: Jenkins
Performance benchmarking: XDebug + Cachegrind

In the two years since I asked this question I've seen some additional tools gain popularity to the TDD scene. Nowadays when you speak of Test Driven Development (in a Drupal context, of course) there's two sides to the same coin — front-end testing, and back-end testing.

Here are two presentations that stand out from the latest Drupalcon Portland 2013 representing this matter:

Development, By The Numbers, backend testing.
Automated testing with Jasmine and PhantomJS, frontend testing.

The first presentation is not related to unit or functional testing (strictly speaking), it's more about tools to measure code quality. Nevertheless, I feel it's somewhat related to the topic.


Creating a Drupal user with user_save doesn't automatically join an existing CiviCRM contact record

The function to synchronize Drupal users and CiviCRM contacts is CRM_Core_BAO_UFMatch::synchronize().

Since you're calling user_save(), CiviCRM's hook_user_insert implementation should get triggered (from user_module_invoke('insert', $edit, $account, $category); in user_save().

CiviCRM's civicrm_user_insert() checks whether it thinks you are on a CiviCRM callback already*, then calls either civicrm_register_data() which will in turn call CRM_Core_BAO_UFMatch::synchronize(), or CRM_Core_BAO_UFMatch::synchronize() directly.

To deal with this you could trace your way through CiviCRM's code (drupal/civicrm.module, drupal/civicrm_user.inc, CRM/Core/BAO/UFMatch.php) and work out which path your code is triggering; ultimately you want to end up with a call to CRM_Core_BAO_UFMatch::synchronize() which passes in the parameters for CiviCRM to correctly match the existing and new data.

You could also just call that function directly from your custom code; that might be less robust as in future you might end up triggering the synchronize call twice ...


HTTP ERROR 500 comes on using theme function

In D8 controllers return a render array. Put the template name you have defined in hook_theme() in #theme. Prefix the variable names with a '#':

return array(
      '#theme' => 'my_module',
      '#my_module_header_message' => $my_module_header_message,
      '#my_module_form' => $my_module_form,
      '#my_module_footer_message' => $my_module_footer_message,
);


Send email with URL of same page as the email link?

insert a Drupal token of the current page url into the WYSIWYG. This token is provided by drupal 7 core I believe.

See the Token Insert module.

  This module allows you to insert tokens into a textarea. It supports
  both plain text and wysiwyg textareas. The format used for the insert
  is compatible with Token Filter.

  This module contains three modules:

  Token Insert UI: Allows you to select which tokens are available for
  the insert, by default all tokens are shown. This module doesn't have
  to be enabled to use the others.
  Token Insert (text): Add a fieldset
  under each textarea, works for both plain text fields and wysiwyg
  fields.
  Token Insert (wysiwyg): Adds an extra button to wysiwyg
  editors and opens a popup to select the token to insert.


Get taxonomy field value in forum-list.html.twig

Your question is very vague.
I suggest setting up xdebug (https://www.drupal.org/docs/develop/development-tools/xdebug-debugger) then using the function devel_breakpoint() to be able to see how to reach the values/fields of your entity.
If your taxonomy is attached to your topic, I'm assuming that the solution will be something like forum.taxonomy_field.value.
If your taxonomy is not attached to your topic, you should have a look to preprocess your topic to add the missing data by using template_preprocess_forum_list()   I guess?
Here is the list of all preprocess hook, maybe another one with forum might do the trick: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/implementations/hook_preprocess_HOOK/8.2.x


getForm() returns a render array, and a render array can have other render arrays as children, so:

$build = [
    'form' => $form,
    ...
];


How do I check which of my installed modules is unsupported?

As stated here, you need to go to admin/reports/updates rather than admin/reports/updates/update to see which module is having the problem.


How to hide profile2 field label and captcha label in registration form

you can use this code instead:

$form['captcha']['#title'] = '';


Problem ignoring in a view the images inside the .views field body and the minimum number of characters?

The Smart trim module might be helpful. You'll be able to trim units by words or characters on stripped HTML.

  After installing and enabling Smart Trim, you should see a "Smart
  trimmed" option in the format dropdown for your text fields. With
  smart trim, you have control over:

  The trim length
  Whether the trim length is measured in characters or words
  Appending an optional suffix at the trim point
  Displaying an optional "More" link immediately after the trimmed text
  Stripping out HTML tags from the field


How to change user badge when 'total User Points' increase?

The key part of your question seems to be this:

  I tried using the Rules module, but didn't find a way to compare the current total amount of points of the user to my specifications, (for Rules Event "User was awarded points"), so that based on the result of that comparison, the Rules Action would eventually change the badge assigned to the user.

Indeed, for Drupal 7, there doesn't seem to be some Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn Execute custom PHP code condition, e.g. to do some type of comparison):

global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

However, there is a Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want, e.g. to "User was awarded points", as in your question):

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.


Drupal + Simpletest + Class Autoloading = FALSE?

I assumed that all "autoloadable" files for the module I was testing would indeed be automatically loaded, but this seemed to be wrong.

I needed to add the following function to my testclass:

public function setUp() {
  parent::setUp('mta');
}

Please note that 'mta' is the module I'm testing, and which the "autoloadable" classes are defined for. I assume that if you need access to "autoloadable" classes defined for any other module, that you need to set up those modules too.


What is the best way to restrict website's direct access through node urls?

Using the Rules module you can implement a rule that looks similar to this:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

It assumes you'll have a node with a path like no_access (which is where a user trying to use node/xxx will be rerouted to). Feel free to adapt to any other path that fits).

The above rule does not (yet) take into account to only apply the "action" for selected user roles. E.g.: you may want such paths to be used (allowed) anyway for roles like 'administrator' or 'content-editor'. But for anybody a bit familiar with the Rules module, that is a straight forward "Condition" to add.

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function. Then further edit/refine to make it fit in your own environment (eg the "Sorry, ..." message to be shown.

If you have to still install the Rules module, you'll discover tons of other use cases to also be resolved by the same Rules module (possibly complemented with the Flag module soon ...)


I made it work!

There are many details to consider, so here is just a rough overview.

Storing the entries.

I decided to store the entries not in config entities, but as raw config entries. This seems easier, and prevents recursion with hook_entity_extra_field_info().

For each entry, we store:

Configuration that tells us how the item should be displayed when viewing the entity.
Optionally, an administrative label and/or a label for visitor consumption.

We do NOT store the weight (order / position between other fields). Thanks to hook_entity_extra_field_info(), Drupal will do this for us!

We do NOT store an id or machine name as a value within the entry. Instead, the machine name is part of the key referencing the config entry.

Each entry is identified by a key of the format "entdisp.vme.$entity_type_id.$bundle.$view_mode.$entry_machine_name".

entdisp.view_mode_entry.schema.yml:

entdisp.vme.*.*.*.*:
  type: ignore

Obviously this could be more sophisticated, but it works for me.

Crud forms for add + delete

Similar to field_group module, create forms to add and delete view mode entries.

E.g. admin/structure/types/manage/article/display/full will have an action link "Add EntDisP entry" leading to admin/structure/types/manage/article/display/full/entdisp/add.

hook_entity_extra_field_info()

Register extra fields per bundle, with placeholders for the label and other settings.

/**
 * Implements hook_entity_extra_field_info().
 */
function entdisp_entity_extra_field_info() {

  $ids = \Drupal::configFactory()->listAll('entdisp.vme.');

  $fill = ['', '', '', '', '', ''];

  $defaults = [
    'label' => '_',
    'visible' => FALSE,
  ];

  $extra = [];
  foreach ($ids as $id) {
    $pieces = explode('.', $id) + $fill;
    if (in_array('', $pieces, TRUE)) {
      continue;
    }
    list(,,$entity_type_id, $bundle, $view_mode, $vme_name) = $pieces;
    // $view_mode is not used!
    $extra[$entity_type_id][$bundle]['display']['entdisp_' . $vme_name] = $defaults;
  }

  return $extra;
}

hook_form_entity_view_display_edit_form_alter()

Alter the entity_view_display_edit_form.

In $form['fields'] and in $form['#extra'], we already find one entry for each extra field that we previously registered.

For each of the entry in $form['#extra'] that begins with 'entdisp_', do the following:

Check if the a corresponding entry exists in the settings.
If not, remove the entry from $form['fields'] and from $form['#extra'].
If yes, modify the element in $form['fields'][$name], to give it a label and configuration controls. Have a look at field_group_field_ui_display_form_alter() and at EntityViewDisplayEditForm in core.

This is all a bit tricky and more work than can be explained here. But it is easier than in field_group, thanks to the trick with hook_entity_extra_field_info().

hook_entity_view()

In this hook, for each item in $display->getComponents(), we

look up the corresponding config entry.
add a render element to $build.

It can look somehow like this: https://www.webomelette.com/creating-pseudo-fields-drupal-8


If you are looking for the safest way, I would say your current approach is not how most of us get things done in Drupal.

Basically, you can make use of a hook that wakes up your module, check last run's status and if suitable, start its next run.

Check out hook_cron. You can check last run status easily from a variable_get (you need to set the value first using variable_set). Cron runs anonymously regardless of a specific page call. Even if the cron runs frequently, you can use some condition to check last run timestamp and compare it to current system time. If it has exceeded the interval (1 day), you can now run the "create nodes" function.

If nodes are saved correctly, you will see a $node->nid set. use that as a condition and if all given jobs are done, you can set the last run variable to the current time.


What should I name my overriding render-function?

It depends on what you want to target.

If it's the tree of the menu you can use theme_menu_tree :

function drupal_subtheme_menu_tree__menu__menu_usm_navbar_small($variables) {
   return '
' . $variables['tree'] . '
';
}

if it's the link, you can use theme_menu_link :

function drupal_subtheme_menu_link__menu__menu_usm_navbar_small($variables) {
   $element = $variables['element'];
   $sub_menu = '';

   if ($element['#below']) {
     $sub_menu = drupal_render($element['#below']);
   }
   $output = l($element['#title'], $element['#href'], $element['#localized_options']);
   return '
' . $output . $sub_menu . "
\n";
}

These functions need to be in template.php


Drupal View for the 10 Most Recent Items Sorted by Date ASC

Have a look in the following image. This is a view of the 10 most recent nodes, sorted by post date (ascending).

If you meant to something else, please clarify the question.

If its a working solution for you, you are more than welcome to accept the answer by clicking on the checkmark ✓ (and thumb up if you liked it very much).


Fill the "Unpublish on" date field of the Scheduler module depending on list field

You'd do better to have a custom module that does a form alter on the unpublish date field itself - converting it from a date/text to a date/select.


If you have a theme that supports the output of primary and secondary links in the way you describe (Bartik, the default theme for Drupal 7 does, but it doesn't have the secondary nav below the primary, but rather in the upper right of the header), you can accomplish this by setting the secondary menu to be the same as the main menu. Navigate to admin/build/menu/settings to make this selection.

You can further customize this behavior using the Menu Block module.


How do I add an extra "Add content"-link to the admin toolbar dropdown

This is fairly simple. First, create a your_module.links.menu.yml file in your custom module and add the following:

your_module.admin:
  title: 'Add content'
  parent: system.admin_content
  url: internal:/node/add

Clear cache and you're done!


how to dynamically add new fields to a form using ajax?

You've got the parameters the wrong way round in your callback function; and you should probably take $form_state by reference if you need to change it:

function ajax_callback($form, &$form_state){
  $form_state['rebuild']=true;
  return $form['city'];
}


how to alter notification email in search api saved search module. I want to add more details about the search

hook_mail_alter is your best friend, just keep in mind this hook fired on all emails so make sure you check if your are targeting the search-API emails. Here is a snippet of code copied from the mail_example module:

function email_example_mail_alter(&$message) {
  // For the purpose of this example, modify all the outgoing messages and
  // attach a site signature. The signature will be translated to the language
  // in which message was built.
  $options = array(
    'langcode' => $message['language']->language,
  );

  $signature = t("\n--\nMail altered by email_example module.", array(), $options);
  if (is_array($message['body'])) {
    $message['body'][] = $signature;
  }
  else {
    // Some modules use the body as a string, erroneously.
    $message['body'] .= $signature;
  }
}


How to reset values of elements in multi-step form

As I understand it, you don't need the ajax callback for the remove button. You should be able to do that with just using jQuery, and a rel attribute to hold the ID. Consider the following:

Add a class for the jQuery script and a rel attribute that holds the Step 1 element count id to the remove button.

$form['step2']['step2-'.$key] = array(
  '#type' => 'button',
  '#value' => 'remove ' . $key,
  '#name' => 'step2-'.$key,
  '#attributes' => array('rel' => 1, 'class' => 'remove-button'),
);

jQuery script to remove the "remove" button and reset the the Step 1 form element.

$('.remove-button').click(function(e) {
  var id = $(this).attr('rel');
  $('#element'+ id +').val('All');
  $(this).closest('.button-wrapper-class').remove();
  e.preventDefault();
});

This is (most likely) non-working example code, but I think you'll understand my point.


Display certain field values of submissions from multiple webforms in one view

You may want to read this: https://www.drupal.org/node/2497183

  Views cannot display information from more than one webform at a time
  unless the webforms share the same components.

  One solution would be to add order# as a hidden field so that all
  webforms have a component by this field key. I haven't tried having
  mixed component types for with the same field key, but I suspect it
  will work, at least with some view configurations

You may wind up having to create a template for a module to get the report you are looking for.

Drupal answers actually already has a post on this:
Multiple Webforms in one View


I would like to display only the teaser view of nodes

One solution would be to use the Rules module.
Add a new rule and set this:

Condition:

Node is of type: News Story
Custom PHP: check display_id == full
User rôle: not admin/editor (so you can still view/edit if you're not anonymous)

Action:

Redirect to the page you want (404 or your news list for example)


DRUPAL 7: insert images via URL instead of via "file-upload"

I guess you are having problem to use the module File Field Sources.

Use below steps

Download and install the module
Edit any image field, for ex. Article content type is having image field. Let's use this module over there.
Go to URL : admin/structure/types/manage/article/fields
Edit the field field_image
Check the option to use remote URL there. See screenshot.
Create article content and see there option to use remote URL in image field. See attachment.


Custom field widget: hook_field_is_empty()

I think you want to change your default values to variable_get('yourmodule_variable') so that it displays the value that was saved previously.