Add the Form name to the theme suggestions input field

In your yourTheme.theme, you could do:

function yourTheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  foreach (\Drupal\Core\Render\Element::children($form) as $key) {
    $form[$key]['#attributes']['data-twig-suggestion'] = $form['#id'];
  }

  $form['actions']['submit']['#attributes']['data-twig-suggestion'] = $form['#id'];
}

The function \Drupal\Core\Render\Element::children($form) returns an array of all the children elements (for a form) for which the keys don't start with #.

So, this array will have the field names as its elements. Then, you iterate over the array and add the attribute data-twig-suggestion and its corresponding value. Note that the array will have some extra elements that aren't form fields, and those would also get the new attribute and its value. I don't think there is any collateral damage on that.

For the submit button ($form['actions']['submit']) we are adding the attribute "manually", as the field element (submit) is "nested" inside the actions array, so our previous loop won't have added the attribute to the correct element in the array.

Then, you also add this function:

function yourTheme_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (isset($element['#attributes']['data-twig-suggestion'])) {
    $suggestion_suffix = str_replace(['-'], '_', $element['#attributes']['data-twig-suggestion']);
    $suggestions[] = 'input__' . $element['#type'] . '__' . $suggestion_suffix;
  }
}

Here, each form input field is processed and a template suggestion is added based on the previously created attribute.

PS: this solution is based on this article: Getting granular with Drupal 8 forms.


How do I correctly load user_profile_form() to use in my theme?

Here is the code you need to follow:-

function THENAME_theme(&$existing, $type, $theme, $path) {

return array(
    'edit_profile_user_profile_form' => array(
        'arguments' => array('form' => NULL),
        'template' => 'templates/edit/user-profile',
        'render element' => 'form',
        ),
);
}

Next thing You need to create a file called user-profile.tpl.php and save it in template folder.

In the user-profile.tpl.php file, write the following code to print out the fields:

<?php print drupal_render($form['field_NAME_OF_FIELD']); ?>


A post var error upon webform submitting programmatically

According to this post:

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

If it's a custom webform template, you may need to add, at the end of the form:

<?php print drupal_render_children($form); ?>

See also this related issue here: https://www.drupal.org/node/2417757


As per this support request in Views issue queue: Views: Rewrite field, strips some HTML tags (SOLUTION/WORKAROUND FOUND FOR STYLE TAG) Views strips out certain tags. It does this using filter_xss_admin, which if you look at that API entry calls filter_xss, passing in an array of allowed tags. iframe is not one of those unfortunately.

So I think that you might need to do a workaround. I would look at two ways of doing this:

Rewrite the outut in a Views template. You click on Theme:Information at the bottom of the advanced pane in Views UI and you would select the theme file for the Vimeo field. More at An Intro to Drupal Views Templates and Theming
Create your own theme function to output the iframe. Enable Views PHP and call the theme function from a rewritten Views field.


Ubercart payment option without gateway?

I ended up copying the "Other" option from payment pack. Then I changed all references to "busniess_invoice". Works like a charm!


A clean solution for adding _target attribute on flickr thumbnails

There isn't one - links contained in HTML in a node body are not structured, do not run through l(), and no opportunity is given to 'hook' into them during rendering.

You have 3 options:

Change the markup to include the target attribute.
Preprocess the field and run a regex replace on the HTML to add the attribute.
Use javascript (by far the best option).


Best practice to separate content per city

You said you already had a taxonomy vocabulary holding the countries and cities. This sounds like a good start. You can add a term reference field to the user profile, so that users can select their locations from the same vocabulary.

One idea (which could work without coding) is that you use Entity Reference for referencing terms from this vocabulary on nodes. Then you can use Entityreference prepopulate to fill out the reference fields automatically based on a value in the URI's query string. As the last step you will need to render the content creation links and make sure the URIs contain the taxonomy term selected on the current user's profile. You can do that e.g. with Page Manager alongside with Panels by adding a New custom content pane, where you can use keywords from the User context which you need to add manually to the page.


Un-promote all other nodes when one node is promoted to front page

In the views, you can simply sort the view by updated date on filtered promoted nodes. I think this will solve the issue without any custom code. This might not work in all cases. It will fail when content writer promotes a new node, then updates old promoted node.

You can use below code. For your specific case, you can use $base_root to apply the change on a particular site only.

function MY_MODULE_node_presave($node){
  // if $base_root is equal to my.specific.domain.site, then perform the db_update.
  if ($node->type == 'career' && $node->promote == 1) {
    $update = db_update('node')
      ->fields(array('promote' => 0))
      ->condition('node.promote', 1, '=')
      ->condition('node.type', 'career', '=')
      ->condition('node.nid', $node->nid, '<>');
    $update.execute();
    // Do this if you still face the problem. Also please comment if node_revision update was necessary.
    // $update = db_update('node_revision')
    //   ->fields(array('promote' => 0))
    //   ->condition('node.promote', 1, '=')
    //   ->condition('node.type', 'career', '=')
    //   ->condition('node.nid', $node->nid, '<>');
    // $update.execute();
  }
}


Search API - Search widget with Facet OR Exposed filters clean url

This module should help you getting rid of ugly URLs when using exposed filters:
https://www.drupal.org/project/query_parameters_to_url

  ...

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

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

  Or an even shorter URL if you use the provided alter hooks:
  example.com/events/p/cat_id/0__100--1__101/name/John

  Isn't that a joy to look at?

  ...

Please refer also to this question to achieve the same thing writing your own module.


How do I programmatically log in a user?

This might help someone:

function mymodule_user_login_credentials($username, $password)
{
    if(user_authenticate($username, $password))
    {
      $user_obj = user_load_by_name($username);
      $form_state = array();
      $form_state['uid'] = $user_obj->uid;
      user_login_submit(array(), $form_state);
      return true;
    }
    else
    {
        return false;
    }
}

A better version based on the comment:

function mymodule_user_login_credentials($username, $password)
{
    if($uid = user_authenticate($username, $password))
    {
      user_login_submit(array(), array('uid' => $uid));
      return true;
    }
    else
    {
        return false;
    }
}


To add menu items use hook_menu():

  This hook enables modules to register paths in order to define how URL
  requests are handled. Paths may be registered for URL handling only,
  or they can register a link to be placed in a menu (usually the
  Navigation menu).

example:

function YOUR_MODULE_NAME_menu() {
  $items['a/b/c'] = array(
    'title' => 'Example menu',
    'page callback' => 'example_callback',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'your-custom-menu-name',
  );
  return $items;

}

To learn more about hooks see here


js files inside custom directory deleted after cache clear

Files were added using drupal_add_js inside node body using php filter. Path was 'files/js/myfile.js' without using domain name. I resolved it by changing directory name from 'js' to 'js-custom'. I think 'js' directory was created by some module there and was emptied after each cache flush. Now everything works ok.


The website encountered an unexpected error. Please try again later.

Above error is Drupal specific error, to get more details about this error you need to go to Drupal Logs. You can access Drupal Logs by navigating to "Admin => Reports => Recent Log Messages". These logs are provided by Database logging Module in Drupal Core.

Updates:

  Event is the name of node we use

In Drupal Nodes data is stored into node table and not table named with content type. Check out getting started guide about node. You've to check node table to get all nodes where type is event.

To fetch nodes you can use EntityFieldQuery API. Check example on How to use EntityFieldQuery. And to fetch any fields value, check Programmatically get field values.


How to display a Flag in a tpl file for different View modes?

You actually can display a Flag link as a pseudofield, which can be ordered among other entity elements in the Manage display settings for an entity type. Go to admin/structure/flags and pick the Flag that you need. Next, check Display link as field in the section Display in entity links. You can now use the link in your template files by rendering the node and getting the right field (use Devel for this).

Alternatively, you can output a Flag link by using flag_create_link($flag_name, $entity_id). In that case you don't need a pseudofield.


The Nivo Slider module relies on libraries that have a different license from the module itself. To work around this aspect, the Nivo libraries are distributed apart from the module. Consider this explanation from the licensing page at Drupal.org:

10. Can I write a "bridge module" to interface between Drupal and another system or library?
That depends on the other system.
It is possible to distribute a module that communicates with a 3rd party system over HTTP, XML-RPC, SOAP, or some other wire protocol, that leaves the 3rd party system unaffected.Examples of such systems include Flickr, Mollom, or certain legacy systems.
It is possible to distribute a module that integrates with a 3rd party PHP or JavaScript library, as long as the library is under either a GPL or GPL-compatible license. Examples of compatible licenses include BSD/MIT-style "permissive" licenses or the Lesser General Public License (LGPL). The Free Software Foundation maintains a list of popular GPL-compatible licenses.
It is not possible to distribute a module that integrates a non-GPL compatible library with Drupal, because it would be a derivative work of both Drupal and that other library and would therefore violate either the GPL or the license of the other library. Please be aware that includes some open source licenses that are incompatible with the GPL for one reason or another, such as the PHP license used for most PEAR packages.
If you wish to contribute a bridge module to a Drupal Git repository, please do not check in the 3rd party library itself. Doing so creates a fork of that 3rd party library, which makes it more difficult to maintain and only serves to waste disk space. Instead, provide detailed instructions for users to download and install that 3rd party library for use with your module. If you believe that your module is a special case where it really does need to be included in a Git repository, usually only because you need to make substantial modifications to it in order for it to work, please file an issue with in the Licensing Working Group issue queue first to discuss it.


Tag Users and Taxonomy terms in body field of a post

It will be interesting logic to figure out whether $art is a user or the start of the $art and entertainment taxonomy term, but, regardless, what you are most probably looking for is an input filter that can recognize a pattern in the text and then both create a link to either the user or taxonomy term as well as actually tagging the node with that taxonomy term if it is one.

A start might be to take a peek at the Hashtags Module and change its use of # to $ for the taxonomy portion and then extend it to include users.


Image height/width not saved using CKEditor and Full HTML input format

Looks like this might be a known issue. See this thread for info: http://drupal.org/node/731068


You can create a custom Normalizer to use and Views will respect that. Within that, you can create the output structure however you like.

Here is an example class, where "Collection" is the content type:

<?php

declare(strict_types = 1);

namespace Drupal\mymodule\Normalizer;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\image\Entity\ImageStyle;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\node\NodeInterface;

/**
 * Class CollectionNormalizer.
 *
 * @package Drupal\mymodule\Normalizer
 */
class CollectionNormalizer extends ContentEntityNormalizer {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = [
    'Drupal\node\NodeInterface',
  ];

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function supportsNormalization($data, $format = NULL) {
    if (!is_object($data) || !$this->checkFormat($format)) {
      return FALSE;
    }

    if ($data instanceof NodeInterface && $data->getType() == 'collection') {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $attributes = [];
    $attributes['id'] = $entity->id();
    $attributes['title'] = $entity->label();
    $attributes['summary'] = $entity->get('field_summary')->value;
    $attributes['card_type'] = $entity->get('field_directory_view')->value;
    $attributes['list_image'] = NULL;
    $attributes['url'] = Url::fromRoute('entity.node.canonical', ['node' => $attributes['id']])->toString();

    $media = $entity->get('field_featured_image')->getValue();

    if (!empty($media)) {
      $item = $this->entityTypeManager->getStorage('media')->load($media[0]['target_id']);
      $image = $item->get('image')->getValue();

      $attributes['list_image'] = [
        'src' => ImageStyle::load('collection_listing')
          ->buildUrl($item->image->entity->getFileUri()),
        'alt' => $image[0]['alt'],
      ];
    }

    return $attributes;
  }

}

You also have to declare it in your modules services.yml file:

  mymodule.collection_entity:
    class: Drupal\mymodule\Normalizer\CollectionNormalizer
    arguments: ['@entity_type.manager']
    tags:
      - { name: normalizer, priority: 10 }

You can inject whatever other services you need, used entityTypeManager as an example.

Views will use this instead of the default, so long as the priority is higher. IMO this is far easier than trying to use the Views UI to get the output you want from a REST Export display. You are free to construct the output in whatever way you wish.

So in your case, you would replace "Collection" with "Boat" and check that the content type is 'boat', then build the response as you need it.


How to remove front tag from landing page and logged in home page?

There is th module Page Title that fixed this. Also if you're using Metatag, its functionality has moved into the module. They should let you use a custom title that will remove your site name.


I think you are trying to alter a $theme_registry['aml']['function'] which doesn't exist.

Try have a look through the $theme_registry array, and find what you want to override, put this in where you currently have "['aml']". I am guessing you want "['menu_item_link']", but you will have to check.

Then change theme_menu_item_link to aml_menu_item_link.


Replacing display page with views in template.php

Views' hooks are called whenever a View is called, yet you are calling the creation of the View once again inside of it, and then trying to change that View, not the original one.

Instead, you should be doing something along the lines of...

function mobiletheme_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  switch ($name) {

     case 'calendar':

       // process it here, eg change/add $vars['foo']
       break;

     // other Views here

  }

}

Now, that, changing template variables, doesn't appear to be what you want to be doing, so you will have to look into some of the other Views hooks, most probably views_pre_view to change the display, eg, something like...

function mobiletheme_views_pre_view(&$view, &$display_id, &$args) {

  if ($view->name=='calendar' && display_id=='page_classic') {
    $view->set_display('page_mobile');
  }

}

Addition/Caveat:  This appears to have to be called from a module, not a theme (at least in D6), so you may need something like this...

function mobilemodule_views_pre_view(&$view, &$display_id, &$args) {
  global $theme;

  if ($theme=='mobiletheme' && $view->name=='calendar' && display_id=='page_classic') {
    $view->set_display('page_mobile');
  }

}

...inside a small module.


What's the difference between Page manager and Panels?

Ctools

In Ctools, there is a sub-module called "Page manager". This module, at it's core, is a graphical user interface to hook_menu. It allows you to either create new paths in the system, or take over some of the ones provided by Core.

Page manager

Once Page manager manages a path for you, it can do several different things with it. Out of the box, it can provide redirects for you. One common use case for this, is to deny access to nodes that lack proper theming because they are not meant to be viewed on their own, such as "Fact boxes" or "Image nodes". Another is to redirect from a term view to a Solr search of the same term.

One of the main benefits of Page manager, is that it introduces a way of dealing with "Context", not to be confused with the module Context. The kicker here, is that Panes, which are "slightly smarter blocks", can declare their dependencies to the system, and them have the actual arguments (called Contexts) passed in dependency injection-style.

For those unfamiliar with DI, but familiar with Drupal, this, for example, allows you to never need to use menu_get_object again to get "That one and only node referenced from the menu path". What if there's more than one node in the path? Or if you really want to base the block on a node from an entity reference? This becomes a non-issue with Page manager, making all blocks (panes) much more flexible and re-usable.

Panels

The most common use case however, is to hand over the layout, and rendering of the path, to Panels. Panels provides tools to define layouts, either in code or directly in the browser, and the lets you place content directly in the browser.

Conclusion

Both of these modules are very powerful, and relatively poorly documented, which has lead a lot of people to be frustrated about them. Understanding how to use them is however well worth it if you are building a larger site, especially since their approach to handling "pages", as well as layout, looks like they are going into Drupal 8 core, courtesy of EclipseGC's SCOTCH initiative. Relevant sandbox project

Further reading

Examples of other interesting things one can do with these tools:

If Context is used as a sectioning tool, Panels can work in tandem with it and be used as a layout tool.
Panels can interact with Display suite to provide it with a nice drag-and-drop UI.
Page manager and Contextual Administration can help building in "Context" sensitive menues and other helpful things for site admins/editors.


Simple order cancellation in Drupal Commerce, with 24 hour time limit?

I haven't tested any of this, but you might some of the following useful:

Entity Operations allows you to take a Rule and turn it into a menu tab. This would be one way of getting that onto the order view page.

Something I've really been wanting to try is the Entity action links sandbox:

  Allows actions and rules components to be executed via AJAX links on entity view.

Just note the patches discuss in the Sandbox README.

If you wanted to do the Rules route, these would be probably your best option, because you can use conditions and components to provide some sort of response or action system based on the order status and time.

Otherwise, you'd need to create a custom module with a custom access callback that does the appropriate checks and then executes the action if allowed. (For a developer, I think this would actually be an easier route.) But the rules stuff is intriguing.


Based on user's country filter content of same country?

What you're missing is the bridge between users and content, and that comes through Relationships (connecting different tables from the database).

You can do this by approaching from either the content end, or the user end (Content Views or User Views type). Since the goal is to list content, I think it makes more sense to start from the content end, unless you need some more user handling that would be easier from the user then.

Create a Views showing your Content (Page or a Block, which ever suits you best)
Add a Relationship Taxonomy term referenced from field_country (you probably have a different field name), you can require it since you only want nodes in the list that don't have Country empty
Add another Relationship User using field_user_country (you probably have a different field name), it will use the above Relationship by default. You can require it since you need users who also have the Country field not empty.
Add a Contextual filter ID from User Category and it will use the second Relationship by default. Configure it:
When the filter value is NOT available
Provide default value
User ID from logged in user
When the filter value IS available or a default is provided
Specify validation criteria
User ID
Single ID
Hide view
Adjust any other Views settings relevant to you and Save the View
If you've created a Block and need to place it in a Region in your theme, don't forget to adjust the Contextual Views options on the Block configure page.


Error after upgrading ecommerce kickstart is breaking my start

The only reason commerce_info_fields() should have gone AWOL is if the commerce.module file was removed from your server or the module was somehow disabled during your update process. Check those two things: if it's missing, put it back. If it got disabled, try to re-enable it. No clue what about a drush based update would have caused the issue, but I also am unfamiliar with how drush updates distributions. For reference, we document how to update here:

https://drupalcommerce.org/commerce-kickstart-2/install


Add HTML code outside content area on every page load

Content is a region in your theme. Site content goes into regions. So, typically you can only put things in defined regions such as Header, Footer, Left Sidebar, Content.

You have slight flexibility with #prefix and #suffix render array attributes. You either have to edit the html.tpl.php file, or define your own region within a theme. Or you can supply your own hook_theme() implementation to hint when using your own html.tpl.php template file.


image disappears which uploaded with managed_file type

Drupal prunes files that haven't been explicitly marked as permanent. This happens on a cron job, which explains the delay you're seeing.

To avoid this, you need to add a submit handler to your form which updates the status of the file. e.g.

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


Get node_type entity for default value in form

You can load a node_type entity by specifying the node type id

$node_type_entity = \Drupal\node\Entity\NodeType::load($node_type_id);

or if you have multiple node types an array of entities:

$node_type_entities = \Drupal\node\Entity\NodeType::loadMultiple($node_type_ids);


How do I serve up a themed 500 error response page?

You may create custom exception subscriber as it is shown below.
Notice that I did not use Drupal theming engine to render the error page. Uncaught exception indicates that something really wrong has happened on a site. There is a great chance that some Drupal services are not available so rendering error page may fail as well.
Also keep in mind that exception subscriber won't catch fatal PHP errors because they are handled differently.
src/EventSubscriber/ExceptionSubscriber.php
<?php

namespace Drupal\example\EventSubscriber;

use Drupal\Core\EventSubscriber\DefaultExceptionSubscriber;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Last-chance handler for exceptions.
 *
 * This handler will catch any exceptions not caught elsewhere and send a themed
 * error page as a response.
 */
class ExceptionSubscriber extends DefaultExceptionSubscriber {

  /**
   * {@inheritdoc}
   */
  protected function onHtml(GetResponseForExceptionEvent $event) {
    if ($this->getErrorLevel() == ERROR_REPORTING_DISPLAY_VERBOSE) {
      parent::onHtml($event);
    }
    else {
      $content = file_get_contents(DRUPAL_ROOT . '/../500-error.html');
      $response = new Response($content, 500);
      $event->setResponse($response);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Catch the exception just before default exeception subscriber.
    // @see Drupal\Core\EventSubscriber\DefaultExceptionSubscriber::getSubscribedEvents()
    $events[KernelEvents::EXCEPTION][] = ['onException', -255];
    return $events;
  }

}

services.yml
services:
  example.exception_subscribtr:
    class: Drupal\example\EventSubscriber\ExceptionSubscriber
    arguments: ['@serializer', '%serializer.formats%']

    tags:
      - { name: event_subscriber }

Note that you need to have error reporting set to something other than verbose for this to work (unless you alter the code above).  This can either be controlled in the CMS here: /admin/config/development/logging or it may be overridden in your settings.php file.  For example, you might need to set
$config['system.logging']['error_level'] = 'hide';

Also note, that if your file_get_contents throws a fatal error, you will get the standard error for uncaught exceptions: "The website encountered an unexpected error. Please try again later."
Here's two ways you can trigger a 500 error for testing:
use Symfony\Component\HttpKernel\Exception\HttpException;

throw new HttpException(500);

or
/** @var \Drupal\Core\Template\TwigEnvironment $environment */
$environment = \Drupal::service('twig');
$environment->loadTemplate('this-template-does-not-exist.html.twig')->render([]);


Create a Json view of the user, with the format of the user/login response

When you query /user/login it defaults to currently logged-in user.

I suppose you need to create a view with a "REST export" display. The view defaults to "Entity" row style, change it to "Fields".

In "Fields" settings, you can rename the labels that are output in "Alias" fields:

In this "REST Export" view you will have set a path. i.e. /rest/people

Querying /rest/people?_format=json should output something like this:

[
  {
    "user_name": "admin",
    "user_id": "1",
    "user_customtext": "Custom text"
  },
  ...
]

You can use the Global - Custom text field to concat multiple fields as tokens, then hide those fields from being displayed:


jQuery Uncaught TypeError: Object # has no method 'on'

on() was only added in jQuery v1.7; Drupal 7 ships with jQuery v1.4, and can be updated to 1.5 using the jQuery Update module. The reason you're getting the error is simply that the lightbox library you're using is written for jQuery v1.7 and above.

See How do I update jQuery to the latest version I can download? for some ideas on how to get round this.


Create a cron job to automatically clear cache

Thanks to @No Sssweat, @kiamlaluno, @Rick B, I've got an answer.
Firstly, I learned that is not a good practice to clear cache automatically every minute or so often.
Secondly, I figured out that I can solve this problem without using a cron job at all, but I have to understand these tag based caching mechanisms.

The problem was as in the image attached below, Page-Caching was Tag Based, so selecting None option solved my issue.


This is step by step solution that I use to get this done:

Create new content type with image field
Install Field Slideshow and View Slideshow modules
Create new View of type Slideshow
Add image field from created content type in View, than set 'Slideshow' for 'Formatter' of that field and choose settings that you want for slideshow
That's it, you have slideshow of images inside slidedeshow...


Help needed with hook_node_submit in custom module to save data

So now I can answer my own question:

In my module I had $form['container'] defined in the hook_form_alter(), but the actual field $form['container']['main_taxonomy_term'] wasn't defined yet as I was adding it in my callback, so naturally Drupal didn't know about the field when rendering the form.

I restructured the module, moved the $form['container']['main_taxonomy_term'] = array(...) into the hook_form_alter(), created a new function to get the select options, calling upon it in various circumstances, added some extra checks for the edit node form as the options had to be built from the database values upon first display, but after that use $form_state else it wouldn't refresh the list upon editing the checkbox selection...

Oh well, so i finally managed to get it working without error message.

Maybe this is helpful for anyone, or maybe it isn't at all.


How Do I pass the Option description in Checkboxes to a webform result

It roughly depends on how you build that form element. Form API or Field API? Seems you are with Field API here. In general all you have to do is to provide an associative array for the options where key equals value.

Form API

Here comes a simplified example for Form API. You might want to use $options = array_combine($my_array, $my_array); to build the options array dynamically.

$options = [
  '21' => '21',
  '22' => '22',
  '36' => '36',
];

$form['my_element'] = [
  '#type' => 'checkboxes',
  '#title' => 'Choose',
  '#options' => $options,
]

Field API

With Field API and the list field you have to build the associated array in the Allowed values list like in the following example. Simply divide key and value with a pipe character.

21|21
22|22
36|36


How can I change the default branch of a contributed module?

Turns out it's a setting on your Drupal.org version of the module page. Visit edit > default branch on the page-specific menu of your module.

At the time of creating this question, the documentation page from 2012 (last updated 2015) is still close enough to be helpful.


You need to create subfolders like this:

yourdomain.com/drupal/sites/site1.com

yourdomain.com/drupal/sites/site2.net

yourdomain.com/drupal/sites/site3.org

and park domains site1.com , site2.net , site3.org to folder yourdomain.com/drupal/


I would approach this by building a view that has relation to current user selected taxonomies. Then listing content according to that.


Does node_load() function prevent multiple loading of the same node?

Yes, node data is statically cached per request, if the requests are for un-revisioned nodes. No, you don't need to do the caching yourself.

The cache read/write happens in NodeController::load() if you're interested in what's going on behind the scenes.


How to configure drush command-specific archive-dump --tar-options in a site alias

It should be like this - Edit: I've just confirmed that the following works as expected with Drush 6.3:

$aliases['example.com'] = array(
  'uri' => 'example.com',
  'root' => '/var/www/example.com/public_html',
  'command-specific' => array (
    'archive-dump' => array (
      'tar-options' => '--exclude=directory1 --exclude=sites/all/modules --exclude=*.txt',
    ),
  ),
);

I did notice that %files didn't work (Warning: sprintf(): Too few arguments exec.inc:138).


How can i change the form default value but not via hook_form_alter

Let assume you want to create a page. Then create button A which redirect user to /node/add/page?button=a and button B redirect to /node/add/page?button=b

Then in your module create hook_form_alter for node form

function MODULE_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'page') {
    if ($_GET['button'] == 'a') {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'aaa';
    }
    elseif ($_GET['button'] == 'b') {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'bbb';
    }
    else {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'ccc';
    }
  }
}


Using Migrate API with a multi-page / paginated source

https://www.drupal.org/node/2640516 is the issue to add this support to migrate_plus.

In the meantime, in a case where I knew up front how many pages there were, I simply listed the pages in the urls configuration:

source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls:
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500&startrow=501
    - http://www.example.com/api/search?query=blahblahblah&rowlimit=500&startrow=1001
...


How to check if file has changed during (hook) form_validate in a form?

There are 2 approach we can look into:

Query the DB using db_query in field table, like if your field machine name is field_image, then its field will be field_data_field_image, and get fid of a particular node, in this case fid will be in field_image_fid

SELECT field_image_fid from field_data_field_image WHERE entity_id=NODE_ID

It will get u previous fid, and u can validate

Load Node from nid, either using node_load or entity_load_single, from here you will get your Old FID, as image has not yet been attached to the node, it has only been saved in file_managed Table.


I would like to create a view where I can add tags to content

First off, if all you need is a check box on your node form which toggles something as on or off - basically, a "Featured" state in this case - using taxonomy to achieve this is overkill. All you really need is an instance of a "Boolean" field.

Second, you can use Views Bulk Operations to operate on the results of a View. Basically, you can create a View with a column of check boxes much like the default content list in Drupal core. You can check a list of items - Beverage nodes in this case - and then select an operation to apply to the items you've checked. So yes, you'd need a custom module - a fairly simple one which would define "Make Featured/Unfeatured" actions, then implement callbacks to programmatically set/unset the "Featured" values on the selected nodes. See the VBO development guide for instructions on how to implement this.


Contextual Shared comments on nodes that are clones of one another

There's many routes which to take for this. Drupal 8 gives you a bit more flexibility than previous versions. For the sake of managing a shared comment section, you can go about creating a new body-less content type that only contains:

A comment field
A node reference field with 2 entries (one for the parent & child cloned node)

Upon your clone operation, you can create a new entity with a dummy, to-be-hidden, title and the node reference field populated with the parent/child nodes.

For display/commenting, you can create a block view that uses a Provide default value: Raw value from url (Path component: 2) (i.e. the node id) contextual filter so the block only displays the shared comment entity on viewing the child/parent nodes.


Customize output style of views filter fields

The CSS classes given by Views should normally be good enough, if you don't know how to find them you may using a chrome or firefox browser: right click on the filter field and then inspect element

Or if you want you may install the Better exposed filters module and follow the intructions given in this question

UPDATE:

As per your comment below, how to group filter fields under one div ?, it is out of the scope of the original question and for that you will have to ask another question.

However, I believe that what you are asking for is not doable using the views UI and you will have to write your own custom codes, for that you may find the below links somehow useful even if they are referencing the D7 version:

Wrapping fields together in a views exposed filter
Place exposed filters in a fieldset
Views Grouping field to use a shared wrapper div
Views exposed groups Module for D7


Move Comment form/render out of node.tpl.php (into separate region)

You should be able to just hide() the comments in the node template and then create a block that calls menu_get_object() and then prints them there...


How to query for entities without a value for a specific field?

The SQL implementation of EntityFieldQuery doesn't support this, because it builds the query using INNER JOINs instead of LEFT JOINs. I consider this a bug, please open an issue in the core queue.


Multiple node access rules for same node?

Is there a way to allow more than one module to use node access rules?

The problem with hook_node_access_records() and hook_node_grants() is that, independently from the weight of the modules, once a module returns 1 for "grant_view," "grant_update," or "grant_delete" that permission is allowed to the user. If a module returns 1 for one of those operations, and another module returns 0, the access is allowed, independently from the priority given to the records returned from the modules for those records.

In Drupal 7 it is also possible to use hook_node_access(), which is able to report if the user has access or not to the node, or if the hook implementation let other implementations  decide if the user has access to the node (using the value NODE_ACCESS_IGNORE).

In Node access rights it is explained how the node access is checked.

  In determining access rights for a node, node_access() first checks whether the user has the "bypass node access" permission. Such users have unrestricted access to all nodes. User 1 will always pass this check.

  Next, all implementations of hook_node_access() will be called. Each implementation may explicitly allow, explicitly deny, or ignore the access request. If at least one module says to deny the request, it will be rejected. If no modules deny the request and at least one says to allow it, the request will be permitted.

  If all modules ignore the access request, then the node_access table is used to determine access. All node access modules are queried using hook_node_grants() to assemble a list of "grant IDs" for the user. This list is compared against the table. If any row contains the node ID in question (or 0, which stands for "all nodes"), one of the grant IDs returned, and a value of TRUE for the operation in question, then access is granted. Note that this table is a list of grants; any matching row is sufficient to grant access to the node.


Views plugins are testable, and Drupal core has a lot of examples.  I believe most aren't UnitTestCase (or \PHPUnit_Framework_TestCase), but rather KernelTestBase tests.

KTB tests will boot a minimal Drupal setup so you don't have to set up extensive mocking for dependencies, especially config and database.

Views in particular has ViewsKernelTestBase, which does basic setup for testing Views plugins.  You can use your IDE to find usages of this for example, but I know some are in web/core/modules/datetime/tests/src/Kernel/Views/

Essentially, you make a test module that has YAML for your test views.  The test declares this in its $modules list, along with the module that is providing the plugin.  You also define the test views, and these get imported.  You can then use the Views API in your test methods.

Then, as long as you use the new ViewsKernelTestBase, you can run it directly through PhpUnit, assuming you have your phpunit.xml setup properly.


You could use the Shared Email module.

The shared email module allows multiple users to use the same email address for different accounts. The module works for both registration and account updates.

Users using that module could also be interested in the Shared Email Password Reset module.

This module will have users reset their password based on both email and user name, there are some cases where this module can help when using the Shared Email module or when there is a requirement that passwords should be reset only if email and username matches.

Both the modules have a Drupal 8 version, and they are declared compatible with Drupal 9.


How to force cron to use config saved during a SimpleTest?

As commented, you were missing the save call in the test.

That means that the change is only in the runtime object returned by getEditable() and since get() and getEditable() do not share the static cache, you didn't see the change.


How do you create a block of fields to a second Profile2 using views?

Using Configuration

You can use the Views module to access the Profile2 fields.

Below is a quote from ltiong on Drupal.org regarding accessing fields from multiple profile types.  The same process applies to accessing a single Profile2 type.

  5.1 create View (Show:User)
  5.2 add relationship, (User:Profile); give the Identifier a unique name ie 'MainProfile'; select a single checkbox for 'Profile type',
  in my case 'Main profile';
  5.3 add another relationship, (User:Profile); give the Identifier a unique name ie 'EducationProfile'; select the other checkbox for
  'Profile type', in my case 'Education profile';
  5.4 add Fields to view; select Profile2 field items; use Relationship dropdown in 'Configure field' to associate w/ correct
  relationship;

You can output as a Block, and use the Page URL to retrieve the correct user ID to load. (For your views context)

Using Code

You can use the profile2_load_by_user(); function to programmatically retrieve Profile2 data.

$profile_data = profile2_load_by_user($user->uid);

See also: profile2_load_multiple()


Printing the last 6 characters of a field into a confirmation email

You could probably use the rules module with the "Execute custom PHP Code" option to execute a small php substr function.

You might need to enable the php filter module for this.


How to use variables in a PHP evaluation in a rule?

You can achieve this,  use variable module and define variable which you want use in rule.

To define a variable you need to write custom module , which will contain following function

function My_module_variable_info() {
  $variables['rainbow_count'] = array(
  // 'name' isn't really necessary, as it will get populated from the key of this array above.
 'name' => 'rainbow_count',
 'title' => t('Number of Rainbows'),
 'type' => 'number',
 'group' => 'UserPoints Config',
 'token' => TRUE,
'default' => 0,
'description' => t('Specify the number of rainbows.')
);

}

Set value for variable which you want use in rule through :

configuration>>variables>>modules>>My_module_...

Now go to rules >action> grant points to a user > Points:

Set data type =current-user:uid  and put return variable_get('rainbow_count'); code in PHP evaluation.

This solution worked for me,hope will help you also.


How to hide Profile2 entity fron user view?

At admin/people/permissions you can configure what user roles are allowed access to the Profile 2 profiles on a per-profile-type basis. So if you're alright with letting admin users see the profiles, you can hide them for everyone else with the permission controls.


Facet blocks are not appearing, when indexed view block is called programmatically with views_embed_view

For now, i have fixed it, putting the facet blocks also in the page.tpl.php, for me in the first sidebar. I iterated all active facet blocks in the block table an d then displayed each one with this code:

        $block_facet = block_load($module, $delta);
        print render(_block_get_renderable_array( _block_render_blocks(array($block_facet))));


Adding custom variable to twig's html.html.twig which is not cachable

Ok - so to write your own extension see this answer, refeer to the twig tweak module. Or follow this article, that's it's content adapted to session (using a funcition) - like twig tweak, but different form the linked answer:

In this exemple, we built an extension du display a Drupal block directly from a twig template :

{{ session_var('my_var_name') }}

To to it, you must create a custom Drupal module. You can use the Drupal console to easily create your module.

In your module folder, frist create a new class in in a src subfolder :

For exemple : src/MyTwigExtension.php

<?php
namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'session_var';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('session_var',
        array($this, 'session_var'),
        array('is_safe' => array('html')
      )),
  }

  public function session_var($key) {
    return \Session->get($key);
  }

}

In a second time you must register your extension as service :

Create a service configuration file

# src/MyTwigModule.services.yml
services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }

And you are done :-)

You can now enable your module and use your Twig extension.

The simple workaround could look like this in twig:

{% app.session.get('cart')|length %}


Elysia cron has a hook specifically for that; hook_cronapi():

function hook_cronapi($op, $job = NULL) {
  $items['key'] = array(
    'description' => 'string',
    'rule' => 'string',
    'weight' => 1234,
    'callback' => 'function_name',
    'arguments' => array(...),
    'file' => 'string', // External file, like hook_menu
    'file path' => 'string'
  );

  $items['key2'] = ...
  ...
  return $items;
}

Taken from the API.txt file included with the module.


How can I programmatically get various common user profile related URLs?

The user URLs (or routes to be more "Drupal correct") are defined by the core user module (core/modules/user/user.routing.yml)
E.g.
user.register:
  path: '/user/register'
  ...

user.login:
  path: '/user/login'
  ...

user.logout:
  path: '/user/logout'
  ...

user.page:
  path: '/user'
  ...

So you can programmatically build links to these routes like so:
<?php

use Drupal\Core\Link;

// Replace user.login with other routes such as user.page
$user_login_link = Link::createFromRoute(
  t('User log in link'), // The link text
  'user.login', // The link URL generated from the route
);


Loading nodes from another Drupal database using Views

Consider looking at the Forena module. It can be used to query (not update) the data in other databases. Various DBMS formats are supported, such as another Drupal database also.

Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports. For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

Forena documentation - use the link 'Reporting documentation' or visit relative link /reports/help.
Forena samples - use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

Disclosure: I'm a co-maintainer of Forena,
I hope this does not violate the site's policy on self-promotion.


Twig Template print field - if not node number

Yes. Sometimes themes will drop documentation when they override a template, but you can always check the original template file for the available variables and other info relevant for working with the template. If you check the node.html.twig template provided by the node module in core, you'll see the following documentation at the top of the file.
/**
 * @file
 * Default theme implementation to display a node.
 *
 * Available variables:
 * - node: The node entity with limited access to object properties and methods.
 *   Only method names starting with "get", "has", or "is" and a few common
 *   methods such as "id", "label", and "bundle" are available. For example:
 *   - node.getCreatedTime() will return the node creation timestamp.
 *   - node.hasField('field_example') returns TRUE if the node bundle includes
 *     field_example. (This does not indicate the presence of a value in this
 *     field.)
 *   - node.isPublished() will return whether the node is published or not.
 *
 * ... continued ...
 *
 */

Note the relevant info here:

The node entity [is available] with limited access to object properties and methods. Only method names starting with "get", "has", or "is" and a few common methods such as "id", "label", and "bundle" are available.

This means you can access the node id with node.id.
So, you can print your field on nodes other than your specific node by wrapping your field in a conditional like:
{% if node.id != 45 %}
  {{ content.field_big_image }}
{% endif %}

or
{% if not node.id == 45 %}
  {{ content.field_big_image }}
{% endif %}

Either choice should produce the same result.


Your code currently loads the form with the _form routing definition. For classes extending ContentEntityForm, you have to use the _entity_form notation instead. Here is an example of an 'module_name.routing.yml' file:

kollektivhampel.pdf_erstellen_form:
  path: '/intranet/{my_entity}/something'
  defaults:
    _entity_form: 'my_entity.default'
    _title: 'Your page title'
  options:
    parameters:
      my_entity:
        type: my_entity
  requirements:
    _permission: 'some permission defined in your module_name.permissions.yml file'

The     _entity_form is composed of two parts: before the dot, you have the entity type id, in this example my_entity. Behind the dot, you have the name of the form, defined in the handlers section of the @ContentEntityType annotation. In this case, the second part is default, According to your question's code, this refers to \Drupal\my_entity\Form\MyEntityForm. You might not need the route_callbacks code, as a static routing directly in the yml file is probably enough.

For more details, see https://www.drupal.org/docs/8/api/routing-system/structure-of-routes.


You could render content as table using Theme Table

<?php
$table_element = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' =>t('Your table is empty'),
);
drupal_render($table_element);
?>

Here are some Examples for it:

Examples of theme_table() in Drupal 7
A Drupal theme table example
Drupal for Beginners: How to Create a Table Using theme_table()


How to use commerce_cart_order_product_line_item_delete?

The function accepts the $commerce_order object not just the order_id. You could try

commerce_cart_order_product_line_item_delete($order, 70);

commerce_entity_reference_delete is defined in commerce.module so it should be available, if commerce is enabled and at current version.


Check out the rules module. You can set up a rule that accesses other module (search for a sms module), or core features (like mail).


You can avoid the notice error by checking if that field has data, e.g

if (isset($node->field_recipe_skill_audio[$node->language][0]['filename'])) {
  /* Do stuff */
}

or

if (isset($node->field_recipe_skill_audio[LANGUAGE_NONE][0]['filename'])) {
  /* Do stuff */
}


hook_block_view called multiple times per request

It gets called everytime the block is rendered.  Truthfully, that is a bit wasteful since the params it is passed are the same.  Still, in the normal block system, each block only loads once (i.e. it can only be in one region).  This makes the logic forgivable, but yeah, it should be cached.  You can of course cache it yourself in your hook_block_view implementation.

Disclaimer: I am drunk.


Programmatically get menu links filtered by language

@pbonnefoi.
I've played a lot around with a filtering of menu items by language while worked on menu block multilingual task.

Here what I got:
Drupal\menu_link_content\Plugin\Menu\MenuLinkContent is responsible for retrieving of menu_link entity, but this class hides from us getEntity() method, using one we could get menu link language ($link->getEntity()->get('langcode'))

So the trick is:

Extend this plugin by a new method getLanguage() and register it. This plugin used in
the menu.tree_storage service, also you need to change link
provider class and plugin class to yours.
Create a new manipulator yourmodule.menu_manipulators:filterByLang,
and use it wherever you want like: ['callable' =>
'yourmodule.menu_manipulators:filterByLang', 'args' => ['langcode'
=> $langcode]]

Result code can be something like:

class MenuMultilingualServiceProvider extends ServiceProviderBase {

  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('menu.tree_storage');
    $definition->setClass('Drupal\yourmodule\Menu\MenuTreeStorageMultilingual');
  }
}

class MenuTreeStorageMultilingual extends MenuTreeStorage {
  protected function doCollectRoutesAndDefinitions(array $tree, array &$definitions) {
    foreach ($definitions as &$definition) {
      if ($definition['provider'] == 'menu_link_content') {
        $definition['class'] = 'Drupal\yourmodule\Plugin\Menu\MenuLinkContentMultilingual';
      }
    }
    return parent::doCollectRoutesAndDefinitions($tree, $definitions);
  }

  protected function loadLinks($menu_name, MenuTreeParameters $parameters) {
    $links = parent::loadLinks($menu_name, $parameters);
    foreach ($links as &$link) {
      if ($link['provider'] == 'menu_link_content') {
        $link['class'] = 'Drupal\yourmodule\Plugin\Menu\MenuLinkContentMultilingual';
      }
    }
    return $links;
  }

}

UPDATE:
Also tuutti created another solution for that using a new menu tree manipulator menu_block_current_language_tree_manipulator::filterLanguages inside a new menu block type.

Here is his sandbox https://www.drupal.org/sandbox/tuutti/2832329

Also welcome to the discussion regarding translatable menu links on the d.o https://www.drupal.org/node/2466553

UPDATE 2:
I've created a module for the end user to bring multilingual features to the menu blocks https://www.drupal.org/sandbox/matsbla/2831709

You can refer to it as an example of all said above.


If nid reaches the maximum your site will no longer be able to create new nodes as there will be SQL errors whenever Drupal tries to insert a new nid.

Chances are though, that drupal.org will hit this limit before you do, regardless of what you're doing to your site in any useful real-world application.

If drupal.org gets anywhere close to 4 billion nodes, there definitely will be a workaround readily available for you.


How to setup the recipient email in the webform mail template file?

You cannot set the recipient in a template file, these files are only used for the theme layer. The templates only control the display of information.

The recipient email must be set on the settings page of the webform.


Passing arguments from Panel to View without url or using contextual filter from panel to field of taxomony term within view

The easier (semi-automatic) way I can think of
is to

Override the path /taxonomy/term/%taxonomy_term
(enable the *term_view* page provided in system) in Page manager.
Build a page with panels for this path.
Now your content panes, when used in this page, can get their arguments
with the 'From panel argument' option.

You can always have SEO-friendly URLs like
mysite/education/fellowships/surgical or mysite/education/fellowships/transmed
with path (in /admin/config/search/path/add).

The other way is to use the 'Input on pane config' option
for your content panes.
You will have to set the arguments for these panes manually
in their settings dialogue.
In your case, the argument should probably be the (numerical) term ID.
This way your content panes don't need to be tied
to a specific path pattern, and you can have
some logical combinations in your contextual filters,
such as 1+3+5 (term 1 OR 3 OR 5).
This can get quite laborious, though.


Matt -
The user_mail_tokens is a function provided by the user module (Drupal 7 core). Essentially, what your code is saying is:

If the function user_mail_tokens exists (which it should because it's a core function, however these conditional checks are awesome and important), then we are going to include an include file located at /sites/all/modules/modulename/modulename_e.inc.

As to why your code is throwing an error for user_mail_tokens that is an interesting question. I'm looking into it now. Part of me wonders if we should  just say module_exists

What is the need to check the user_mail_tokens?


One approach would be to use the Domain Access module.  Not sure if you can use it with subdirectories, but you can use it with subdomains.  Basically, you would create an "affiliate" (module's term for a site) for dogs and one for cats, and configure as needed.


How can I allow admins to choose anything from an Entity Reference field while restricting it for everyone else?

The solution was to use hook_views_pre_build. That hook lets you edit the view's criteria before it actually gets run. Here's my full code:

function mymodule_permission() { // Create the permission for privileged users
    return array(
        'create jobs for any company' => array(
            'title' => t('Create Jobs for any Company'),
            'description' => t("Don't limit the Company field in the Job node type to only those Companies assigned to the user."),
        ),
    );
}

function mymodule_views_pre_build(&$view) {
    /* If it's the right view and the user has the above permission… */
    if($view->name === 'job_company_entity_reference' && user_access('create jobs for any company')) {
        /* …then get rid of the view criteria that limit the choices for everyone else.
        (I found these by enabling the devel module and calling dpm($view) at the top of this function.) */
        unset($view->filter['uid_current']);
        unset($view->relationship['reverse_field_company_user']);
    }
}


How does Drupal 7's SQL call for 'node' and retrieve an image?

It's utilizing a loaded entity to fill in these placeholder columns. Per the views_handler_field_field::query() docs:

  By default, the only columns added to the query are entity_id and
  entity_type. This is because other needed data is fetched by
  entity_load(). Other columns are added only if they are used in
  groupings, or if 'add fields to query' is specifically set to TRUE in
  the field definition.

In the post-execute phase, during views_handler_field_field::post_execute(),  you can see where the field values are dropped in from the entity values.


Possible to turn off Twig debug mode for a specific template?

There is also this alternative found here and here where you can do something like this using the triple filter |render|striptags|trim :

<img src="{{ url_image }}" alt="{{ title|render|striptags|trim }}" />

It worked perfectly in my case (|escape didn't work)


How do I change order of completion rules in checkout?

You should be able to edit the rule and set it's weight:

Screenshot, showing reaction rule with weight of "2"

Lastly, your rule should still fire, even with a different weight. If it's not firing, it's probably an issue with that rule itself.


Limit/nullify entity reference query/loading of select options, if using hook form alter to populate with ajax

I have managed to achieve this using hook_entity_query_alter. I am not sure if this is the best approach.
You can set the limit using the $query->range($start, $length).
Return 1 row.. $query->range(0,1);
See https://api.drupal.org/api/drupal/includes%21entity.inc/function/EntityF...

<?php
/**
 * We don't want to load thousands of courses into the student course entityreference field as
 * we populate it with ajax, so add LIMIT 0 and database should return empty result set
 */
function mymodule_entity_query_alter(&$query) {
  // check if we got our field
  if(property_exists($query, 'metaData') && $query->metaData['field']['field_name'] == 'field_student_course') {
    $query->range(0,0);
  }
}
?>


How to compare the already saved value of node and updated value?

node_save(), which invokes hook_node_update(), contains the following code.

// Load the stored entity, if any.
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}

So, every time a node is updated, $node->original will contain the node object before it is updated.

To get, for example, the value the field_example field had before the update, you use the following code.

$old_value = field_get_items('node', $node->original, 'field_example');

To get the updated value for the same field, you use the following code.

$new_value = field_get_items('node', $node, 'field_example');


How to have separated enabled modules in multisite based on Domain Access?

It's been a year or two since I have used the Domain Access module on a site, but I don't think this is possible.

Domain Access runs all of the affiliate sites out of the same database, so there is a single {system} table, which is where all of the module info it.  Essentially, the module provides some content access rules based on domain (ie, node_access() based controls), along some helpers for other site-specific tasks and integration with other modules.  In the end, though, you still have a single database which means you have a single site.


How to display multiple multi-value fields inside one for loop?

If you use square brackets [] in twig, you don't need a period .

{% for key, item in content.body if key|first != '#' %}

  {{ item }}

  {{ content.field_text[key] }}

  {{ content.field_image[key] }}

{% endfor %}

A better solution for this might be a field collection or a paragraph, because you depend on that the user is keeping the deltas of the fields in sync.


How do I programmatically check if a context is active?

I figured it out: The Context module defines a service for getting the ContextManager object, which has getActiveContexts(). You can obtain it using the following code.

$activeContexts = \Drupal::service('context.manager')->getActiveContexts();

I need to read Service Container.


I achieve this by using Purl with help of mytheme_url_outbound_alter()


It sounds like you're looking for a Contextual filter.

You create a Page Display with a path of your choosing that is displaying many Content types. This is your page that lists all of them, for example my-content-types.

Then you add a Contextual filter to that View called Content type from Content Category.

Configure it with these options:
    When the filter value is NOT in the URL
    Display all results for the specified field
    When the filter value IS in the URL or a default is provided
    Specify validation criteria
    Validator Content type
    Case in path Lower case
    More
    Transform spaces to dashes in URL

You can leave other options as default, although you should read them all and adjust to your needs, for example what Views should do in case your argument doesn't validate, or you need more than one content type filter on the same page.

This Contextual filter adds options to your path based on the content types you have on your system. If you add the name of a content type to your path (in your browser Location bar):
my-content-types/article the Views results will reduce the list to only show Article nodes.

If you enter a path my-content-types/page it will list only Basic page nodes.

There is also an option to override the Title if you need to correct it to name only the content types filtered out.

If you set your Contextual filter to allow multiple values (there are two places for that) you can construct the path with two or more content types to filter them out: my-content-types/page+article.

To test that your Contextual filter is working you can enter the argument for it in the Preview with contextual filters: field and hit the Update preview button if you don't have it set automatically. To view all the results without filtering simply delete the argument or enter all at the Preview or at the end of your path.


We have a client who runs a security scan that flags login forms that have autocomplete enabled, and have been using this solution for a few years now:

/**
 * Implements hook_form_alter().
 *
 * Remove autocomplete from all user forms.
 * Based on http://www.midwesternmac.com/blogs/jeff-geerling/disabling-autocomplete-forms
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'user_') === 0) {
    $form['#attributes']['autocomplete'] = 'off';
  }
}


Drupal 7, show drupal blocks only on specific pages with PHP code?

How the $username variable's value will be available there?
If you want to use current logged in user, write it like
global $user;
and check $user->name instead of $username.


How do I Install an earlier version of Drupal 8 with composer because install fails on server with PHP 5.6?

Drupal 8 does not support PHP version 5. It requires a minimum PHP version of 7.0. Please see here for Drupal install requirements

Drupal Installation Requirements - Drupal.org

So you will have to upgrade PHP on your machine. Also PHP 5.0 is no longer supported and is not secure. So you might want to upgrade PHP on your server any way.

PHP Supported Versions - php.net


Views: Display users with a gmap attachment

Try using getlocation module. In order to show gmap with views, you need google api key. Getlocation module comes up with blocks and views with api key already embeded in code.


How would I have got blog and news pages to list articles/blogposts, how do I edit?

In Drupal 7, go to /admin/structure/menu/manage/ to manage your menus. Select "Main Menu" as that will probably be your primary navigation.

Click +Add Link. For both Blog and News, set the appropriate name in the "Title" field.

For path, set the Blog path to "blog" or for News you can set it to "home" to retrieve articles promoted to the front page, or something like "news" if you have a specific page with a path set to that for those articles to be displayed on.


You can use select count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%m-%Y') as month from users group by MONTH(FROM_UNIXTIME(created));. This uses the created field of the users table.

Edit:

In your code this should look something like

$result = db_query("SELECT count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%m-%Y') AS month
                    FROM {users}
                    GROUP BY MONTH(FROM_UNIXTIME(created))");

This will return all new usercreations grouped by month. You could use other Date/Time Functions like DAY. But be carfull with the groups. The example above only works correct if you track the data of one year (because it does not group by year). Here is a more complex example:

$result = db_query("SELECT count(*), DATE_FORMAT(FROM_UNIXTIME(created),'%d-%m-%Y') AS month
                    FROM {users}
                    GROUP BY YEAR(FROM_UNIXTIME(created)),
                             MONTH(FROM_UNIXTIME(created)),
                             DAY(FROM_UNIXTIME(created))");

I'm not entirely sure if there is a better solution to this. I can't help with the Integration into the charting API as I never used it.


For the Drupal Garden's style setup, you should definitely look at Aegir.  It requires a bit of setting up, but there are loads of tutorials and screncasts - there are a couple of good ones here and here.

With regards to your menu question, that seems like a simple permissions question.  When you deploy your new sites, you'll obviously have to set up a user for the owner of said site.  If you ensure that user has a particular user role, you can set permissions at "/admin/people/permissions" for the core menu module.  Look under Menu around halfway down the page and check the box for Administer menus and menu items for your site owner's user role.


flowplayer with videojs module and video-js

As the project page says

If you are using latest videojs module i.e 7.x-2.3 with 3.x video.js version it comes with Flash fallback. Video.js library will handle the flash fallback option. You don't need to install swf tools or flowplayer API. You don't need to place flowplayer folder inside libraries folder.

If you would like to use flow player API you might need to use 7.x-1.x version of video.js module. As long as you follow installation instructions here you are good to go with 7.x-3.x version of module. Make sure you use right library of video.js version vs Module version as shown above and follow instructions in Readme file.


How to hide the 'Format Options' / 'Help Text' Guideliness from the bottom of comments textarea?

Check out the Better formats module. It allows you to hide the format options and tips link per user roles and fields.


For the second view , I think it's possible using agregation : you will have to select two times the field dates , the fist one will be displayed as year and second one month , then use group by the first date field. If it doesn't work then in the fields settings you will have to separate the date as one field for year , and one field for month , then you will have to group by the year field in the views.

Here is a great tutorial from nodeone.se of how to use agregation in drupal 7  :


How to manage / consume multiple Queue API queues in a module?

It's possible to achieve this using Ultimate Cron! module.

This module creates a separate entry for each Queue item.
Maybe it will help somebody.


URL Redirects and Configuration Management

Yes indeed. If you wish to carry the redirects around you should probably export
Or manually create the file if they are not too many.
I would recommend a csv file.
You can check this for reference How do I export the list of URL alias into an excel or csv?
Then I would write a simple drupal migrate process to re import them in any environment. If you use csv file it should be quite simple for the redirects.


Drupal jquery behaviors & views - Ajax multiple times / wrong arguments - triggerHandler('RefreshView')

For the sake of posterity & future visitors with this issue, here is how I eventually got it to work.

refreshView: function (context, settings) {
  // Unbind event to prevent multiple ajax refreshes.
  $('.view-id-packages').unbind();
  Drupal.attachBehaviors('ViewsAjaxView');

  // When map changes, update the grid of packages below the map.
  var visibleMarkers = this. leafletMap.getVisibleMarkers();

  // Get all the node IDs to pass into the views contextual filter.
  var nids = '';
  $.each(visibleMarkers, function (i, v) {
    nids += v.node.nid + '+';
  });
  nids = nids.slice(0, -1);

  // Update the Drupal ajax object to use our new set of node IDs.
  $.each(Drupal.settings.views.ajaxViews, function (key, value) {
    if (value.view_name === 'packages') {
      Drupal.settings.views.ajaxViews[key].view_args = nids;
    }
  });

  // Add the throbber on since it doesn't show automatically.
  var throbber = '

&nbsp;

';
  $('.views-submit-button').append(throbber);
  // Trigger the ajax.
  $('.view-id-packages').triggerHandler('RefreshView');
}

And then my view > advanced > contextual filter looks like:


How we can make weekly calendar block with ajax?

Use calendar module (requires views module). Calendar module comes with bunch of blocks (block views) available and you can set for them to use AJAX instead of refreshing page. With views you can do a lot of customization.


I discovered that the error only occurred when using the in-place panel editor. When adding the block in the panel page editor there were no errors.


The Asynchronous Prefetch Database Query Cache module should handle it. If you want the longer version see How to get rid of Deadlocks and Lock time out type issues?


Select the following fields to output:

1- title, body, path, (Global: Custom text) and any other fields you want. and make sure that (Global: Custom text) is ordered last, and all other fields are excluded from display.

2- in (Global: Custom text) settings, use the fields' tokens in the body. [title], [body], then choose "Output this field as link" and in the path just enter the [path] token. (See Replacement Patterns for more details)

Hope this works... Muhammad.


If you need a per product price modificator, your best solution is to have a field with this information, you can probably use a normal numeric field for this purpose.

You've got many examples on how to create a field using the API, for example, drupal commerce itself adds a price field every time a product type is generated by using hook_modules_enabled hook.

/**
 * Implements hook_modules_enabled().
 */
function commerce_product_modules_enabled($modules) {
  commerce_product_configure_product_fields($modules);
}

Then in this function

function commerce_product_configure_product_fields($modules = NULL) {
(...)
      // Loop through and configure the product types defined by the module.
      foreach ($product_types as $type => $product_type) {
        commerce_product_configure_product_type($type);
      }

Next

/**
 * Ensures a base price field is present on a product type bundle.
 */
function commerce_product_configure_product_type($type) {
  commerce_price_create_instance('commerce_price', 'commerce_product', $type, t('Price'), 0, 'calculated_sell_price');
}

And finally

function commerce_price_create_instance($field_name, $entity_type, $bundle, $label, $weight = 0, $calculation = FALSE, $display = array()) {
  // Look for or add the specified price field to the requested entity bundle.
  commerce_activate_field($field_name);
  field_cache_clear();

  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle);

  if (empty($field)) {
    $field = array(
      'field_name' => $field_name,
      'type' => 'commerce_price',
      'cardinality' => 1,
      'entity_types' => array($entity_type),
      'translatable' => FALSE,
      'locked' => TRUE,
    );
    $field = field_create_field($field);
  }

  if (empty($instance)) {
    $instance = array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,

      'label' => $label,
      'required' => TRUE,
      'settings' => array(),

      // Because this widget is locked, we need it to use the full price widget
      // since the currency option can't be adjusted at the moment.
      'widget' => array(
        'type' => 'commerce_price_full',
        'weight' => $weight,
        'settings' => array(
          'currency_code' => 'default',
        ),
      ),

      'display' => array(),
    );

    $entity_info = entity_get_info($entity_type);

    // Spoof the default view mode and node teaser so its display type is set.
    $entity_info['view modes'] += array(
      'default' => array(),
      'node_teaser' => array(),
    );

    foreach ($entity_info['view modes'] as $view_mode => $data) {
      $instance['display'][$view_mode] = $display + array(
        'label' => 'hidden',
        'type' => 'commerce_price_formatted_amount',
        'settings' => array(
          'calculation' => $calculation,
        ),
        'weight' => $weight,
      );
    }

    field_create_instance($instance);
  }
}

So you in summary can use hook_modules_enabled to react and loop the product types and create your field and instance. Another examples of this procedure can be found in commerce recurring, commerce discount, commerce coupon and more.


What is the best practice for showing a specific node within a specific page?

You could try creating a new block view, which selects a specific carousel node, and then choose where you want the block to appear.

Views Slideshow does something similar, where you can create a slideshow in a block from a number of existing images.


I fixed this by doing the following:

I appended a cache buster querystring parameter to the link to the page that needed to be kept out of cache (using the timestamp token + random number token)
Added the 'url.query_args' cache context to the required_cache_contexts in services.yml

It puts a bit more strain on the memory use of the cache than just keeping it out of cache altogether, but the \Drupal::service('page_cache_kill_switch')->trigger(); line did not do anything for me at all.

I think it makes sense for the querystring to be part of the default cache context anyway.


Change size of views exposed form search box

I think it would be better to change the form sooner than during themeing ... the best is to implement a form_alter hook, in this case

  function MODULENAME_form_views_exposed_form_alter(&$form, $form_state)

you can try to dpm($form) first, to see what exactly you should change, and probably also add a condition about module id.

if you install advanced_help, this info can be found on your site at help/views/alter-exposed-filter :)


Can I delete old hook_update_N functions?

Actually, there is a situation where you could need to keep the older update hooks: when you restored the database from an old backup and you need to update the database to the latest version of the installed modules.
If that is never your case, then—as long as you are sure all the sites have been updated to the same version of the module—you can remove the old update hooks. Keep in mind that, if you delete an update hook you needed for a site, the alternative is uninstalling the module, and then install the latest version, but this will cause data loss.

Updates hooks are only invoked when updating an installed module, and they are not invoked contemporarly to hook_schema() and hook_install(). When a module is installed, hook_update_N() is not invoked; hook_schema() and hook_install() are only invoked when a module is installed. That is the reason why old hook_update_X() could be removed, once a module is updated to version X or older.

Usually, the update hooks are removed when passing from a Drupal version of the module a more recent one (e.g. from the Drupal 6 module to the Drupal 7 module). Since the installation file is loaded just on updating and installing (and other limited situations), removing the update hooks doesn't give any significant gain.


How to render a text with linebreak saved from a textarea form?

I tried putting the value in a '#markup' => $text render array, but it
  was the same. How can I render this new line?

Yes, you need to put the text in a render element, but for a formatted text field the correct element is processed_text:

'text' => [
  '#type' => 'processed_text',
  '#text' => $node->field_text->value,
  '#format' => $node->field_text->format,
],


Because you are very inexperienced with Drupal, you don't know that your question is actually a set of several questions.

If you never have used Drupal before, you must understand a few basic things about Drupal, then learn about how to install it, and how to administrate (and customize) your Drupal to add the features that you want.

Also, Drupal has installation profiles; there are a variety of "pre-configured" versions of Drupal you can download and use for common needs. I am not sure any profile exists that is specialized for your needs, but you can search and select the most suitable and customize according your needs.

Update:
If you have installed a Drupal version, and have reviewed the basics of Drupal administration, you can find and test several options for modules to (integrate with Facebook](http://drupal.org/search/apachesolr_multisitesearch/facebook%20Integration?filters=ss_meta_type%3Amodule). For letting people share their content, you can review that with Content Types and CCK fields (CCK is needed for Drupal 6) you can create separated types of content having custom fields according your needs.

here http://drupal.org/documentation/modules/field-ui and here http://drupal.org/node/774728 are documentation about how to create a Content Type, and here is screenshot about where you can add custom fields for Content Types:

Remember review Drupal profiles, can be a suitable answer that you can customize with content types and Facebook integration.


How do I post a node that has its created field set to the past in a test class?

When you access node create form using admin role created value is exposed using Authored Information...

So, You can able to set created date by creating user with administrator role for testing...

Please see implementation below..

<?php

/**
 * Tests the functionality of the Simpletest example content type.
 */
class SimpletestExampleTestCase extends DrupalWebTestCase {
  protected $privileged_user;

  public static function getInfo() {
    // Note: getInfo() strings are not translated with t().
    return array(
        'name' => 'Simpletest Example',
        'description' => 'Ensure that the simpletest_example content type provided functions properly.',
        'group' => 'Examples',
    );
  }
  public function setUp() {
    // Enable any modules required for the test. This should be an array of
    // module names.
    parent::setUp(array('simpletest_example'));
    // Create and log in our privileged user.
    $user = $this->drupalCreateAdminUser();
    $this->drupalLogin($user);
  }

  public function drupalCreateAdminUser(array $permissions = array()) {
    $roles = user_roles();
    $index = array_search('administrator', $roles);
    $user = $this->drupalCreateUser($permissions);
    $user->roles[$index] = 'administrator';
    return user_save($user);
  }

  /**
   * Tests creation of a Simpletest example node.
   */
  public function testSimpleTestExampleCreate() {
    // Create node to edit.
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit["body[und][0][value]"] = $this->randomName(16);
    $edit["date"] = "2012-04-19 22:54:38 +0530";
    $this->drupalPost('node/add/article', $edit, t('Save'));
    $this->assertText(t('Simpletest Example Node Type @title has been created.', array('@title' => $edit['title'])));
  }
}

Here is the output


Form loaded with ajax call not having autocomplete enabled

If you want Drupal's autocomplete, you need to modify form using Form API '#ajax'. If you are doing it with your custom scripts, Form API will not know that field really belongs to your form, and will not handle field's calls.1

The way you should do it is:

In your form building function, create element with '#ajax' property, that will be responsible for loading your form part, or add it to existing element.
Also in your form building function, add an if that will check triggering element ($form_state['triggering_element']), and if that was your button, add entry in $form_state that new section should be visible.
If there is an entry mentioned in 2., output form part you want to be loaded with AJAX.
Use AJAX callback function only to select and return proper part of the form.

1 Simplified explanation, of course.


Vocabulary set by another hierarchy and combinations

It's a required part of the entity. The name field for a Drupal 7 taxonomy term is defined in the taxonomy's module:

hook_entity_info() invocation to designate name as the label (a human readable field that's required for displaying entity).
hook_field_extra_fields() invocation to define the name field within the taxonomy term for the admin UI.

The Drupal API does expose hook_entity_info_alter() & hook_field_extra_fields_alter(). You can use these function to redefine how you'd like specify your taxonomy term label field.


Why am I getting a JSON dump when saving a node?

We were having this same issue on our company website. We have Administration Views installed, and use jQuery 1.8 as default version and 1.5 for admin pages.

As SomethingOn mentioned above, we were consistently seeing the JSON dump after filtering on the Find Content view, editing a node then saving. The URL paths all had 'views/ajax' in the query string of the node edit URL; e.g.,

/node/XXXX/edit?destination=admin/content%3Fq%3Dviews/ajax%26title%3D%26type%3DAll%26author%3D%26status%3D0%26vid%3DAll

What I ended up doing was turning AJAX off (under Advanced > Other > Use AJAX) for the Find Content view (Administration:Nodes). This removed 'views/ajax' from the node edit paths and resolved the issue for us.


Views 3: filter nodes such that an entity reference on the node corresponds to the current user

The steps to create a view that lists all nodes of type scholarship that are referenced to the current logged in user:

Add new view, showing content of type scholarship
Add a relationship: Entity Reference: Referenced Entity
Add new filter: User: Current
Select Yes for the option Is the logged in user
Save.


menu-mini panels: removing anchor tag from menu item

You can use some jquery here, by capturing click event of this menu item, and returning false.

$("<selector>").click(function(){
   return false;
});

Or try this

$("<selector>").click(function(e){
   e.preventDefault();
});


Basic kernel test fails with Type of Drupal\KernelTests\Core\Entity\EntityKernelTestBase::$modules must be array

From KernelTestBase:
 /**
  * Modules to enable.
  *
  * The test runner will merge the $modules lists from this class, the class
  * it extends, and so on up the class hierarchy. It is not necessary to
  * include modules in your list that a parent class has already declared.
  *
  * @see \Drupal\Tests\KernelTestBase::enableModules()
  * @see \Drupal\Tests\KernelTestBase::bootKernel()
  *
  * @var array
  */
 protected static $modules = [];

You'll need to match this declaration in your own code (though you can add to the array).


Programmatically create a paragraph entity reference field

The following code did the trick for me when adding the field to custom entity. This provides a reference to the paragraph and the revision. Just to note out that when the paragraph is edited, the reference field will still refer to the old revision. The field type is entity_reference_revisions and my paragraph type

$fields['social_media_id'] = BaseFieldDefinition::create('entity_reference_revisions')
  ->setLabel(t('Skill'))
  ->setDescription(t('The ID of the skill'))
  ->setRevisionable(TRUE)
  ->setSetting('handler', 'default:paragraph')
  ->setSetting('handler_settings', ['target_bundles' => ['social_media' => 'social_media']])
  ->setSetting('handler_settings', ['negate' => 0])
  ->setTranslatable(TRUE)
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE);


Try this code

drupal_add_js(
  url(
    libraries_get_path('mylibrary') . '/MyLibrary.js',
    array(
      'query' => array(
        'config' => MY_CONFIG_PARAM
      )
    )
  )
);


how to know this query related to which block

There is some hint on last line. the block in showing Article(node type) which are published to site and created in arabic language.

So, remind that where u seen this kind of content block in the site.


hook_views_data Join by multiple value field

I believe this https://www.drupal.org/node/810932#comment-3020000 comment describes exactly what you need which is the extra field in a join description:

$data['node']['table']['join'] = array(
  // this explains how the 'node' table (named in the line above)
  // links toward the node_revision table.
  'node_revision' => array(
    'left_field' => 'nid',
    'field' => 'nid',
    'extra' => array(array('field' => 'fieldname', 'value' => 'value', 'operator' => '='))
 ),

);


How do I print a specific meta tag attribute value in html.tpl.php?

create a preprocess_html function in template.php
function porto_sub_preprocess_html(&$vars){
  if (drupal_is_front_page()) {
    if (isset($vars['page']) && isset($vars['page']['content']) && isset($vars['page']['content']['metatags'])) {
      $meta_tags = $vars['page']['content']['metatags'];
      if (isset($meta_tags['global:frontpage']) && isset($meta_tags['global:frontpage']['description'])) {
        $meta_desc_list = $meta_tags['global:frontpage']['description'];
        if (isset($meta_desc_list['#attached']) && isset($meta_desc_list['#attached']['drupal_add_html_head'])) {
          if (isset($meta_desc_list['#attached']['drupal_add_html_head'][0]) && isset($meta_desc_list['#attached']['drupal_add_html_head'][0][0])) {
            if ($meta_desc_list['#attached']['drupal_add_html_head'][0][0]['#value']) {
              $vars['front_page_meta_desc'] = $meta_desc_list['#attached']['drupal_add_html_head'][0][0]['#value'];
            }
          }
        }
      }
    }
  }
  drupal_add_http_header('Cache-Tag','mktg',true);

2. This defined meta tag is accessible from html.tpl.php
 if (!isset($front_page_meta_desc)) {
       $front_page_meta_desc = '';
     }

In the schema JSONLD, you need to call the variable.
"description": "' . $front_page_meta_desc . '",


Content sorted by machine name not title

Just had to apply patch of "Content types are ordered by machine name on node/add"

https://www.drupal.org/project/drupal/issues/2693485

It resolved the issue


how to make a row in a view a different style depending on the content type

In the left top, behind format you can click the settings button. This shows you the style options dialog, where you can define a row class.

This class fields accepts views tokens (though does not provide the overview of them). So you should add a field for the content type, hide it from display if you please. Discover the token name of this field by checking the rewrite section and finally place this token in the row class field.

In my example I use the value of a php field to add row classes:


How to Disable "Upload" in IMCE to only keep "File browser"?

Go to:

  Administration » Configuration » Media » IMCE

Select your profile.
Under Directories there are checkboxes: Browse,Upload,Thumbnails,Delete,Resize.

Uncheck: Upload


Saving the content from a Textarea dont works

Solved!

I just rebuild the save-stuff:

<?php
function text_edit_form_submit($form, &$form_state) {
  $form_state['conf']['form_text'] = $form_state['values']['form_text']['value'];
}
?>


How can I add previous and next controls to the views slide show?

I done it through css code, just follow this steps

#views_slideshow_singleframe_prev_gallery-block_1, #views_slideshow_singleframe_next_gallery-block_1 {   width:71px;   height:0px;   padding-top:71px;   position:absolute;   top:100px;   overflow:hidden; }

#views_slideshow_singleframe_prev_gallery-block_1 {   background:url('images/left-button-on.png');   left:0px; }

#views_slideshow_singleframe_next_gallery-block_1 {   background:url('images/right-button-on.png');   right:0px; }

 #views_slideshow_singleframe_playpause_gallery-block_1 {   display:none; }

And also take a look at https://drupal.org/node/691984


Drupal automatically create hardcoded links and do such links impact performance?

If by "a lot of custom code" he meant he created a custom module, then there is nothing that explains why the links were hard-coded. Keep in mind that Drupal has url() and l() to create URLs and links, which removes the need of using hard-coded links when they are links to the same Drupal site. For example, the following code (used by Drupal core) would work correctly even when the code would be moved from a site to another. As a matter of fact, it generates links that work for every site powered by Drupal.

  $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
  $count = count($actions_in_db);
  $orphans = implode(', ', $orphaned);
  watchdog('actions', '@count orphaned actions (%orphans) exist in the actions table. !link', array('@count' => $count, '%orphans' => $orphans, '!link' => $link), WATCHDOG_INFO);

To notice that, Drupal normally (as in the above case) generates links that are relative; that is why they work independently from the domain. l() works in many cases, even in the case Drupal is installed in a sub-directory of the server document directory, or when clean URLs are disabled. On my test site, the above code ($link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');) would create the following link.

Remove orphaned actions

If I disable the clean URLs, the same code would get me the following link.

Remove orphaned actions

The same code would produce the following links, when Drupal is not installed in a sub-directory.

Remove orphaned actions

Remove orphaned actions

The only case I can think where absolute URLs are necessary is when the URL is pointing externally to the Drupal site, for example to a sub-domain (to blog.example.com from exampl.com). That is the only absolute URL I have in my Drupal site, since I have added the link from admin/structure/menu/manage/menu-secondary-menu/add.

I could have used a custom module to add the link, and in that case I would have avoided to use an hard-coded link. For example, I could have used the following code.

global $base_url;
$blog_url = preg_replace('@(https?://)(.*)@', '$1blog.$2', $base_url);

In the case of my local test site, the above code would set $blog_url to 'http://blog.tero.local/dr71', while in the case of my Drupal site, it would set the same variable to 'http://blog.avpnet.org'.

A quicker method would be adding to the settings.php file a function that returns the link.

function _get_absolute_url($type) {
  global $base_url;

  switch ($type) {
    case 'blog':
    $url = preg_replace('@(https?://)(.*)@', '$1blog.$2', $base_url);
    break;
  }

  return $url;
}

In this case, for my test site I could use the following code, since I don't have a blog sub-domain.

function _get_absolute_url($type) {
  global $base_url;

  return $base_url;
}

In that way, I don't hard-code 100 links, but I use a single function that changes basing on the settings.php used from the site. In the case I need a link to the blog site, I would use code similar to the following one.

$blog_first  = _get_absolute_url('blog') . 'node/1';
$blog_second = _get_absolute_url('blog') . 'node/2';
$blog_third  = _get_absolute_url('blog') . 'node/3';

The code is assuming that, in the case of link to a Drupal site, that Drupal site is using clean URLs. If you administer that other site/sub-domain, it would not be difficult to change the code to get the correct URL.


Single site with multiple user interfaces based on path and role

Role Theme Switcher does what you're asking for roles.  For access to pages you could write your own custom module that implements hook_node_access or you could use Views permissions (which I've found to be quite easy and works well) or you could use another module that manages permissions on a per-page basis like Content Access or Nodeaccess.

Lots of options for what you want.  I personally recommend trying to combine Role Theme Switcher with Views permissions.  Otherwise I would go for making a custom module with hook_node_access.  I don't recommend Content Access or Nodeaccess, they've never worked exactly right for what my needs are, but they are there for reference.

EDIT: You may also find Rules to be helpful re-directing users of certain roles to certain pages based on their role when they login.

EDIT 2: As I mentioned in the comment below, logintoboggan is another module that will allow re-directs upon user login.


What is the best way to retrieve the current menu object, regardless of it's type?

As you can see in that function, it does nothing more than:

$router_item = menu_get_item($path);
return $router_item['map'][$position];

However, I'm not sure how that will help you, for pretty much all objects, you need to know what it is to work with it as there are just some attributes.


Drupal 7: Displaying external SQL-table as paginated list

the squiggly brackets are used for escaping table names in drupal. For cases where you have multiple sites in one database.

I'm guessing that you have a db prefix set up for all of your Drupal tables to be drupal_

You can set this on a db connection before $result = $query->execute(); using the setprefix method

Something like

 $query->setprefix(array(
     'default'   => 'drupal_',
     'perf_users'     => ''));

untested code

may do it. However you are more likely to want to change your settings.php file and set table prefixs in there


How to create custom 403 page for a particular content type?

Try looking at the Custom 403 module, or the Teaser 403 module .

  Custom 403

  This module provides helpful messages to users when they encounter a 403 (Access Denied) page. Depending on different role(s) permissions set on the specific node or content type, the administrator can specify messages accordingly. The user who encounters the 403 will obtain more specific information on how to obtain the role(s) required to access the node.

  Teaser 403

  This module is designed to expose teaser content for sites which normally require users to login to view nodes.