It seems you need to have pages ordered ascending, but inside a page descending. To do that, you need to query database in ascending order. Then reverse order of one page in template that renders it.

<?php

/**
 * @file  views-view-unformatted--yourviewname.tpl.php
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php /* foreach ($rows as $id => $row): // That's how it looks by default */ ?>
<?php foreach (array_reverse($rows, TRUE) as $id => $row): /* That's what you need */ ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>
    <?php print $row; ?>

<?php endforeach; ?>


How to know from which country people are accessing my website?

You do not need a module for that. Simply make use of any web analytics system such as
 Google analytics, Piwik analytics and such like.


How to render the 'actions' section of a form in twig template?

Hat tip to Clive who already answered the question as a comment:

{{ form.actions}}

To render the rest of the form, you can do something like {{ form | without('actions') }}

So you whole code will look something like this:

In my_module.module:

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  $result = [
    'custom_form' => [
      'render element' => 'form',
      'template' => 'custom-form',
    ],
  ];

  return $result;
}

And in custom-form.html.twig:

Form

    {{ form | without('actions') }}

Action

    {{ form.actions }}

For more reading:

Similar Q&A:

https://stackoverflow.com/questions/48997506/how-to-render-specific-form-elements-drupal-8
How to pass a custom Form to a Twig template

Drupal.org documentation on Twig filters in Drupal: https://www.drupal.org/docs/8/theming/twig/filters-modifying-variables-in-twig-templates

Hope that helps!


How do I render content generated by a controller in a custom block?

@4k4 is correct in their answer that it is preferable to refactor the shared code into a separate class (probably a service).

However, if that is not an option (because you are building on core or contributed code that you cannot change) it is still possible to re-use the output of a controller that uses dependency injection (DI). To do so, inject the class_resolver service into your block and use it to get a controller object. Your block code would look something like this:

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a custom block containing the output of a controller.
 *
 * @Block(
 *  id = "controller_block",
 *  admin_label = @Translation("Controller block"),
 * )
 */
class ControllerBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Class Resolver service.
   *
   * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
   */
  protected $classResolver;

  /**
   * Constructs a new ControllerBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
   *   The class resolver service.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    ClassResolverInterface $class_resolver
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->classResolver = $class_resolver;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('class_resolver')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    // Assuming that \Drupal\my_module\Controller\MyController::build is a
    // public function that returns the controller output.
    $controller = $this->classResolver->getInstanceFromDefinition('\Drupal\my_module\Controller\MyController');
    return $controller->build();
  }

}


Is there any online tutorial explains how can I map the requested URL to actions' code in drupal 7?

You are looking for hook_menu(), you will need to implement this hook on your custom module to register path in drupal.

  Define menu items and page callbacks.

  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). A path and its associated information is commonly
  called a "menu router item". This hook is rarely called (for example,
  when modules are enabled), and its results are cached in the database.

Since you are beginner, First I would suggest you to learn about hook system for drupal.

Checkout this answer for detailed use of hook_menu.


Drupal 7 Single Sign On possibilities with the Domain Access Module

See: Comparison of Single Sign On (SSO) Modules

Bakery supports SSO for sites with the same domain (site1.example.com, site2.example.com). Have not tried CAS as you noted above it is an option. You could also use an oauth server to authenticate across domains.


Is it possible to set multiple permission in hook_permission()?

Of course:

function MYMODULE_permission() {
  return array(
    'name of permission' => array(
      'title' => t('Access Something'),
      'description' => t('Access Something to do something'),
    ),
    'name of another permission' => array(
      'title' => t('Access Something Else'),
      'description' => t('Access Something Else to do something'),
    ),
  );
}


Why do many functions now require more code than the equivalent functions of the previous version?

Is this actually the case or am I misinterpreting whats happening.

Yep, a lot of D8 stuff is more verbose than that of its predecessor. A huge chunk of the codebase has moved to OO based on PSR-0, so you're always going to be writing more code, more files, creating more folders to put those files in, etc.

  If this is the case then what is the advantage?

You can't directly apply an 'advantage' or 'disadvantage' to the concept of "D8 will use more code" (if that's indeed even true when you average it all out); it's simply an inevitability - the D8 page request has completely changed with the introduction of Symfony, so what was possible in a few lines in D7 just isn't possible with the same code now. The overall advantage is that Drupal gets all the power of Symfony driving it, and Symfony's framework/request lifecycle is generally considered to be stable and to use good practice. Plus, introducing a strict DI methodology to any kind of project is a big win in my opinion.

  Would it be possible / desirable to use lots of wrapper functions to reduce the amount of code to achieve simple tasks?

Possible? Of course. Desirable? Depends on your opinion, and what you're creating a wrapper for. If it's something you do 10 times a day, and you can shorten 10 lines to 1 or 2 lines, then you'd be mad not to do it. Obviously that attitude transcends Drupal/PHP and should apply to any language/technology.

  This is only a couple of examples but it seems that to achieve anything is D8 is going to take far more code.

The anything there isn't true - some things will be more verbose, some things less, it depends on exactly what you're looking to do.


How to overridden command via hook_drush_command_alter?

The command_alter hook is not super friendly / obvious when it comes to complete command replacement, as this hook was only designed to make minor alterations to the command.  It is all the same possible to replace one command with another, but the process is a bit obtuse, as you need to reset some variables that Drush has already initialized.

This should do the trick:

/**
 * Implements hook_drush_command_alter
 */
function policy_drush_command_alter(&$command) {
  if (($command['command'] == 'features-revert-all') && (drush_drupal_major_version() >= 8)) {
    $command['command'] = 'custom-features-revert-all';
    $command['command-hook'] = 'custom-features-revert-all';
    $command['primary function'] = FALSE;
    $command['arguments'] = array(); // Adjust this only as needed
    drush_set_command($command);
  }
}

Note that this example removes any arguments the user may have passed to the command; I included this just to demonstrate how to alter the arguments, in case this is needed. Remove the assignment to $command['arguments'] if you'd like the original args passed through.


page--front.tpl.php not showing up in Zen subtheme

Found out the problem was caused by the Context Layout module. Apparently this module overrides Drupal's normal template file search order. The solution was to either to disable the Context Layout module or include the templates (like page--front.tpl.php) in the layouts definition in the themename.info file. I went with the latter solution.

Here is an example of what should appear in the .info file:

; Layout: Landing
layouts[landing][name] = "Landing Page"
layouts[landing][description] = "A layout for landing pages."
layouts[landing][template] = "templates/page--front"
layouts[landing][regions][] = "search"
layouts[landing][regions][] = "highlighted"
layouts[landing][regions][] = "mega_menu"
layouts[landing][regions][] = "slider"
layouts[landing][regions][] = "sidebar_first"
layouts[landing][regions][] = "sidebar_second"
layouts[landing][regions][] = "footer"
layouts[landing][regions][] = "bottom"

Notice the layouts[landing][template] line where we define where and what template file to use. This is key to getting this to work with Context Layouts.


Attaching a view to a content type that takes the content type's taxonomy terms as arguments

You can pass to the template, a variable which contains the second view value

function mymodule_entity_view($entity, $type, $view_mode, $langcode) {

  list($id, $rev, $bundle) = entity_extract_ids($type, $entity);
  switch ($bundle){
    case 'customtype':
      if( $view_mode == 'teaser' ){
        $entity->test['test'] = array(
          '#markup' => views_embed_view( 'view_2', 'default', $entity->field_custom['und'][0]['value'] ),
        );
      }
    break;
  }
}

Then, in your theme, a node--customtype.tpl.php, you can render the variable:

print render($test);


Drupal Commons add automation using Workflow modules to solve the problem of Wiki/Article Publishing for End users

your subject is quite different than the question you ask. If its just a permission issue then you need to check under roles and permission. Sometime we cannot give all rights required to for mod or data entry access, so best is to copy administrator role and remove all critical permission and assign only what you want to give (to specific piece of content).

Btw, workbench is only used for permissions and not for the work flow. Its a like creating a working space for certain set of people (work bench) with adequate permissions, that's it.

If your question is regarding your subject of how to create workflow, then look at maestro module https://drupal.org/project/maestro to create GUI based logical workflow with great level of approvals, check point and notification options.

I researched Maestro week back for my friend and worked for a short while.


There is data for this field in the database. The field settings can no longer be changed

I haven't tried to lower the settings in a situation where no extra data would prevent it, but it seems it is possible: Changing cardinality lower than highest existing delta causes data loss upon save.

But assuming it can be done, you can also create Views to list content with more than one term in a multi-valued field.

Fields with multiple values track the values with Delta starting from 0. Field with one value has Delta 0. Field with 2 values, has Delta of 0 for the first value, and Delta of 1 for the second value etc.

Field

Value 1 (Delta: 0)
Value 2 (Delta: 1)
Value 3 (Delta: 2)
…

Delta is available in Views. This means you can Filter content with regard to it, which is what you want.

Create Views of type Content with Filters and Fields appropriate for your initial situation, show Title and the Taxonomy field in question so you can check the results (you probably already have this covered)
Add a Filter of your field Delta. It will be called something like MyTags (field_mytags:delta). If you search for your field name it will list both your field and the Delta, choose the Delta option.
Set the Operator of the Delta Filter to Is equal to and enter 1

This will list all the nodes (provided your other filters are set appropriately) where the second position in the Taxonomy field isn't empty. Meaning there are at least 2 terms recorded in that field. The nodes will only be listed once.

If you set the Delta Filter Operator to Is greater than 0, as you may be tempted, it will also list the nodes that have more than one term in that field, but it will list them as many times as there are terms on that node minus 1. So if a node has 3 tags, it will be listed twice, because it will list one result for each Delta above 0.

With this result, you can go on to use Views Bulk operations to edit the listed "offenders", by coding an operation that deletes all but the first value from that field. Or even manually edit each node if coding is not an option.


What are the differences between EntityFieldQuery and field_get_items()

They are intended for different purposes.

EntityFieldQuery is an object to query entities using conditions that includes the value of their fields (for example: retrieve all entities of type node that have 'foo' as value in the field_somestring field).

  Retrieves entities matching a given set of conditions.

  This class allows finding entities based on entity properties (for
  example, node->changed), field values, and generic entity meta data
  (bundle, entity type, entity id, and revision ID). It is not possible
  to query across multiple entity types. For example, there is no
  facility to find published nodes written by users created in the last
  hour, as this would require querying both node->status and
  user->created.

field_get_items(), on the other side, is a function to retrieve field data of a single entity:

  Returns the field items in the language they currently would be
  displayed.

So, I guess you should use EntityFieldQuery. Keep in mind the advice I copiyed above: you can only query properties (status, creation date, etc),metadata and field values, but you can't join with other data (any other specific table or query two entity types). If you need that use db_select.


Why does my rule have no effect on a VBO list of unpublished nodes but does work for published nodes?

Anything about Rules that uses the Rules Scheduler, runs for sure with "Anonymous" authorizations. There are cases (Rules Actions) for which that auth is insufficient of course.

So a possible explanation for the cause of your issue, is that your unpublished nodes are not included in your VBO views result. To verify if this is indeed the reason that causes your issue, just check the views results you get by looking at the Views results without being logged in (so as Anonymous user). If those unpublished nodes are included anyway, verify if Anonymous users are authorised to delete those nodes.


a quick google search: http://lmgtfy.com/?q=drupal+redis+sessions

and the 2nd result talks about redis session handling:
https://www.drupal.org/node/2250195

from that issue thread i recommend looking Session Proxy. This allows you to override the default session handler by Drupal -- which is explained in the above issue:

  This is because Drupal will override your session handler and use its
  own, it goes straight to the database. I'd recomend that you try using
  this module: https://drupal.org/project/session_proxy

Session Proxy provides the following, I believe your attempting #2:

  ships three different session managing implementations:

  Database session handling: core default, ported to the object oriented
  API. It comes with an additional SQL query done more than core
  session.inc default implementation due to the API strong
  encapsulation.
  Native PHP session handling: by selecting this session
  management mode, you explicitely remove any core session management,
  and let PHP manage it. This can be useful if you intend to use
  low-level PHP extensions, such as Memcache or PhpRedis to handle
  session in PHP low-level layer instead of core. This allow to use any
  PHP native session storage to work gracefully: some of them are high
  performance.
  Cache based storage engine: Using the same session
  handling than core, but deporting raw session storage into a cache
  backend instance. You can use any already-functionning cache backend
  to store sessions. Sessions will use their own bin, and won't be
  cleared at cache clear all time.

Again from the linked issue after installing session proxy you likely need to configure your php.ini to something like:

session.save_handler = redis
session.save_path = "tcp://localhost:6379"


There was an error in the generated markup. A missing closing div was messing everything. Now everything work as expected. Thanks.


You can keep it simple and just add the following to your css

.field_b:before{
  content:"-";
}

It will only show when there is a value for the b field.


Can a sidebar span two zones in omega 3 theme?

No, with the way the HTML is built, it goes

zone-wrapper div (if used)

zone dov

region div

In your case, I would leave the Header zone empty (make sure the checkbox for forced rendering is off), and then move all of your regions to the Content zone.  In the grand scheme of things, there is nothing special about the Header zone.  I am looking at one of my sites now, and I left Header empty.

With the default templates, the Content zone also contains the Breadcrumb and Messages, so you may need to tweak this a bit to output the regions specifically to get these in the proper place.


Yes, it's just up to you to add the fields or roles to your user accounts and then write product pricing rules to adjust prices through a calculation (10% off for role X) or price swapping from whatever price fields you've added to the product type (base price for normal customers, price 2 for role X, price 3 for role Y). This is just pretty standard Drupal stuff combined with Rules.


Include a third party library using namespaces, dependencies

It is indeed possible with xautoload.

Here is some explanation what initially went wrong:
https://gist.github.com/4018045

As a general guide:

function hook_libraries_info() {
  return array(
    'Taleo' => array(
      'name' => 'Taleo PHP Library',
      'xautoload' => function($api) {
        // $api already knows the library path.
        // 'src' is relative to that.
        $api->namespaceRoot('Taleo', 'src');
      },
    ),
  );
}

The $api object is explained here:
http://drupalcode.org/project/xautoload.git/blob/refs/heads/7.x-2.x:/lib/InjectedAPI/hookXautoload.php


Customizing tableheader.js Sticky table Header

You can override tableheader.js using hook_js_alter(&js) {}, just replace path of file, like in example (details here).

Also you can override Drupal.settings.tableHeaderOffset value.
Thus, in template.php place something like this:

drupal_add_js('themeTableHeaderOffset() { return 200; }', 'inline');
drupal_add_js(array('tableHeaderOffset' => 'themeTableHeaderOffset'), 'setting');


Check this issue https://www.drupal.org/project/drupal/issues/3150614
You could set next parameters in you services.yml
parameters:
  session.storage.options:
    cookie_samesite: 'NONE'


Remove $submitted from your template and use below code

$timestamp = $node->created;
print format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL);


This is not answer to your question - but a tip on the way...

There is a good possibility to use Rules + some rules contrib module to do this, maybe in a better way because rules is also able to send node-fields-values trough Tokens id, and also capable to act on site-current-user:language from the users own default language and send mail in preferred user language. Rules can be triggered on different actions at the site.
One of my Rules setting sending mail, where all fields-name are translated together with the fields value, based on user-default-language settings.


similar question is here.

Dynamic select list in the form (dependent dropdown)

you can get your solution from here.


How can I create a custom form settings to my custom field formatter?

Whenever you need to figure out how something works, look at examples that already do what you want. In your case, that's the ImageFormatter plugin.

Specifically, you are looking for the methods defaultSettings(), settingsForm() and settingsSummary(). Implement them, define the form for you settings, specificy default settings and for improved user experience, implement the summary method to give users a short summary of the current settings.

That's all, in viewElements(); you can then access your settings with getSetting().


As i can see from the menu token that the module has a pre-released version for drupal 8 as development release, so maybe you could try it out or at least search in its code to find a way to accomplish your needs.

I have recently built a drupal 7 website and i have used the menu token to create a hover over drop down usermenu with username and profile picture.

See image below (i drawed in black on top of it because the site in not yet online)

If you like, i can right back small tutorial on how i achieved that !


Creating a bootstrap sub-theme with the SASS starter kit

Try using Radix Theme. Check how the compiler gulp is setup and try to replicate it to bootstrap sass.


How to hide node title for specific content type using template file

Maybe you render article as full page then  $title rendered in page.tpl.php

you just need override your content type page template, I mean duplicate page.tpl.php ( if you use bootsrap sub theme go to  boostrap theme boostrap\template\system\page.tpl.php`  file to your subtheme template forlder and rename it to page--article.tpl.php and remove title form it.

I mean remove these lines from it

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

<?php print $title; ?>

  <?php endif; ?>

dont forget clear the cache


Conditionals with Combining Fields in Views

Instated of

 [field_products} [field_downloadable_products] [field_product]

Try

[field_products] [field_downloadable_products] [field_product]


How can i add a block below the Main Menu?

The main menu that you can see in the theme is not in a block.  It's printed at a certain spot within your page.tpl.php page in the bartik theme.  Check it out (make a copy first) and mess about to see the results.
If you want to add a new block to a region that doesn't already have a block check out this post http://drupal.org/node/1088718 as it details how to do so.
Your other question had to do with why the menu renders vertically instead of horizontally like the main menu, it's all due to the css styling.  Chances are that the menu is in an unordered list

 and that the list items (menu links) have been set to display:inline or float:left.
I hope I was of some help


Check if available values of a list-field is already used by other node of content type

you need to build a custom module in which you implement hook_form_FORM_ID_alter. since we're dealing with node create/edit forms, try yourmodule_form_yourcontenttype_node_form_alter().

(you could go for hook_form_alter(), but that would yield less performance, especially since you have a query to run.)

your implementation should include a query for that specific field, probably the table field_data_field_yourfield. narrow it by bundle and if it returns any entity_id, that's the one you're filtering out of your dropdown.

here's a few links to help you sort things out:

function hook_form_FORM_ID_alter():
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7.x
function db_select(): https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7.x
also look up "D7 Form API reference" (I can't post more than two links atm, sorry)

please write back if it works. good luck!

cheers,
Luco


Can't send managed file as mail attachment

file_load return file object:

  Loads a single file object from the database.

But $message['params']['attachments'][] should be an array.
So just change $file = file_load($fid); to $file = (array)file_load($fid); in your submit function my_form_submit will be like:

function my_form_submit($form, &$form_state) {
  $fid = $form_state['values']['document'];
  //file object as an array.
  $file = (array)file_load($fid);
  $params = array(
    'attachment' => $file,
  );
  global $language;
    drupal_mail('my_module', 'key_1', 'my_own_mail@gmail.com', $language, $params);

}

Update:

to send attachement you need just the filePath try with:

$params = array(
    'attachments' => array(
      0 => array(
        'filepath' => $file->uri,
      ),
    ),
  );


How to trigger a Rule when content is viewed with Panels activated?

You should use Rules Bonus Pack which allows to create a new event when a panel variation is loaded.

Detailed instructions:

Download Rules Bonus Pack and enable "Rules Bonus: Miscellaneous" sub module.
From the panel settings page you will see a new "Reactions" tab. On this tab you will select the new option "Create a Rules event for this variant".
Now open the rule and add a new event. You will find a new section "Rules Bonus: Miscellaneous" with the selected panel variation. Use this event instead the "Content is viewed" one.

It should work as you expect.

Alternative solution

An alternative solution is to write a custom module. You should take a look to the Rules Bonus Pack source code. You can find some inspiration to solve the problem.

Instead using hook_node_view() you can implement hook_ctools_render_alter().

First you should check the handler (node_view) and after load the node data from the ctools/panels context.

Example:

function yourcustommodule_ctools_render_alter(&$info, &$page, &$context){
  // Verify if the page/node is the one you want to interact with
  // and set the field value as you wish.

  // First check if the handler is node_view:
  if($context['handler']->task == "node_view"){

    // Then verify the node content from the context sub array
    // The $context variable contains the node data but you
    // have to dig in.
    $node = $context['contexts'][key($context['contexts'])]->data;

    // [... your code ...]

}

Happy coding :-)


VBO action 'Modify OG user roles' does not show custom OG roles on the 'Add roles' list

It turns out that new roles are not visible to already created groups. When I create a new group I can see the added roles. However there should be a way to make existing groups 'see' newly added roles...


Does using modules Metatags and Metatags Quick together cause SEO problems?

You have to be careful so that the output of each module won't overlap. For instance, the same meta should not be present twice and even worse with even slightly different values. I am not aware of the exact SEO penalty depending on the engine, but it is common sense.

You can examine the output of the modules for the <head> tag with the browser's inspector, or Firebug.


Drupal Coding - Menus - hook_menu is not generating menus

The place to start debugging is in _menu_navigation_links_rebuild() which builds up the menu links...it gets passed the menu router items built up from menu_router_build() (which is where hook_menu() is called from). A bit of temporary debug code in that first function would be the best way to go I think.

To address your other question, I've just added a menu item to a module in exactly the way you've done and it's come up in the UI as expected. It sounds like you have something pretty unusual happening with your menus!


Define available default colors for Color Field programatically

Finally to achieve I move to implement in my custom module the hook hook_field_info_alter and update at this hook the $info[field]['settings']['default_colors'] list of hex color values.

I couldn't find the solution I was looking for.


Just got the answer. After PHP 5.5, these constants were removed!

https://bugs.php.net/bug.php?id=68147


Views: greater than a date expose filter

In Views, add a filter of Node: Post date.  You should see something like the image below (without example values changed):

Click Expose to have the filter exposed to your users, choose the operator Is greater than or equal to and choose how you want to filter the results (by inserting a date to be greater than or equal to or entering a value of "-6 months", etc).  This won't present a dropdown, but it will certainly add the filter you need for your view.


A panels display for a node should not affect diff/revisions.

Is there a revision tab for the node?  "node/NID/revisions" also were any revisions created for the node for diff to even compare? By default they won't create a revision.


How do print the query which is built using search api

Enable Views query preview in Views Settings (admin/structure/views/settings) by checking the box "Show SQL query".

Then you will be able to see the query created by your view while you constructing it.


Adding a button above rendered output from a contrib module

If you are already using Display Suite or would like to use it, there is an area to create custom fields and display them within your node. You can use tokens and html.

Here is a good video.


Can a database query be written inside a template.php file?

You can definitely do it, however you really shouldn't.

The theme layer is for presenting the data.
The actual functionality and the data itself should come from modules.

If you mention what you are trying to do I can give some more information on where it should go instead

Edit

Based on your code example, if you are dealing with a custom data table the best thing would be to use hook_views_data() to let views know about your database table and fields. Then you would just use your new fields via the UI.

If you didn't want to go to that much trouble though you could use basically the same solution as you are using now in a custom module in one of the views hooks, like hook_views_post_execute(), where you can loop through the results in a similar fashion as you are doing now.

You generally wouldn't be dealing with markup here though (like your abc_code div). You're really only changing data here and then changing markup in the theme. Although your field should already have classes that let you specifically style it so adding that class probably shouldn't be necessary.


token_replace : operate on two different 'user' entities?

I don't think you can do what you require as the data fed to [user:name] belongs to the currently logged in user. Sender and receiver would be different objects in your database.


Drupal Form API tableselect programmatically check or uncheck checkbox

I fixed this I understand how #default_value works now. It has to be an array.

$values = array();

$values[1] = TRUE;
$values[2] = FALSE;
$values[3] = TRUE;

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );


Override Theme table function used in contributed module?

theme_uc_recurring_user_table() is a theme hook (not a table function), and its preprocess function is hook_preprocess_uc_recurring_user_table().
From the preprocess function you can just change the content of $variables which, in the case of theme_theme_uc_recurring_user_table() just contains $variables['uid'].

What you need to do is overriding the theme hook implemented from the module, which is quite easy, since you are doing it from a theme.

function MYTHEME_uc_recurring_user_table($variables) {
  $uid = $variables['uid'];
  drupal_add_css(drupal_get_path('module', 'uc_recurring') . '/uc_recurring.css');

  // Set up a header array for the table.
  $header = array(t('Order'), t('Amount'), t('Interval'), t('Next charge'), t('Status'), t('Remaining'), t('Options'));

  if ($GLOBALS['user']->uid) {
    $header[] = t('Donations');
  }

  $recurring_states = uc_recurring_fee_status_label();

  // Build an array of rows representing the user's fees.
  $rows = array();

  foreach (uc_recurring_get_user_fees($uid) as $fee) {
    // Get the user operations links for the current fee.
    $ops = uc_recurring_get_fee_ops('user', $fee);

    // Add the row to the table for display.
    $rows[] = array(
      'data' => array(
        l($fee->order_id, 'user/' . $uid . '/order/' . $fee->order_id),
        theme('uc_price', $fee->fee_amount),
        array(
          'data' => check_plain($fee->regular_interval),
          'nowrap' => 'nowrap',
        ),
        format_date($fee->next_charge, 'short'),
        'status) . '">' . $recurring_states[$fee->status] . '',
        $fee->remaining_intervals < 0 ? t('Until cancelled') : $fee->remaining_intervals,
        array(
          'data' => implode(' | ', $ops),
          'nowrap' => 'nowrap',
        ),
      ),
    );
  }

  if (empty($rows)) {
    $rows[] = array(array(
        'data' => t('Your account has no recurring fees.'),
        'colspan' => 7,
      ));
  }
  elseif ($GLOBALS['user']->uid) {
    $rows[0]['data'][] = l('Update Donation', '/donation');
  }

  return theme('table', array('header' => $header, 'rows' => $rows));
}


Webform - Show the preview page on confirmation instead

You can achieve that like follows

Go to your Webform form settings, then find Redirect Location and select Custom URL:

Here you can insert tokens but for that you need to install the Token module.

After install and enable the Token module, Click on Browse available tokens link.

Let's say your webform URL path is node/5.

You need to insert Custom URL path like follows

node/5/submission/[submission:sid]

Then whenever user submits the webform, will be redirected to their webform submission results page.

Hope this simple solution helps you.

There is another way you can achieve that by writing some custom code in tpl files. Follow the Print submitted data on confirmation page


How to create Media video youtube entity programmatically?

Code example:
use Drupal\media\Entity\Media;

$media = Media::create([
  'bundle'      => 'my_youtube',
  'uid'         => 1,
  'name'        => 'my_video',
   'field_media_oembed_video' => [
    'value' => 'https://www.youtube.com/watch?v=iZ53oOOTsdc',
   ],
]);

$media->save();


Add specific CSS class to form elements from the address field

You can use the hook_form_FORMID_alter in order to add classes to the fields you want to.

/**
* Implements hook_form_FORM_ID_alter();
*/
function hook_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['my_custom_field']['#attributes']['classe'][] = "my-custom-class"
}


Get file ID and path to use in View template

The THEME_preprocess_views_view_fields(&$var) function in the template.php in your theme directory is get called just before loading the Row Views Template file. Every component of the current row is saved inside the $var array.

To get what you need, simply just kpr($var) and it gives you all of the information about the current row. You can also save these information in the $var array as an index and use them later.


How to change the size of the avatar in Drupal 7?

You should use theme_image_style instead.

**Update:

Example setting width/height attributes by hand (until it's resolved in Drupal core):

global $user;
$user = user_load($user->uid);
print theme('image_style', array( 'path' =>  $user->picture->uri, 'style_name' => 'thumbnail', 'width' => '150', 'height' => '162'));

Remember to change your image style 'thumbnail' in this case to your desired width/height. Now that I think about it you don't necessarily need to use theme_image_style, you could just edit the image style thumbnail presets and get the desired results. If you want width/height HTML attributes, use the example above.


How to add custom css class to block wrapper

You can also use the Block class project for the matter.

  Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!


I have a similar script that I use, but I run it as a drush scr.  You can adapt it for your needs, perhaps to do this in a hook_cron():

$tags = taxonomy_vocabulary_machine_name_load('tags');

$tids = db_query('
  SELECT DISTINCT t.tid
  FROM {taxonomy_term_data} t
  LEFT JOIN {taxonomy_index} i ON i.tid = t.tid
  WHERE t.vid = :vid
    AND i.tid IS NULL
', array(':vid' => $tags->vid))->fetchCol();

if (!empty($tids)) {
  foreach ($tids as $tid) {
    taxonomy_term_delete($tid);
  }

  watchdog('foo', 'deleted @count orphaned tags', array(
    '@count' => count($tids),
  ), WATCHDOG_NOTICE);
}

This exact version is untested and a hand-edit from a very specific use-case I have.  Take backups and use at your own risk!

The only problem is that {taxonomy_term_data} doesn't have a created column, so this will immediately delete orphaned terms.  It also doesn't take into term hierarchy, or tags being on entities other than nodes.


Can you try to use:

drupal_render_children($form),

remove "actions". and hide all redundant elements :)

As second approach, you can

  echo render( $form['form_id']);
  echo render( $form['form_build_id']);
  echo render( $form['form_token']);
  echo render( $form['options']['status']);

in the beginning of the template file
Regards


hook_node_presave($node) should be included in a custom module and not in your theme !

Look at Creating Drupal 7.x modules if you want to try so.

In your hook do something like that :

function norma_node_presave($node){

  $value = array();
  foreach( $node->field_checkbox['und'] as $checkbox){
    $value[] = $checkbox['value'];
  }

  $node->field_textfield['und'][0]['value'] = implode('<br>', $value);
}


If you mean the alias for the taxonomy term you can use url() (if you just want the URL), or l() if you want a link:

$url = url('taxonomy/term/' . $term->tid);

$link = l('Link text', 'taxonomy/term/' . $term->tid);

Both of those will give you the current path alias for the term page


Your template is expecting that the node title will be displayed as the page title, which in controlled in the page.tpl.php. Either the title is printed, but not where you expect or you don't print the page titles at all.


js file in custom module's library is not attached when big pipe is running

So it turns out that it was big pipe, but unrelated to my module. Elsewhere on the page a profile image is loaded to appear next to the user name, and if the user has none, a default image. It seems that if a 404 is returned (in this case because part of the oath did not yet exist to match the path supplied for the image), when big pipe goes to load it and gets the 404, downstream js is not loaded.


How to noindex on paginated pages in Drupal 7?

You can use Metatag module and Metatag Quick module to add a "noindex" meta tag to the artiklar content type for pagination pages (you will use the path based metatags part of metatags_quick).


How to check if a Vocabulary is translatable?

This information is stored in configuration and you can retrieve it by using this service:

\Drupal::service('content_translation.manager')->isEnabled('taxonomy_term', 'my_vocab')

More info Where do I fetch myself complete definition for a bundle?


Check out Contact Storage.

Among various other features, like being able to store contact messsages, the latest version has a view builder that allows to display a referenced contact form (it's a config entity, so you can reference it using a standard entity reference field).


Different user form for registration and edit

the multistep registration module will help you with this I think.
Together with the profile2 module.
Those 2 modules will help you with the multi step registration part. For the user edit page you should check the checkbox in the profile2 preferences where it says use a seperate page for editting user profiles


When you create a new view, you can choose on which entity the view is based on. In the first picture the view is based on File, in the second picture it is based on Content (nodes).

You only see the fields of that source you have selected.

Another method to get the fields from File would be to configure a relationship using a reference field. But this is then additional, you get fields from both tables by doing this.


This is a setting that's built into the core of Drupal. On D7/D8 the Who can register accounts? (Public registrations in D6) setting adjusts who can create accounts on your Drupal installation.

Administrators only
Visitors
Visitors, but administrator approval is required

The settings form can be found under /admin/config/people/accounts (/admin/user/settings in D6).


Add cardinality_unlimited taxonomy reference to custom entity

This is the best solution I have been able to come up with so far.  Answers are still welcome, because I still don't know:

Why this is happening, is it a views bug?
Could I have created the field in a way that using a hook to alter the query is not necessary?

What I ended up doing was using hook_views_pre_execute(Drupal\views\ViewExecutable $view) to get the query out of $view->build_info['query']->getTables() and then manually change the condition on my join table to use the correct column, which was not poll__cat.cat but rather poll__cat.cat_target_id.


Artifical part of URL path, not corresponding to node, triggering view attaching

In the Page settings section of the view editing form, there is an item labeled Path. Click on this item. It allows you to enter the path under which the view will be accessible.


Create Taxonomy vocabularies and terms in installation profile

'Terms' are data, so you must import them using the Migrate module or Feeds module.

It's easy to create 'vocabularies', not programmatically but using a Feature and then enable it with you installation profile.

But if you want programmatically here is a good article that describes how to create Taxonomies vocabularies and terms programmatically.


Frontpage is a menu item...title won't change

Just deactivate the predefined menu link and add a new one - use

<front>

as path.

In Drupal 7 and 8 go to

Home > Administration > Structure > Menus > Main menu > Add link

Drupal 7

See tooltip for details (using Rubik Theme)


Why submit button is losing disabled attribute after deletion of uploaded file?

You can't do it, because on remove event, only HTML for file input field is reloaded. There is a need of using custom AJAX callback for this (such as ajaxSuccess). I don't know nothing about Drupal Ajax callbacks for this type of event too.


Access the value of a disabled field in a twig template

Try to add it on you hook_preproccess_node to variables.

something like following snippet could help you.

on your THEMENAME.theme

function THEMENAME_preprocess_node(&$vars) {
    $node = $vars['node'];
    if(isset($vars['node']) && $vars['node']->getType()=='YOUR_CONTENT_TYPE_MACHINE_NAME') {
        $values = $node->field_color_backgroud->entity->getValue();
        $vars['myvar'] = $values[0];
    }

}

Then on your TWIG file {{ myvar }} will be available.


Trigger 'Add another term' using javascript

Try this code

jQuery('#edit-field-attribute-und-add-more').click();


How does the theme folder work in drupal 7?

Folder name does not matter. What matters is name of the info file. If you have themeName.info in folder, Drupal knows it's a folder for a theme named themeName.


(Nearly) single page website - any clever ways to manage menu anchor links?

Use the single page site module, this has all the functionality you need to get this working.
https://www.drupal.org/project/single_page_site


How to translate my drupal site in other language.

As your module is not hosted on drupal.org, the strings it uses are not available on localize.drupal.org, where they can be translated in any language available there.

As such, you need to enable the Locale module, and translate the strings on your site.

With Drupal 7, you visit the page at admin/config/regional/translate/translate, and you get a list of untranslated strings you can translate.

In Drupal 6, a similar page is available on admin/build/translate/search.


Execute product pricing rule for the order owner

In any product pricing situation, you should always make your user related conditions check against the commerce-order:owner token, not the site:current-user. That sounds like exactly what you need.


Get current URL arguments inside ajax callback?

The arguments passed to the page callback are saved in $form_state['build_info']['args'], with the exception of the form ID.

If you use the following definition for the menu item, you would get them there. (Replace 'form ID' with the form builder ID.)

$item['name/%/%/%'] = array(
  // …

  'page callback' => 'drupal_get_form',
  'page arguments' => array('form ID', 1, 2, 3),

  // …
);

References

drupal_get_form()
drupal_build_form()


How to create a view for logged in user?

I added an extra reference field to dossiers which refers to an user. In the view: add relationship to the referenced field and make it mandatory. Now it works. The logged in user sees only his files.


How to remove the status bar from CKeditor?

I managed to remove the status bar for a profile (admin/config/content/ckeditor/edit/some_profile) by adding this code in Advanced Settings > Custom JavaScript configuration :

config.removePlugins = 'elementspath';
config.resize_enabled = false;

Code found here on the CKeditor forum.


Disable default view when offering module is disabled

hook_disable() is what you are looking for:

  Perform necessary actions before module is disabled.

  The hook is called every time the module is disabled

Remember to do inverse actions with hook_enable(), which is used when a modules is enabled, install hooks don't fire when a module is re enabled.

Also if you need to track enable/disabling of another module you can use hook_modules_disabled() and hook_modules_enabled()

(it looks like you found it, but adding an answer for others is always good).


Like @alias suggested, you can Create an SQL query that will go over the url_alias table and create whatever aliases you want.

Note: for a small number of nodes, the answer is much much simpler:

Go to admin/config/search/path/patterns to define the new URL pattern for that content type.
Open the admin/content page.
Filter by a specific node type.
Check the checkbox above the content item to select all the items of the certain type.
Select the 'update URL alias' operation.
Press 'Update'.

Two other options if you have a medium number of nodes:

Temporarily change the number of nodes per page hardcoded in core. This will allow you to use the option above with more then 20 nodes at a time.
Create a VBO content admin view to allow the user to select more then 20 nodes on a same time, then select which action to execute.


why does internationalization menu i18n_menu translate but never localizes?

As said in the 2nd choice Translate and Localize, there are two different ways for translating menus.

If you want to use the Menu items with language will allow translations option, set a link in each of your defined languages, but none in language neutral, and check in admin/structure/menu/manage/main-menu then in *admin/structure/menu/item/[ITEM_ID]/edit* for each set of translation, that it is correctly translated.

Now if you wish to work with the Menu items without language will be localized option,  make sure you create the menu item in the site default language (because localization always happens from the site's default language to other languages). And choose language neutral for the menu item when created.

Now in the opened up Translate tab, you'll translate the menu item title and description instead of creating another menu item. And you're done !

For a complete explanation read this nice tutorial about Drupal multilingual navigation.


The ShortcodeBase Class uses renderplain which strips 'the attached assets and cache tags'

In the comments to the source code they say: We use renderplain so that the shortcode's cache tags would not bubble up to the parent and affect cacheability. Shortcode should be part of contentand self-container.

In order to attach the library I then rendered the Array with this code:

$renderer = \Drupal::service('renderer');
return $renderer->render($output);

and it works. Need to understand if and how it affects cache, though.


List the hooks that can be used in .install file?

I think you are missing function
hook_field_schema
This hooks are mentioned in the "list" and "number" default module which is in "field" module.


Seeking iPhone/iPad JavaScript/jQuery libs, techniques & tutorials

The only thing that I know of that's close to what you want is on Eric London's Drupal blog where he talks about themes and redirects for mobile versions of Drupal websites.  I'd be interested in knowing more about this too, sorry that I couldn't be of more help.


Problem with adding checkbox to a view of flags with webform view

Using drupal commerce (irrelevant), session_api, flags, views, webform4, custom content type (product display in my example), custom module.

Works even under anonymouse user

I think it's in select field settings.

Called "Multiple":

webform_flags.module:

    <?php
 /**
 * Implements hook_webform_select_options_info().
 */
 function webform_flags_webform_select_options_info() {
    $items = array();
     if (function_exists('webform_flags_user_flag_sample_requests')) {
         $items['webform_flags_user_flag_sample_requests'] = array(
         'title' => t("User's flagged products"),
         'options callback' => 'webform_flags_user_flag_sample_requests',
         );
     }

    return $items;
 }

 function webform_flags_user_flag_sample_requests() {
     $view = views_get_view('user_flagged_products', TRUE);
     $options = array();
     if(isset($view)){
         $view->set_display('webform_options');
         $view->execute();

         if ($view->result) {
             //$row_class = $view->style_options['row_class'];
             //$attributes = $row_class ? " class='$row_class'" : '';
             foreach($view->result as $item) {
                //dpm($item->field_field_image);
                $options[$item->nid] = '<a>' . render($item->field_field_image[0]['rendered']) . $item->node_title .  '</a>';
         }
         }
         else {
            $options[0] = t("Nothing");
         }
     }

    return $options;
 }

View's settings:


How to generate 'tag' field in form config module?

The standard site install includes a "Tags" taxonomy vocabulary, and includes a "Tags" field on the "Article" content type.  You can either reuse these components on your own site, or duplicate them for your particular use case.


Add a display by copying settings from another display in Views

If you want an exact copy of the page, you can clone the display.  In Views 3 on Drupal 7, you do this by opening the view to edit it and clicking the downward-pointing triangle next to view page above Advanced and choosing clone page.

EDIT: Sorry, missed that.  By default, Views will use all applicable settings data from the Master display (hidden by default in Drupal 7).  So your content pane should inherit whatever the settings are in the Master display, which will be the same as those for the first display you created (the view in the first row) in that view, assuming you didn't override anything.  (note that some things may not apply to content panes when moving from a page but your fields, relationships, etc. Should definitely be pulled in by default under normal circumstances.)

To make the Master display visible so you can see if there's something going wrong with it, you can visit admin/structure/views/settings and check Always show the master display.

It sounds like you have multiple displays and the one you want is not the master display.  I don't think there's an easy way to copy settings back to the master display so your best bet is probably to make the master display visible and reset it to what you want before making more displays.


drush appears to not be respecting --no-backup

This is a Drush bug, and would best be raised in the issue queue.  By coincidence, someone recently posted this: http://drupal.org/node/1741108


Cannot seem to get hook_preprocess_page to work in 8.4.2

both should work on custom MODULE or THEME

function MODULENAME_preprocess_page(&$vars) {
  //do stuff
}

function MODULENAME_preprocess(&$vars, $hook) {
  if($hook == 'page') {
    //do stuff
  }
}

You need to rebuild cache and at least when using netbeans be careful not all lines will trigger the breakpoint ... for example I have noticed that multiline array definitions will not trigger it.  Post your code for more details


DraggableViews not displaying drag-handles

All "draggable" tables in Drupal have a switch that turns the draggable javascript interface off, and allows you to order the items using a less interactive "ordinary" form with fields to enter weight numbers and a submit button.

There is a link, usually at the top right of the table, that says Hide row weights if you have the draggable option turned off, and Show row weights if you have it on.

Look for that link, it's probable you just have it turned off.

Once you make the switch it will be "remembered" in a cookie so it will apply for all the draggable tables on the site. Maybe you changed it on some other table, Drupal remembered it, and you're simply seeing the non-draggable case in your draggable views.

I guess this brings up to the surface that "Draggable views" isn't quite an accurate name, because it works even without dragging. Maybe it should be called "Order views" or something similar, but javascript tools usually win that race and this example illustrates it.

I hope this is the issue here. Nothing broken, just a temporary UI blindspot, we've all been there :)


Rule action to remove a product from the cart? (using the commerce module)

Check what rszrama, the Drupal Commerce leader, says about this:

  If you find and delete the line item, it should work just fine. You can do this with the "Delete entity" action. You could also just unset the price of the line item you want deleted during "Calculating the sell price of a product." That's what the "Unset the price of disabled products in the cart" default rule does, so you can refer to it for an example. Unsetting the price just involves setting the amount to NULL (i.e. no value, not 0).

http://drupal.org/node/1267156#comment-4937288


Here is a module that does exactly the same as you want.

From Module page.

    Create a new view (eg: a list of node).
    Set format Table Rowspan for this view.
    Add some field to this view.
    Group field that has same value.
    Check option "Merge rows in group".

Click on settings and group by your results by Principal, Guest, Email Member, Non Email Member. This module will render your table in exactly the same format you want.


How to show 2 instances of the user profile form, displaying different form modes, on the same page?

You don't need to modify core files, you can modify the "user" entity type in a hook. This is how you add a form class for the form operation change_password:

mymodule.module

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('change_password', 'Drupal\user\ProfileForm');
}


drupal_match_path() for multiple wildcard patterns?

The API page you've linked describes the format of the $patterns argument:

  $patterns: String containing a set of patterns separated by \n, \r or
  \r\n.

These are types of carriage returns, in different Operating Systems.

Sooo .... did you try:

 $pattern = "portfolio/*\nphoto-blog";
 // or
 $pattern = "portfolio/*\rphoto-blog";
 // or
 $pattern = "portfolio/*\r\nphoto-blog";

EDIT:

 // for platform portability heh
 $pattern = "portfolio/*" . PHP_EOL . "photo-blog";


hook_url_outbound_alter only for links in node body

For the googlers:

Module:

/**
 * Implements hook_url_outbound_alter().
 */
function draft_links_url_outbound_alter(&$path, &$options, $original_path) {
  // Internal URLs only
  if (!$options['external']) {
    // Check if current page is draft page
    if (preg_match('|/draft(/?)$|', current_path())) {
      $options['alias'] = $path;
    }
  }
}

/**
 * Implements hook_preprocess_page().
 */
function draft_links_preprocess_page(&$variables) {
  if (preg_match('|/draft/?$|', current_path())) {
    drupal_add_js(drupal_get_path('module', 'draft_links') .'/draft_links.js');
  }
}

JavaScript:

(function ($) {
    $(window).load(function() {
        $('.node__content a').each(function(){
            href = $(this).attr('href');
            // Internal URLs only.
            if (href.match(/^\/?[0-9a-zA-Z]*/) && !href.match(/^(https?:)?\/{2}/)) {
                $(this).attr('href', href+'/draft');
            };
        });
    });
})(jQuery);


How can I save the configuration value in a custom submit form method

The blockForm is used to configure a block. The configuration is then used to build the block.

If you want to use the configuration system to store data in the database use one of these methods:

Simple Configuration Form
Creating a configuration entity
type


Adjust search system - return all nodes, but exclude a specific node type if a field is less than current date

I think you need a different kind of SQL Join there, your (inner) join will produce a result set of only nodes that have an respective entry in the field_data_field_date table.

I would try a left outer join and add an OR condition for field_date_value2 being NULL. An example:

$u_alias = $query->leftJoin('field_data_field_date', 'fd', 'n.nid = fd.entity_id');
$query->fields('fd', array('field_date_value2'));
$db_or = db_or();
$db_or->condition("{fd}.field_date_value2", '2016-03-08T21:30:00', '>=');
$db_or->isNull("{fd}.field_date_value2");
$query->condition($db_or);

Cheers!


How to assign "Access Results" permission per Webform?

Sounds like you need Permissions per Webform module

You can set permissions per Webform as it suggests. Under the form settings.


Allow customers to add arbitrary data to products when adding to cart

For the benefit of anyone who comes looking, the answer is that the fields need to be added to the order item type. Commerce sees each product as a sort of Platonic object and stamps out instances as order items -- think line items. You can add fields to this. Whee. Unfortunately, you can't reference Paragraph entities because, as ridiculous as it seems to me, Paragraph entities only support a single reference.


The property of field_image.value is wrong, it should be field_image.entity.

$registry->addFieldResolver('Product', 'image',
  $builder->compose(
    $builder->produce('property_path')
      ->map('type', $builder->fromValue('entity:product'))
      ->map('value', $builder->fromParent())
      ->map('path', $builder->fromValue('field_image.entity')),
    $builder->produce('image_url')
      ->map('entity', $builder->fromParent())
      ->map('field', $builder->fromValue('field_image'))
  )
);


Libraries Not Loaded After Cache Clear / Reload

Solved

this issue occurred because I've another custom module with the same name as the theme.


How to upgrade to Drupal 8 from 7 with clean install?

If I'm understanding your situation correctly in that you just want a new Drupal 8 website without any of the content from your existing Drupal 7 website then you would just simply install Drupal 8 from scratch, as if you didn't even have an old site.

Once the new Drupal 8 website is installed you can then create/re-create any content that you'd like.


Explicitly passing argument to local action for access check

Answered my own question. The key is that we are working with route parameters,  not route options which are akin to l() in Drupal 7.

This article goes into more detail. Here is the important part:

# yaml file to define one or more local task(s).
#
# Definitions can contain any of the following:
# title: (required) The untranslated title of the menu link.
# description: The untranslated description of the link.
# route_name: (optional) The route name to be used to build the path. Either a
#   route_name or a link_path must be provided.
# base_route: Used to group together related tabs.
# parent_id: Use the parent_id to relate a tab to a parent tab for multiple
#   levels of tabs.
# route_parameters: (optional) The route parameters to build the path. An array.
# link_path: (optional) If you have an external link use link_path instead of
#   providing a route_name.
# weight: (optional) An integer that determines the relative position of items
#   in the menu; higher-weighted items sink. Defaults to 0.
#   Menu items with the same weight are ordered alphabetically.
# options: (optional) An array of options to be passed to l() when generating
#   a link from this menu item.

So my action routing file is updated:

entity.group_content.create_form:
  route_name: entity.group_content.create_form
  title: 'Add new service'
  route_parameters:
    plugin_id: group_node:service
#  defaults:
#    plugin_id: group_node:service
  appears_on:
    - 'view.group_services.page_1'

Flush caches.


How do I execute my custom submission handler before any other submission handler?

array_unshift() the name of the function onto the "#submit" array of the button.


Is there any elegant way of excluding form element from the `values` array of the `FormState`?

Not within the building of the form as far as I know. You'd need to strip out the values you don't want in the submit handler as you mentioned.

This is probably the easiest way to remove the default form values:

$values = $form_state->cleanValues()->getValues();

That will remove: form_id, form_token, form_build_id, op


How can I implement a flag module with caches but won't affect cache the flagging nodes?

Views Content Cache has a patch for flags support, although I don't know how well it will work with Boost.

Try using the Views Flag Refresh module, it's supposed to tell the view when to refresh, don't know if it will play nice with the other modules though.


Setting default image style to 'original image' in formatter

It is have simple solution when you want specified image_style use something like

  image_style_url('850x450',$file->uri);

and when you don't want use any image style and want use origin image use

 file_create_url($file->uri);


Drupal schema API not supporting MySQL date data type?

You could define it yourself, have a look at http://drupal.org/node/159605#comment-1674678.

You should however only do this if you are sure that you will only ever use/support MySQL.

Portability with date data types among different databases is almost impossible. Drupal 7 initially had date types defined but they were removed again because there is simply no way to make them work consistently across multiple database types.

You might want to look at http://drupal.org/project/date, I'm pretty sure that allows to use dates that can not be mapped to a UNIX timestamp.


I think what are looking for is hook_node_validate()

  Perform node validation before a node is created or updated.

  This hook is invoked from node_validate(), after a user has has
  finished editing the node and is previewing or submitting it. It is
  invoked at the end of all the standard validation steps, and after the
  type-specific hook_validate() is invoked.


Difference between drupal_static and \Drupal::state?

They perform different tasks.

drupal_static() only stores data for the current page load (or ajax load). For example, if you are loading something from a database table multiple times on a single page load (ie - a user account), the first time it is loaded it is saved to memory, and the next time it is needed, it is pulled from memory, rather than reloading it from the database, saving that second database query.

Drupal::state() saves data to the database, where it can be recovered in future requests. It's a cache of sorts.

You can actually use them in conjunction with each other as follows:

function get_some_value()
{
  // Instatiate the static
  $value = &drupal_static(__FUNCTION__);
  // Check if the value has already been set in this page load
  if(is_null($value))
  {
    // The value has not yet been set for this page load,
    // so retrieve it from the state if it exists, and if it
    // does, then save that to the static
    $value = \Drupal::state()->get('my_value');
    // Check if the value was retrieved from the state
    if(!$value)
    {
      // The value was not retrieved from the state, so
      // it needs to be generated. Below is an example
      // fetching it from the database
      $value = db_query('SELECT some_value FROM {some_table} WHERE some_column = :some_value', [':some_value' => 'some value'])->fetchField();

      // Save it to the state for future page loads
      \Drupal::state->set('my_value', $value);
    }
  }

  // Return the value
  return $value;
}

With the above code, the first time this function is hit, it will first check if the value exists in the static cache (this page load), and when it doesn't, it attempts to retrieve it from the state cache, and when it doesn't it finally generates it with a database query, saving it both to the static cache, as well as the state.

If it hits this function again on the same page load, the value will be in the static cache, so none of the internal code is needed, and the value is returned from the static cache.

On a future page load, the first time this function is hit, nothing is retrieved from the static cache, so it will pull it from the state cache. If the function is hit again on that page load, the value will be in the static cache and returned from that.


Message not being sent in the body of the mail

You need to add a hook_mail code

As this line $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send); behind the scenes will invoke this hook_mail function.

something like this:

/**
* Implements hook_mail().
*/
function <module_name>_mail($key, &$message, $params) {

 $options = array(
   'langcode' => $message['langcode'],
 );

 switch ($key) {
   case 'uploaded files':
     $message['from'] = \Drupal::config('system.site')->get('mail');
     $message['subject'] = t('@title', array('@title' => $params['node_title']), $options);
     $message['body'][] = $params['message'];
     break;
 }
}


Adding multiple users to a field using user/autocomplete

as @Geat said:

Your form should be like below.

    $form['usershare'] = array(
      '#title' => t('Share Collection with:'),
      '#type' => 'textfield',
      '#autocomplete_path' => 'user/autocomplete',
      '#multiple' => TRUE,
    );

    // Implemenbts hook_menu() for user/autocomplete path.
    function module_name_menu() {
      $items['user/autocomplete'] = array(
        'page callback' => '_user_autocomplete',
        'access arguments' => array('access user autocomplete'),
        'type' => MENU_CALLBACK
      );
      return $items;
    }

    // Implements callback function to get users in autocomplete with comma seperated
    function _user_autocomplete($string) {
      if ($string) {
        $items = array_map('trim', explode(',', $string));
        $last_item = array_pop($items);
        $prefix = implode(', ', $items);
        $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
        foreach ($result as $user) {
          $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
          $matches[$value] = check_plain($value);
        }
      }
    // return output in JSON format.
    drupal_json_output($matches);
}


How to create a vocabulary and populate it with terms using features

The problem with exporting content like taxonomy terms is keeping the taxonomy id intact when migrating it from site to site which is exactly what the features extension module UUID Features solves by using the UUID api:

  The UUID Features Integration module provides a mechanism for
  exporting content (nodes, taxonomy, fields) into a features module.
  What's that you say? You thought features was only for configuration?
  This module is meant to be used in the cases where certain pieces of
  content straddle the line between pure content and configuration.


This should give you a list of the fields and types on your site.

drush field-info fields

Should output something like this

 Field name               Field type            Field bundle
 body                     text_with_summary     page,article
 field_image              image                 article
 field_category           entityreference       article
 field_name               text                  article


How to create a "go back" or "cancel" button on the node add form?

Adding '#limit_validation_errors' will help override validation,

$form['actions']['submit_cancel'] = array (
  '#type' => 'submit',
  '#weight' => 999,
  '#value' => t('Delete all input and return to previous page'),
  '#submit' => array('MYMODULE_userpageredirect_callback'),
  '#limit_validation_errors' => [],
);


How can I do the dynamic select in Drupal 7 forms?

In any case take a look at the first answer of this question: i think it's what you are lloking for https://stackoverflow.com/questions/5158744/drupal-7-best-practice-for-a-dynamic-select-list-in-drupal-7


Open the view which you've created, expand Advanced Option column
open Theme:Information
copy the last theme suggestion from Row style output row
go ahead to the theme(project theme) folder and create that file,
example, views-view-fields--docs---page-1.tpl.php (this is how my
template looks like, this is just for an example), rescan the templates, and save the view.
debug $fields array (better install Devel module, it provides useful functions, like dpm(), dsm()..)
Copy the code from the sample template and put into this template.
Lastly, put the output of fields (e.g. something like this <?php print $fields['SOME_FIELD']->content; ?>) to the desired html blocks..

Don't forget to clear the cache;


How to create Dummy Content with certain data restrictions (specific date ranges, users, values, ...)

Quick solution that worked best for me in the end:

The solution i gave before was indeed the best one to have a general solution and use the mechanisms that were used in the devel module, but what worked best for me in the end was to just use the HOOK_node_presave to validate the nodes that were created by the devel module.

function MY_MODULE_node_presave($node) {
  // only do this for my_type, and only for nodes created by the devel module
  if ($node->type == 'MY_TYPE' && isset($node->devel_generate)) {
    // apply the limitations, e.g. use values between 2 and 8 in our field
    $node->field_my_field["und"][0]["value"] = mt_rand(2, 8);
  }
}

In case a node of the type MY_TYPE is generated by the devel module (verified by checking the devel_generate property) we give the field field_my_field a value between 2 and 8. This is not possible with the devel module, but we can apply this custom restrictions here and modify the node before it is saved.

So the devel module will create the node as usual, but the function above will modify its values to our needs before it is being saved to the DB.

This has the desired effect although it is hard coded in our custom module, it does the trick.


Include referenced term's custom fields in node view with content display

The Default Content View mode is controlled through the Manage display page of the related Content Type.
Check that page and make sure that the Taxonomy Term reference field is set to Rendered entity and not Label or some other option.
The Rendered entity option will make sure that all the Vocabulary fields set to be displayed for terms will also appear under Content rendering of the Content type.


Is it possible to change the tab order of MENU_LOCAL_TASK items on a given page?

An easy and correct way is to change the weight as you do. Did you clear menu cache?


Well, since you already loaded the order, I guess you could do:

<div class="order-id">
  <?php print render($content['order_id']); ?>
  <?php print format_date($order->created, 'custom', 'd-m-Y'); ?>
</div>


I seem to understand that for every user with "uid" = "userID", you want to create 1 role like "role_userId" ... That means if you have dozens of users (only), you have dozens of roles. Not to mention that you have hundreds (or thousands?) of users if you'd have hundreds (or thousands?) of roles ... IMO that is not a good idea. I'm not sure what exactly you're up to with that "user view some fields which are public and others can only see friends (user relationship or flag friend, ...)", as in your question, but it does seem to be related to access permission somehow.

Have a look at the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

In your case you could have 1 Group "Type" (eg: "User Groups"?), and create 1 group for each user. Think of a Group Type as equivalent to a Content Type, and a Group (of a specific Group type) as equivalent to a node of a specific Content Type). You'd probably come close to having something with a 1-to-1 relationship between a specific user and Group permissions related to that user (whereas Group permissions is not the same as standard Drupal permissions ...).

Also, since Group is fully entity based, it integrates perfectly with Rules also. With that in mind, you could use Rules to capture Rules Events about user relationship or flag friend (as in your question), and then trigger Rules Actions to manage various access levels to the Group designated to that user. Important to realize: you wouldn't need like dozens (or hundreds/thousands?) of "roles".

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


The following code does what you seem to need (screenshots attached). The following modules need to be activated:

i18n_menu (part of the i18n)

Further configuration:

I added a new language (tr) and set language detection to "Determine the language from the URL (Path prefix or domain)."
I added a new menu with machine name (menu-sol-menu) and set the translation mode to "Translate and Localize". Also added the new menu as a block to the header region of the theme.
Added the following code in a custom module and activated it.

function agi_menu() {
  $items = [];
  $items['agi'] = [
    'title' => 'AGI (Family Status Declaration)',
    'page callback' => 'drupal_get_form',
    'page arguments' => ['node_form'],
    'access arguments' => ['access content'],
    'menu_name' => 'menu-sol-menu'
  ];
  return $items;
}

I visited the menu admin page and saw that a new menu item was added:

I checked the language option for that new menu item, it was set to neutral.

I visited the home page of my drupal instance and checked that the menu item appears, for both english (default language) and turkish, using the URL to define the current language.

Finally, I looked in the translate interface for the title of the menu item.

Conclusion: The provided code with the described configuration works as expected by the OP.

Good luck!

N.B.: Especially for the 'title' and 'title callback' properties, the documentation is very clear about how to use them in a multilingual setting

  "title": Required. The untranslated title of the menu item. "title
  callback": Function to generate the title; defaults to t(). If you
  require only the raw string to be output, set this to FALSE.


generate a coupon automatically after checkout

Here is a little help.

Actions

Add Action - Entites - Create a new entity - select Commercce Coupon - Continue - Save
Add Action - Data - Set a data value - select the field you want (ex. entity-ecreated:commerce-coupon-number-of-uses) - enter the value you want - Save
Do the 2. for the fields you want

--

At the end I decided to do my custom Rule action for creating a coupon, because is more flexible.


Using xdebug to find out why a variable is mysteriously set to 0

The key idea here is to use the "step into" functionality of PHPStorm to figure out when the second argument ($column within the function's declaration) gets changed.  $id_key shouldn't change at all if you're describing the calling conventions correctly, the second argument would have to be declared as &$column, i.e., as a reference to the variable.  So I'm assuming that's what you mean. Otherwise, PHP passes a scalar variable "by value", and won't let any changes made to the variable in the body of the function change the original variable outside of it.

And there's nothing inside of the function that will change it either.  Here J. Reynolds is right; you're passing the wrong thing to fetchCol(), which wants an integer. But fetchCol() doesn't modify its argument either.

Since you're using xdebug, this then raises an important question: how are you using it?  Is your php process running on the same server as PHPStorm?

I ask this because one thing can definitely go wrong using xdebug: you can be debugging a different file than you think you are, if you're "mapping" a file on your server to a local file. If the file isn't the same, weird things can happen like what you describe. You may not really be on the line you think you are, since xdebug will tell PHPStorm the file line on the server, which may be a different line entirely on your local file. And the values of variables, if they display at all, may have different values than what the code displaying in PHPStorm allows.

Without knowing how you've set up PHPStorm to get to your PHP process, it's hard to know what exactly's going on. But you should describe what technique you're using, so folks can give you a better answer.


How to use Tamil language in my website?

Use Internationalization module to make your site multi language. It gives you translate interface for every language you select in configuration.

After enabling the module you have to add Tamil as language under admin/config/regional/language/add.


Change the product status after checkout_complete

You'll want to use the commerce hook_commerce_checkout_complete which runs after a order is complete (AKA paid for)

http://www.drupalcontrib.org/api/drupal/contributions%21commerce%21modules%21checkout%21commerce_checkout.api.php/function/hook_commerce_checkout_complete/7

That provides the order and you'll just need to get the product ID from that $order variable, load it with product_load(), change the value you want and then save


Send email notification to node author with Rules

This worked.

As a workaround, you can use the data selection string as a token in the direct input textarea.

Switch to data selection and get your string, in my case content_moderation_state.uid.entity.mail.value

Switch to the direct input mode and paste the string with double braces {{content_moderation_state.uid.entity.mail.value}} to use the token replacement API.

As described here: https://www.drupal.org/project/rules/issues/2799569#comment-12376804


How can I create multiple cropped Media images without re-uploading them?

Solution:

Install Crop API and Image Widget Crop modules
Configure Image Widget Crop as explained in the tutorial, for Image field situated in Structure > Media types > Image. The image style for this Image field should contain no effects.
There where you want to use cropped image, select the style for it (in content type, for example) that contain "Manual crop" effect and, if you need, "Crop and Scale effect" (to display square thumbnails in listings, for example).
There where you want to use full umage, select the style for it that contain no "Manual crop" effect.

How to use images:

Upload a large full image, crop manually the interesting part
Use the same image there where you need it cropped and there where you need it full. It will be displayed differently on front.

Note: if you try to clone the Image entity (for example with Entity Clone module), it will not help because the clone Image entity and the original Image entity will apply the same crop.


Limit the search to only one content type

These instructions by selvam on KnackForge worked for me. Basically, you can use the MODULE_search_apachesolr_query_prepare hook to add a filter to the query before it's run.

<?php
function MODULE_search_apachesolr_query_prepare($query) {
  if (/* not correct page */)
    return;
  $compiled_filter = new SolrFilterSubQuery('AND');
  $compiled_filter->addFilter('bundle', 'TARGET_CONTENT_TYPE');
  $query->addFilterSubQuery($compiled_filter);
}

I haven't actually tried the hook, but I did use the filter and apply it to a query in a different context (API) and it worked as expected.


I think your problem is that you are focusing on the label. You need to use a contextual filter of 'Block: Block Delta'. Then you can add a menu tab to views using this path:

block/%/back-links


It seems that it's very easy to implement a computed dependent field. Suppose there is a term reference (field_section) on an edit form with YOUR_FORM_ID.

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == YOUR_FORM_ID) {

    // Add an AJAX behaviour to field_section:
    // After you will select a new term on the edit form,
    // YOUR_MODULE_NAME_form_alter and
    // _YOUR_MODULE_NAME_form_section_callback will be called.
    $form['field_section'][LANGUAGE_NONE]['#ajax'] = array(
      'event' => 'change',
      'callback' => '_YOUR_MODULE_NAME_form_section_callback',
      'wrapper' => 'nomination-desc-wrapper',
      'method' => 'replace',
      'effect' => 'fade'
    );

    // Add a wrapper for our computed dependent field.
    // At the begining it will be invisible
    $form['nomination_desc_container'] = array(
      '#type' => 'hidden',
      '#weight' => 2,
      '#attributes' => array('id' => array('nomination-desc-wrapper')),
    );

    // Add a computed dependent field. It will be shown as a text
    $form['nomination_desc_container']['nomination_desc'] = array(
      '#type' => 'item',
    );

    // This code will be executed during form creation and
    // during each AJAX-call
    if (isset($form_state['values']['field_section'])) {

      // Find taxonomy term
      $tid = $form_state['values']['field_section'][LANGUAGE_NONE][0]['tid'];
      $term = taxonomy_term_load($tid);

      // Show it's description
      $form['nomination_desc_container']['nomination_desc']['#markup'] = $term->description;

      // Display description wrapper
      $form['nomination_desc_container']['#type'] = 'container';
    }
  }
}

// Just return new wrapper body
function _YOUR_MODULE_NAME_form_section_callback($form, &$form_state) {
  return $form['nomination_desc_container'];
}


Is there a way to make aliases as short as possible?

hook_pathauto_alias_alter is nearest to your query.

First parameter $alias will be newly created alias by pathauto. You would have to analyze it with some regex pattern for undesired pattern generation.

The second parameter will give you contextual picture of item in associated array.

module definitely be taxonomy_term
source system path of taxonomy e.g. taxonomy/term/<tid>

I think you will have pretty much to analyze the term and get its hierarchical info to update $alias variable.


Config split settings file generated into split directory

Have you checked the $config_directories array in the settings.php/settings.local.php files.

It might be a good idea to explicitly set it via config as per https://www.drupal.org/docs/8/configuration-management/changing-the-storage-location-of-the-sync-directory:

$config_directories[CONFIG_SYNC_DIRECTORY] = '../config/sync';


How to add a different specific image for each page in a region?

I assume that you have a content type which contains the field image and that image field have to displayed randomly in different pages. If so the solution would be

Create a block view and add the content type as criteria and the field:image
Remove all sort criteria and just add Global: Random as a sort criteria
specify only one content should be displayed in Pager option

That's it. Now you can render it and it will randomly display the image in each page


How to set defaults for a custom Views display?

The class views_plugin_display_page defines its options (and defaults) through the
views_plugin_display_page::option_definition() method. This method is just a series overridden methods that extends from the view base class. In a similar manner, your custom plugin can override this method:

// defined in your views_plugin_display_page descendant class
function option_definition() {
  $options = parent::option_definition();

  // @TODO: set your own options plus override any other options
  // defined in parent classes. For example:
  // $options['path'] = array('default' => 'my-default-view-path');

  return $options;
}


What is the best way to theme the first row in the view differently?

In this specific situation, the issue can be easily solved by simply using CSS to target .views-row-1 differently than the other rows, as Jimajamma mentioned.

However, if you had a situation where the content in that first row was much more different than in the other rows, there is a solution natively in Views to create this sort of layout.

Create two displays in your View using the same filter criteria.  Display A would be a block that shows only one node (the top, larger item in your mockup) and has a larger image format and different order for the fields to be displayed.  Display B would be the display that you use as the page that your users see.  You would attach Display A to the header of Display B and set Display B to be offset by 1 result, so that it does not duplicate the first node.

Here is a screenshot of the Views 3 UI, showing where to find these settings.  Earlier versions of Views support the same type of set-up, but the naming and placement of the settings in the UI is different: https://skitch.com/sheenad/gqdmm/archive-content-shop.


Try the Background Images module as a ready-built solution:

  Background images is a collection of modules that allows users to add
  background images to html elements on pages of the site


adding css classes into a specific image field

As of Drupal 8.2

function MYTHEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_news_images') {
    foreach($vars['items'] as $key => $item){
      $vars['items'][ $key ]['content']['#item_attributes']['class'][] = 'thumbnail';
    }
  }
}


Make a Search view have the same options as a Content view

H,

This is something I'm still searching for an authoritative solution to/answer on.

This is apparently known issue with Flag and Views, with most people taking programmatic approaches to solve their particular problem.

There's a patch to that should address at least some of your problems here. https://www.drupal.org/node/1362298. This seems to be the closest anyone is to a solution at the moment.


Accessing a webform's element properties including #title, #description via tokens is not currently supported. I am not sure the core Webform module should provide these tokens, but a third-party module can easily make these tokens available.


How to get the value of a variable in CCK from Devel?

As you mentioned after enabling the Dev module, you can use dpm($variable); to get a detailed graphical listing of the array values.


How to get the customer name in Commerce order confirmation e-mail?

First, you have to create function as @NoSSweat suggested (thanks for the hint) and from it get it like:
function hook_preprocess_commerce_order_receipt(&$variables)
{
  $givenName = $variables['billing_information']['#profile']->get('address')[0]->given_name;
  $variables['given_name'] = $givenName;
}

(was incredible hard to figure this out :) ) Field name for last name would be "family_name". Checkout the file:
/modules/contrib/address/src/Plugin/Field/FieldType/AddressItem.php
for other available fields.
I added this function to my module, but adding it to theme file should also work.
That way you are assigning variable which is now available in twig template so you can print it simple as:
{{ given_name }}

Don't forget to clear the cache.


How do I completely unpublish a node (not just change revision state) when using Workbench Moderation with rules?

Well, I suppose it's a bit late, but this issue is discussed in and should be mostly solved by https://drupal.org/node/1436260 once the issue is fixed. You should be able to unpublish the node, and as long as the code calls node_save, workbench moderation should set the state back to draft. If you want a different state, e.g. "archived", you'll probably have to come up with something custom.


Drupal 8: Read field value from $variables in preprocess_html

So your field is on the node?

Then you need to get the node object first.

<?php
if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {

}

Once you have that, you can read your field, assuming it is a text field, like this: $node->field_background_color->value. Make sure to always check if you really have a $node object as done in the snippet above when you're in the global context. You will only have on on node/N, but not on other pages.

There are many questions already about how to access field values, and there are great presentations as well.


how to get information about discounts on product?

On the line item, you have the field_unit_price field. Inside of that field's data attribute, you'll find information about the discounts that are applied to that product:

array(1) {
  ["components"]=>
  array(2) {
    ...
    [1]=>
    array(3) {
      ["name"]=>
      string(22) "discount|discount_test"
      ["price"]=>
      array(3) {
        ["amount"]=>
        float(-240)
        ["currency_code"]=>
        string(3) "USD"
        ["data"]=>
        array(2) {
          ["discount_name"]=>
          string(13) "discount_test"
          ["discount_component_title"]=>
          string(5) "Test"
        }
      }
      ["included"]=>
      bool(true)
    }
  }
}

Iterate over the components. If there is a discount applied to one of the items, you'll find one with a name that begins with discount|.  Then you can then load that discount and grab more information about it:

$discount = entity_load('commerce_discount', array('discount_test'));

From here, if you've added dates, the date fields will be accessible on the field commerce_discount_date.


How to set a term reference field value from a text field with Rules?

Looks like you could just use the "add to list" Rules Action.

For multi value fields you should not use "Set a data value" (which is possibly what you've tried, a common mistake when using Rules for such fields).

Refer to the answer to "How to set multiple values to an unlimited Term Refence field with Rules" for "some" more details ...


How do you give the content of a node a margin/padding without using html within the node?

it varies per whatever theme you use. it's typically something like div.node or div.node div.content as an example. tools like Firebug and Chrome developer tools can show you what classes a piece of content has in your HTML page. Using DisplaySuite for example you could provide additional classe(s) to any piece of content within view_mode -- but the basic markup exists per theme to target a nodes output on the screen.

It not only varies per whatever theme your using, but if your theme is HTML5 vs HTML4 (why in this day in age, i dunno) it may be article.node as a CSS selector because article is a new HTML5 element type, vs say a plain old div.node in older versions of HTML.


You can use Simplify

  Simplify allows particular fields to be hidden from the user
  interface. This helps to de-clutter forms and present a more
  user-friendly experience to content editors.

Enable the module, then go to People >> Permissions and check mark View hidden fields for the user role you want to allow to see them.


The 'drupal' way to implement delete button UI: part 2

It does look good! But you could remove the repeating hook_menu items as well.

When I said the following,

  When the entity gets complicated, I often end up writing a single menu
  router to handle them all. The operation argument of a menu path
  (edit, delete, clone, disable, etc) can be a wildcard loader as well,
  and you can easily validate it using a method_exists() call.

I actually meant that you'd use one menu router item that passes extra variables to resolve the call to an actual function. Now that you have posted some real code, I'd go ahead and show an example for you. Note that this is not an official way to do this, but I practice this quite a lot and never had a problem.

The only menu router item we need.

$items['bluenose/%/%'] = array(
  'page callback' => 'bluenose_app_rmelement',
  'page arguments' => array(1, 2),
  'access arguments' => array ('access bluenose_app wishlists'),
  'type' => MENU_CALLBACK,
);

The page callback to handle 'em all.

function bluenose_app_rmelement($type, $id) {
  switch($type) {
    case 'rmlist':
      bluenose_app_remove_wishlist($id);
      drupal_goto('bluenose/wishlists');
      break;
    case 'rmlistitem':
      bluenose_app_remove_list_item($id);
      drupal_goto('');
      break;
    case 'rmavailableproperty':
      bluenose_app_remove_available_property($id);
      drupal_goto('');
      break;
    default:
      break;
  }
}

Now, you will notice that the menu router item is actually of type MENU_CALLBACK, and its not of type MENU_LOCAL_TASK. If you want to make it a local task, it has to be defined so in the hook_menu... But you can also do so in a hook_menu_local_tasks_alter() hook implementation.

If you absolutely need to make all the operation links to be MENU_LOCAL_TASKS, you can either go for the multiple router item way (from your original question's snippet) or implement hook_menu_local_tasks_alter(). With this hook, you are dynamically adding menu router items only when the current router item is what we are after.

Also, note that menu paths that immediately execute the functions are vulnerable to CSRF attacks. When you create the URLs, you should add a token to the link and validate it in the page callback. See drupal_get_token() and drupal_valid_token().


You can use Display Suite to duplicate your fields, go into Structure -> Display Suite -> Fields and add a dynamic field. Fill out the details specific to your node, etc.

On the Manage Display page of your content type you need to configure this field and select your product details, etc.


User error: "attributes" is an invalid render array key when rendering image

Yes, it seems like you are not supposed to render item in a field template. Render item.attributes and item.content separately:

{{ item.content }}

Or the attributes in a  if the
 doesn't work with your layout and you need the attributes:

{{ item.content }}

BTW storage' => [] is part of the Attribute object any code can store attributes on its way until it reaches your template. So it's a good idea to print the attributes, even if they are now empty, because you don't know which extension you might want to install in the future and debugging will then be some fun until you'll find out that one of the field templates is not fully working.


How do I export data into yaml with mapping?

Those two are semantically the same thing. The only difference is that the {} format is more compact.
See the output in these two links.

Regardless, the second argument to the dump method lets you configure the verbosity of arrays. See Writing YAML Files.


Switch style plugin of a view based on results

I have finally discovered a workaround, that may be the solution for some. I display the view using Panels. Using visibility rule, there is possibility to limit visibility of view based on number of results of that view. The steps could be:

Create a Contextual filter for your view for field Content:Nid. This should correspond to argument of your Ctools Page (so that path of a page is similar to something/%nid). You may need to add Relationship, if you want to display content, that is related to the content with nid.
Create a Context display for your view.
Create a 2 separate displays (Content panes) for your view - for one result and multiple results.
Create a new Relationship based on your view for your Panel (at the Contexts tab).
Add both your content panes to the panel.
Add Visibility rules to both panes. You should choose PHP-based filtering and enter something like:

if (count($contexts['relationship_view_from_argument:name-of-your-view-ctools_context_1_1']->output['rows'])==1) {
return TRUE;
}


How to display all children on parent node for custom content type?

How are the children linked to the parent? Do you use an Entity Reference field?

Also, what do you want to display from the children? The titles? The entire, rendered nodes?

If you look up entity_metadata_wrapper (see: Entity metadata wrappers) you can see how to access an Entity Reference field.

You also may want to reconsider Views. Overriding templates for Views can give you a lot of flexibility.


"public://" is not resolved correctly to the full path

The reason there's no $base_url is because the script you're running isn't in a HTTP context; when Drupal bootstraps, unless you've specified a $base_url in settings.php, it retrieves this value from $_SERVER['HTTP_HOST'] which doesn't exist in the command line context.

To remedy this, you can set the $base_url in your settings.php or, if you're running Drush, use the --uri argument.

drush scr --uri="http://www.example.com" my_script.php