Best APC settings to reduce page execution time

We run in a SVN push environment so we only clear the apc file cache with a script.

APC settings:

apc.ttl=604800
apc.user_ttl=3600
apc.shm_size=192M
apc.include_once_override=1
auto_globals_jit=Off
apc.num_files_hint = 2048

apc.stat_ctime = 0
apc.file_update_protection = 2
apc.stat = 0

PHP Script:

<?php
$return = apc_clear_cache('opcode');
echo var_export($return);

604800 = 1 week.

After this, getting xdebug/xhprof up and running and doing a cache grind of the site should let you know what's slowing down the site. In short analyzing the cache grind output is the best way to speed up Drupal. Below I'm listing what patches and modules we use to speed it up; in your case it will be different most likely.

Drupal 6 Specific Answer Below

Once you get past this point and realize the APC isn't going to give you what your looking for, switch to pressflow and give these patches a whirl:

Core - Cache module_implements()
Imagecache - use lock.inc instead of a file lock
Views - views_get_default_view() - race conditions and memory usage
Views - Persistent caching for unpack_options() calls from building displays

Also try some of these modules as they improved our sites speed in a big way:

Imageinfo Cache
Advanced CSS/JS Aggregation


You have to set the permission inside the Views BLOCK SETTINGS > Access


Querying taxonomy terms with the level hierarchy

have you reviewed taxonomy_get_tree() documentation? http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_get_tree/6 I guess that taxonomy_get_tree() documentation and code function could be a guidance.

  taxonomy_get_tree
  ...

  Return value

  An array of all term objects in the tree. Each term object is extended
  to have "depth" and "parents" attributes in addition to its normal
  ones.


How I can intercept an image field upload and validate it?

It looks like there a couple of very small bugs in that code that would stop it working properly, try this:

$lang = $form['field_all_images']['#language'];
foreach (element_children($form['field_all_images'][$lang]) as $key) {
  $form['field_all_images'][$lang][$key]['#upload_validators'][] = 'check_image_correct';
}


What's the size of your image? For scale you may need roughly:

X * Y * 4 (bytes per pixel) * 2 (for source and destination image) * 2 ( to make sure there is enough RAM for computation).

Now, core can require up to 32 MB, and modules can easily double or even quadruple this. So, let's optimistically assume your core + modules only use 64MB. That leaves other 64MB. It means you can safely scale images up to 4194304px. It seems you have enough memory for 4Mpx input images. Anything larger can cause this error and it will not be anything surprising.


I believe your primary question is:

  Is there a way to get a query that when run against MySQL directly, it will output similar results to that of views?

You're probably getting an error when you try to run the query when copied directly from Views UI.  Change the {node} to myprefix_node, changing myprefix_ to the prefix you gave your tables.  If you didn't supply a prefix than simply replace {node} with node.

To respond to your other question:

  I don't understand what it is doing here: 'node' AS field_data_field_vis_group_node_entity_type Is views doing some additional processing after this to get the data?

Views creates aliases for the columns that are returned by the query so that it can more easily reference it later on.  In this case it is creating a hard-coded value of "node" for each result, which is interesting.  And the hard-coded value has an alias of field_data_field_vis_group_node_entity_type.


Main_menu Google Analytics Event Tracking

To do that I was using Menu attributes module with Onclick Event patch. Simply install it, apply patch, enable module and you will be able to add onclick code to menu elements via GUI.


What are the minimum requirements for a custom Drupal 8 theme that can be enabled

Perhaps you've missed core.
Required params in *.info.yml are:
name
description
type
core
regions:content

Also you can check your *.info.yml for using tabs instead of spaces:

  Tabs are NOT allowed, use spaces ONLY.
  You MUST indent your properties
  and lists with 1 or more spaces.

See more in official docs: https://www.drupal.org/theme-guide/8/defining-a-theme


Yes. As Clive says in his comment above, you can certainly use Composer to manage other code besides Drupal core and contrib modules.

If you are keeping your code in version control such as git, this also has the advantage of keeping third-party code out of your project's version control repository. Just commit your composer.json and composer.lock and you can rebuild all your project dependencies when you deploy.


The simplest way to do this would be to create the order that you want until the step that you want with your admin/webmaster/whatever role that has enough permissions and then, edit the order and change the owner.

If you create an order so the customer can pay it, you just send them the checkout url, as you changed the owner, they will have access to finish the checkout.

If you process the payment as well, you need an extra step of configuration, in order to send the customer a proper notification that the order was made. Rules is a good way to do this.


Access the label for a form element via hook_form_alter

The attributes for labels are hard-coded into the theme_form_element_label() function. You can override it at the theme/module level but you'll have to do so for all labels in the system as the variables passed to the theme function do not contain the form context.

The easiest thing to do would be to add a predictable class to each label in every form (based on the name of the form element that the label is for), and then use a CSS selector based on a combination of your form ID and the label class to target it.

Unfortunately there's a fair bit of code you'll need to copy over, and only one small change you'll need to make, but I can't think of another way to do it:

function MYTHEME_form_element_label($variables) {
  $element = $variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element['#title_display'] == 'after') {
    $attributes['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element['#title_display'] == 'invisible') {
    $attributes['class'] = 'element-invisible';
  }

  if (!empty($element['#id'])) {
    $attributes['for'] = $element['#id'];
  }

  // NEW CODE HERE
  $label_class = 'label-for-' . $element['#id'];
  $attributes['class'] = isset($attributes['class']) ? $attributes['class'] . ' ' . $label_class : $label_class;

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
}

Once you put that code in your theme's template.php file and clear the cache, you'll be able to target the label with CSS like so:

form#webform_client_form_3 label.label-for-edit-field-name


It sounds like you're confusing hostnames with file system paths.

The array mapping in sites.php is:

Hostname => Instance Folder

So taking your example, requests for http://mysite.example.mydomain.com will use the folder /sites/mysitedev.example.mydomain.com.

In that scenario, the path /sites/mysite.example.mydomain.com/files doesn't exist, so requests for files under it will return a 404. That's to be expected.

You can always add an alias/redirect via your server config, but it might be best to just use the system as it was intended.


How do I retrieve media from a reference field?

Do you have to do it with a DB call? Why not use Drupal's existing functions?

  // Load a node by node ID.
  $nid = '213';
  $node = \Drupal\node\Entity\Node::load($nid);

  // OR load current node.
  $node = \Drupal::routeMatch()->getParameter('node');

  if (!empty($node)) {
    // Assumes you have a media field called "Related gallery"
    $medias = $node->get('field_related_gallery')->referencedEntities();

    foreach ($medias as $media) {
      // Do stuff with the media.
    }
  }


How to hide clientside validation error message

You can hide error message using CSS or you can use Inline Form Errors which allow you to hide the error message.


The first argument those callbacks get is $element which, essentially, is a render array as described in Render API overview. This means, for example, that a #date_date_callbacks callback could use code similar to the following one.

function mymodule_date_callback($element, $form_state, $date) {
  $element['date']['#attached']['library'][] = 'mymodule/mylibrary';
  // Optionally, the callback can pass values to the JavaScript code.
  $element['date']['#attached']['drupalSettings']['foo'] = 'bar';
}


Custom Fieldable panels pane template rendering the Field collection items

I found the answer. Actually, by using $elements in .tpl file, we get all variables and also all fields as an array. You can use it to render the output you want to.


When creating an autocomplete form in a custom module how do tell Drupal what modules I need?

See the examples module for a straight forward AJAX Example.


Reducing redundancy (code duplication) in templates

Yep, you can do it in a simple manner, just follow this

It simply states you can (for example) use
<?php include 'page.header.inc'; ?> on a template and include the code for that header.
In this .inc file you just enter the code you want to reuse


How to detect insertion of new item(s) into Drupal's queue?

There is another question here with some equal requirement: Insert task to Queue only if unique

The idea is to create a custom queue class extending the original one. Your custom class only overrides the createItem method. Just copy the original one and add your custom functionality.

After that you need to let Drupal know about your new queue class.

The downside is that it would override the class of your queue for every operation on it.


Restore drupal commerce cart if paypal payment gets failed

Following solution worked for me

function custom_module_commerce_checkout_page_info_alter(&$checkout_pages) {
  $checkout_pages['payment']['status_cart'] = TRUE;
}


How do I theme a link from a template file?

Here's a twig only solution for a particular field that needs this treatment;
it's not a generic solution for all links everywhere.

some-template.twig:

  {% for item in content.field_links %}
  {% if item['#title'] %}

        {% if item['#options']['attributes']['class'] %}

        {% endif %}
        {{ item['#title'] }}

  {% endif %}
  {% endfor %}


form submit hook handler not getting called in drupal

The submit for the node form is attached to a specific button, so something like this should work:

$form['actions']['submit']['#submit'][] = 'myform_form_submit';


Results in view page having multiple duplicate result

What version of Drupal/Views are you using?
In Views v7.x-3.x you can use hook_views_pre_render() in your template.php file or in a module to filter duplicate results like this:

function YOURTHEMENAME_views_pre_render(&$view) {
  $used_nids = array();
  $new_view_result = array();

  if ($view->name == 'YOURVIEWNAME') {
    foreach ($view->result as $row) {
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
    }

    $view->result = $new_view_result;
  }
}


Adding and reading a static HTML page with

File (Field) Paths allows you to specify path using node fields. Using it, you can have node's files in directories like sites/default/files/custom_pages/[nid]/[node_title]/
Just make sure to put .htaccess inside custom_pages folder, one that will allow direct html serving.

Then you can generate link using the very same tokens.


Mismatched entity and/or field definitions

I got the above errors but with the node table. I am not sure if this is a safe thing to do but I executed the following MySQL command at the prompt:

ALTER TABLE node DROP INDEX node_field__uuid__value;

After that the entity updates executed without any problem.

For the author's problem I suppose you could adapt the command to:

ALTER TABLE taxonomy_term_data DROP INDEX taxonomy_term_field__uuid__value;

The key should be generated the next time you run that entity updates Drush command.


Use hook_block_info and hook_block_view. Something like this:

function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'my_block':

      $blockContent = '
Nothing to show
';

      // assuming we're getting it from POST but the source can be whatever you want
      if (isset($_POST['key']) && null != $_POST['key']) {
          $blockContent = '
' . $_POST['key'] . '
';
      }

      $block['subject'] = t('My Block Title');
      $block['content'] = array(
          '#markup' => $blockContent
      );
      break;
  }

  return $block;
}


What is the benefit of making sub theme in drupal?

For instance. You override only files you need to and you have in your sub-theme directory only these files, not all. You can update parent-theme and not overriding your customizations.


What do the three checkboxes on the Interface translation import mean?

Treat imported strings as custom translations

Will add to the Site the translations strings present in the .po file as custom translations.

Overwrite non-customized translations

All the strings that comes in the .po file will overwrite the existing translations that are not customized in the Site.

Overwrite existing customized translations

The customized translations present in the Site will be overwrite with the translations present in the .po file.


the problem was in the way I pass submit callback. It should be like

'#submit' => array('foo_submit_callback')

ARRAY!

the less visible thing is the most visible one...


Well, to those who might wonder the same as me: apparently there is no module yet that does this, which surprises me, as it seemed such a basic request to me.

So you have to do it yourself.

For those who need it, I hereby give you my own solution, but ofcourse other possibilities are available.

I made this with a combination of views & total control module.

Total Control gives you a nice dashboard which you can fill with views. For the view itself, you just have to use the aggregate function and a relationship.

Relationship: 'Content: Author'
Use AJAX: Yes (this is to make sure filters can be exposed in blocks)
Use Aggregation: Yes
Make a table with following fields and filters:

Field: '(author) User: Name'
Field: 'Content: Nid' (Aggregation: Count (Distinct))
Filter: 'Content: Post date' => Exposed

extra fields are possible, like I have also added the date of the last article that person made in this specific period, which could also be handy for activity monitoring. To do this, use the field 'Content: Post date' and add the aggregation setting MAX to it.

Hope this helps others in case they are looking for something similar that is easy to maintain, without having to invent things that already exist.


Cannot add content using default content types

If you go to Structure > Menus > Navigation, goto "list links" of Navigation menu, you'll see that all of your content types are disabled except for the actual "Add content" link. Just check the enabled box and save, then you should be good to go.


Querying the database via a url and displaying the results?

Direct answer to your question - you can get the parameter from the query string a number of ways:

use the arg() command (not recommended as best practice)
use the $_GET string, provided by PHP
use drupal_get_query_parameters

Any of these methods would get you the nid from the query string (in your example, 1) - you could then us db_query or node_load to load the data for this record and output it as desired but thats too much work.

Much easier way to do this is to use the views module and add a contextual filter. Setup a basic view and then configure however you like (ex - display full node / teaser or views, etc). Set the path to

record/%

where the percent sign indicates a variable you are going to pass to the contextual filter. Next, under advanced options

select 'contextual filters' and 'add'
search for and add one of type 'content: nid'
on the next screen choose 'provide a default value' of type 'raw value from url', then select the url argument you want to use which in your case is '2'

Views will handle the querying for you and take care of sanitizing the input, and dealing with the output on the way.


Services 3: Setting taxonomy terms on node creation/update

Your request should use the following:

"field_taxonomy":{ "und": { "values": "14" }  }


create layouts without the use of embedded regions

Your best option really is Panels, especially once you get comfortable making your own panel layouts (which is actually quite easy).  Along with using preprocess hooks to attach classes (particularly to body) as needed, the combination of the three lets you do pretty much anything you want.  I have yet to been given a design treatment from my creative director (and they are all complex) that I have not been able to tackle this way.


Override page template and preserve administration navigation bar

What the code is missing is the code that sets those variables the template file is using. Since you are using page--mymodule as template name, the module needs to implement template_preprocess_page__mymodule().
Alternatively, you can suggest a template file using hook_theme_suggestions_page().
function my_module_theme_suggestions_page(array $variables) {
  $path = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
  if (isset($path[0]) && $path[0] == 'hello') {
    return 'page--mymodule';
  }
}

Implementing hook_theme_suggestions_page() like I show, page--mymodule.html.twig will get the variables set in template_preprocess_page(), which are the same variables passed to page.html.twig.


"Undefined index: link path in menu_link_save() (line 3113 of /includes/menu.inc)"

You are using the correct function (menu_link_save()), but you are passing it the wrong arguments, and you are calling it from the wrong hook.

The array key you can pass in &$item are described in the function documentation; the ones marked as (required) are required, and you need to pass them.

  link_path: (required) The path of the menu item, which should be normalized first by calling drupal_get_normal_path() on it.
  link_title: (required) Title to appear in menu for the link.
  menu_name: (optional) The machine name of the menu for the link. Defaults to 'navigation'.
  weight: (optional) Integer to determine position in menu. Default is 0.
  expanded: (optional) Boolean that determines if the item is expanded.
  options: (optional) An array of options, see l() for more.
  mlid: (optional) Menu link identifier, the primary integer key for each menu link. Can be set to an existing value, or to 0 or NULL to insert a new link.
  plid: (optional) The mlid of the parent.
  router_path: (optional) The path of the relevant router item.

hook_menu() is used to tell Drupal which menu paths the module is using, not for saving a menu link when the module is installed. For that there is hook_install() or, in alternative, hook_enable() which is called every time the module is enabled, even after the module is installed; in the case you use the latter, the code needs also to check the menu link is not already present. As side note, hook_enable() is not used from Drupal 8.


How to pass seperate contextual filter values to a view and get results programatically?

Here we go.

 $nodes_str = implode(',', $nids); // $nids is an dynamic array.
 $args[] = $nodes_str; // First contextual filter argument. 12,13,14.. etc
 $args[] = $tag; // Second contextual filter arguments 8,9.. etc
 $view = views_get_view('view_machine_name');
 $view->set_display('display_name');
 $view->set_arguments($args);
 $view->pre_execute();
 $result = $view->execute();
 $output = $view->result;

If need futher details of the view parameters. You can debug the values using the hook_views_pre_view()

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

}

Hope this helps someone.


You can use Field Permissions for this.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

Just set up the fields on the Profile page so that only authenticated users can fill them in.  This will mean that when the anonymous user is registering they won't see the fields, however when they are registered (and therefore authenticated) they can edit them.


Putting a watermark on image using Imagecache Actions

You can use Imagecache Actions module.

  Effects provided

  Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha
  transparency
  Overlays - Add photo-corners etc to the image
  Text overlay - add a short copyright notice to your image, using available system fonts
  Color-shifting - Colorize images. Also invert.
  Brighten/Darken
  Alpha blending - turn an image into a transparent mask, and back into a flat image against another color
  Canvas manipulation - add padding, either onto color or transparent backgrounds
  Background - Place your image onto another source background
  File Format switcher - If you need tranparency in JPGs : make them PNG. If your PNG thumbnails are 30K each, save them as JPGs. (This is
  distributed as part of the color-actions submodule)
  Rounded corners (transparent). With input from canaryMason, we can even set different radius for different corners, and round just one
  corner etc.
  Aspect Switcher new 2009-08 - lets you perform different actions or use different dimensions based on whether the image is 'landscape' or
  'portrait'
  Custom Actions - Execute your own PHP/GD code in the middle of an imagecache generation process. Requires some familiarity with imageAPI
  internals.

I have bolded the ones that would interest you.


How can I link Fields in a View to the entity it belongs to?

The link to node or link to user option you see on some properties in views are special. The reason the possibility is there, is because Views has added the option and functionality in a special handler.

Things are not that easy with fields since they can be attached to anything, which makes it much more complex (compared to nid, uid, title and username). You could probably do this with some code, but usually it's much easier to use the rewrite result option, and select output as link and type in the link with tokens: node/[nid]. I'm not sure, but I believe the Views will run the link through l or url enabling path auto.


Which Foundation 6 files need to be uploaded to my host in order to make my Drupal 8 custom theme working with full capabilities

The .gitignore file that is downloaded with Foundation 6 is tied to just the Foundation framework - if you're planning to track the whole Drupal site, you can safely delete it and just use the one that comes at the Drupal root.

In the past I've just tracked everything (and committed everything) in the framework up, including the bower_components folder.

My [theme_name].libraries.yml file looks like this:

global-styling:
  version: 1.x
  css:
    theme:
      stylesheets/fonts/stylesheet.css: {}
      stylesheets/foundation-icons/foundation-icons.css: {}
      stylesheets/app.css: {}
      stylesheets/print.css: { media: print }
  js:
    bower_components/fastclick/lib/fastclick.js: {}
    bower_components/foundation/js/foundation.min.js: {}
    bower_components/foundation/js/foundation/foundation.topbar.js: {}
    js/app.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

homepage:
  version: 1.x
  js:
    js/jquery-ui-1.11.4.custom/jquery-ui.min.js: {}
    js/wcreek-slider.js: {}

The js is my own theme's js folder, and you can see I'm including some bower_components files.  I'm using the default jquery that shipped with Drupal 8, but I'm using Foundation 5.  You might want to rather include the version of jquery from the bower_components.

Also I would recommend that you set your Drupal administration theme to be different from your Foundation theme (I usually set it to Seven) so there's no conflict between Foundation and the Drupal admin tools, like views, etc.

You might be able to use jquery_update module to specify a lower version of jquery for the admin theme (I haven't tried this in Drupal 8 yet). This might be needed if you are using the overlay module.


How do i create complicated content type?

Install Field Collection

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.

and Field Collection Tab formatter

  Field collection tabs provides a field formatter that allows you to
  output a multi value field collection field as a tabset, with one tab
  per field collection item.

  You can optionally choose a field from the field collection item to be
  used as the tab title.

modules.

Your common elements, guide, faq, forum goes into the field collection. Also put the stage title as a field in the field collection. Then use the stage title field as the title for the tabs.


Try doing this with the Commerce Discount module.  With it, you can create discounts that are either hard-coded dollar amounts or are percentage based.  You'll use the second option.

This module uses Rules to calculate the discount amount based on a product price or the entire order amount.  Read more on the module documentation page: http://drupal.org/node/1706132


When user is registered to drupal site ,disable admin approval notification

You can disable the administration approval option in configuration page /admin/config/people/accounts of your site.

Otherwise, if you wish to maintain adminstration approval but only disable the email, add the following line at your settings.php:

$conf['user_mail_register_no_approval_required_notify'] = FALSE;

Links: Disable register email notification


How to create a Custom Drupal 8 Content Entitiy? - Baby steps edition

Building a basic content entity type in Drupal 8.

In this case we create a Drupal 8 content entity to match a node from our Drupal 7 site, in preparation for migrating this data.

The entity does not implement the Field API so remains in code throughout. Nevertheless it can be a useful skeleton for building out Content Entities.

Background.

This stems from the need to build a basic custom drupal 8 content entity to hold data coming in from a migration.  Elsewhere we will explore writing tests to drive our field code and plugins for field constraints For the time being it is suffice to say:

Our new Drupal 8 advertiser content entity will have basetable fields:

UUID
ID
Advertiser Name

Defining a Content Entity in Drupal 8.

First all our custom entities now live at web/modules/custom.
Inside our custom entity the file structure that we will end up with looks like this:

web/modules/custom/advertiser$
├── advertiser.info.yml
└── src
    ├── Entity
    │   └── Advertiser.php

We start by defining our custom module in module_name.info.yml. This is self explanatory:

name: Advertiser
type: module
description: 'Barebones advertiser entity'
package: custom
core: 8.x

Meanwhile The basic Advertiser entity class and associated schema is defined in src/Entity/Advertiser.php.

We start with an annotation that describes the class that our file contains.

/**
 * @file
 * Contains \Drupal\advertiser\Entity\Advertiser.
 */

The next thing we do is define a namespace for our Advertiser Entity Class. This will come in handy whenever we want to use our classes.
namespace Drupal\advertiser\Entity;

Now it is time to define our entity, which we do in an annotation! - TIP: This is the  actual definition of the entity type it is read and cached so be sure to clear the cache after any changes.

/**
 * Defines the Advertiser entity.
 *
 * @ingroup advertiser
 *
 * @ContentEntityType(
 *   id = "advertiser",
 *   label = @Translation("Advertiser"),
 *   base_table = "advertiser",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */

Because this is a barebones entity we only use a few properties and no handlers (like access). For a comprehensive list of available options for your entity see the docs here: https://www.drupal.org/node/2192175

At this point we have a functional module that defines our custom content entity, however if we go ahead and enable the module we will see that the 'advertiser' table has not been created in the database.

drush sqlc
SHOW TABLES;

This is because our class doesn't have any methods that explicitly interact with the database. Furthermore we need a description of the bare minimum of methods needed for an entity to interface satisfactorily with the Database.

Generally we can add classes by adding something like use Drupal\Core\Entity\ContentEntityBase; after our namespace defintiion at the top of our script. This makes these methods available to our own class, which can extend them or in the case of Interfaces, implement them.

We do two things, we extend an existing ContentEntityBase class that already has the necessary methods to interact with the DB, and implement an ContentEntityInterface to describe...

  the methods that we need to access our database. It does NOT describe in any way HOW we achieve that. That's what the IMPLEMENTing class does. We can IMPLEMENT this interface as many times as we need in as many different ways as we need. We can then switch between implementations of the interface without impact to our code because the interface defines how we will use it regardless of how it actually works. - https://secure.php.net/manual/en/language.oop5.interfaces.php

All this means is that we end up with the following: Tip Remember to add any new classes through a use statement at the top of our script:

class Advertiser extends ContentEntityBase implements ContentEntityInterface {

But we still need use these new useful methods to put something in the database, we start with the basic fields for our entity.

The method baseFieldDefinitions comes from ContentEntityBase class that we are extending.
It takes two parameters:

  The entity type definition. Useful when a single class is used for multiple, possibly dynamic entity types.

And it returns

  An array of base field definitions for the entity type, keyed by field name.

So we implement it like this:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

  // Standard field, used as unique if primary index.
  $fields['id'] = BaseFieldDefinition::create('integer')
    ->setLabel(t('ID'))
    ->setDescription(t('The ID of the Contact entity.'))
    ->setReadOnly(TRUE);

  // Standard field, unique outside of the scope of the current project.
  $fields['uuid'] = BaseFieldDefinition::create('uuid')
    ->setLabel(t('UUID'))
    ->setDescription(t('The UUID of the Contact entity.'))
    ->setReadOnly(TRUE);

  return $fields;
}

So altogether we have this:

<?php
/**
 * @file
 * Contains \Drupal\advertiser\Entity\Advertiser.
*/

namespace Drupal\advertiser\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Defines the advertiser entity.
 *
 * @ingroup advertiser
 *
 * @ContentEntityType(
 *   id = "advertiser",
 *   label = @Translation("advertiser"),
 *   base_table = "advertiser",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */

class Advertiser extends ContentEntityBase implements ContentEntityInterface {

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

  // Standard field, used as unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Contact entity.'))
      ->setReadOnly(TRUE);
 // Standard field, unique outside of the scope of the current project.
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Contact entity.'))
      ->setReadOnly(TRUE);
  return $fields;
  }
}

Now when we run drush en advertiser -y; drush sqlc we can see the advertiser basetable has been added to the database!


Drupal 7, Faceted results from Search Form

Check out these tutorials for faceted / "drill-down" / filtering searching and browsing navigation without the need for solr.

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/ (really good tutorial and this worked for me but for me the URLs need to be made more user friendly, not covered by this tutorial admittedly)

http://webwash.net/tutorials/intro-search-api-part-1-how-create-search-pages and http://webwash.net/tutorials/intro-search-api-part-2-faceted-search (similar to the first tutorial)

They use the Database Search module: https://drupal.org/project/search_api_db but the settings can be modified later to use SOLR for when your site hits the big time and needs the sophistication and scalability that SOLR provides. But for now, database search gets you going without needing SOLR.

For pretty URLs check out module: https://drupal.org/project/facetapi_pretty_paths - this module aims to make your URLs generated by the faceted filtering and search pretty.

The drupal recruiter distribution is an example of using facetapi_pretty_paths : https://drupal.org/project/recruiter
- on this page you'll find more information including how to run a demo via simplytest.me with just a few clicks!

Myself I will be working out how to use facetapi_pretty_paths in my project and any steps I that work I will follow up on here (not an empty promise as I do write up my findings whenever I can)


You can simply create new filter group and OR them. Just use And/Or, Rearrange from drop-down Filter criteria. Use filter groups as per your needs. Hope this helps.


Force users to add Organic Groups content only to their group(s)

At admin/og/og (D6) you can uncheck the setting "Audience checkboxes". From the description "Show each group that the user is a member of as a checkbox in the "Audience" section. This enables the member to place her post into multiple groups. If unchecked, simplify the user interface by omitting the checkboxes and assuming user wants to post into the current group. This simplification only applies to new nodes, and not to edits of existing nodes. Group administrators always see checkboxes."


How to publish and unpublish content depending on the type of user?

Publishing and unpublishing is not the way to go.

Step 1)

Install the Node Access module and give access to each node or content type accordingly, this way people can't share direct links with other users that have a different role.

Step 2)

What you need is to create 3 different view blocks

One for anonymous which lists primaria/docentes & secundaria/docentes nodes.

One for primary which lists all the primaria/docentes nodes

One for secondary which lists all the secundaria/docentes/kit nodes.

  Hopefully node access module lets you filter your view by node access.
  Otherwise, you'll need to make the "kit", "primaria" and "secundaria"
  be a different content types so then you can filter by content type in
  your view.

Use view's access to role and select the role you want to be able to see the view. (see picture below)

Then you place all 3 view blocks wherever you need them (home page perhaps?) and since you have the view access by role, they will only see 1 view (the one they have access to).


How can I output debug info from hook_node_presave()?

install the devel module and dump your variables with dpm($input, $name = NULL) to the screen.

This article shows additional debugging options.


Make taxonomy term only link to term page if multiple nodes have that term?

Looks possible implementing  hook_entity_info_alter()

  Modules may implement this hook to alter the information that defines
  an entity. All properties that are available in hook_entity_info() can
  be altered here.

Here is some sample code

function mymodule_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = 'mymodule_taxonomy_term_uri';
}

/**
* Entity uri callback for taxonomy terms. Add special exception to redirect users away
* from taxonomy term pages to the associated program node page.
*/
function mymodule_taxonomy_term_uri($term) {
  if (count(taxonomy_select_nodes($term->tid)) > 1) {
    return array(
      'path' => 'taxonomy/term/' . $term->tid,
    );
  }
  else {
    return array(
      'path' => '',
    );
  }
}

You need to make some tweaks to get term id by term name.I have not checked about returning the path if node count is 1.


How can I setup a template for displaying all nodes of a given type?

You can create your content type and add fields to it to create sorting criteria.

Use taxonomy to define a vocabulary to plug into your content field.

Use pathauto to set up custom URL alias paths for your content.

Define a view to read your fields, filter all content to find what you want, sort and display it.  YOu can refine your searches using contextual filters, that will read the URL and extract information from it.

Sounds simple enough, but if you are unfamiliar with the modules it takes a bit of work to master them.


How do I use the value of a JavaScript variable in a module?

You could send that value to a callback function in your .module file using AJAX, an example to do that stuff in forms see that tutorial Ajaxify form fields

And you could send any value to js variable see sending-a-javascript-variable-to-drupal


Prevent accessing files in Drupal files folder directly by following link

Have a look at hook_file_download

  Control access to private file downloads and specify HTTP headers.

  This hook allows modules enforce permissions on file downloads when
  the private file download method is selected. Modules can also provide
  headers to specify information like the file's name or MIME type.


After long research about Webform elements, I have finally figured out the solution. Extend the Select Element. :)
use Drupal\Core\Render\Element\Select;

class Facility extends Select {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $properties = parent::getInfo();
    $class = get_class($this);
    $properties['#process'][] = [$class, 'processMyCustomSelect'];

    return $properties;
  }

 public static function processMyCustomSelect(&$element, FormStateInterface $form_state, &$complete_form) {
    // Here you can add and manipulate your element's properties and callbacks.
    return $element;
  }
}

this post really helped me out a lot: Webform Custom Radios/Checkboxes Element does not get rendered in webform : Drupal 8


You need to pass $form_state as reference; the AJAX function needs to be defined as in the following example:

function mymodule_settings_ajax($form, &$form_state) { /* … */ }


Template suggestions periodically not being recognized

Turns out I had the wrong hook specified. I copied this from another theme and forgot to update the hook prefix. So I had:

other_theme_preprocess_node

instead of:

my_theme_preprocess_node

Changing that seems to have resolved the issue.


How to get a second join into hook_views_data?

$data['mymodule']['table']['join']['node'] = [

  //Second table for Join

  'left_table' => 'foo',
  'left_field' => 'nid',
  'field' => 'nid',
]

more info: https://api.drupal.org/api/drupal/core%21modules%21views%21views.api.php/function/hook_views_data/8.6.x


Try creating a condition that the user have the role, before trying to remove it.
Also, you could look into Rules Link - you may be able to add it to a custom Profile Page, allowing the user to access and change their settings via My Account - at least from a UI standpoint it might make more sense.


How to get instance of referenced entity?

The path to referenced entity is very long:
// $id = some node ID
// $field = field name for entity reference field
$node = Node::load($id);

/** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $referenceItem */
$referenceItem = $node->get($field)->first();

/** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
$entityReference = $referenceItem->get('entity');

/** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
$entityAdapter = $entityReference->getTarget();

/** @var \Drupal\Core\Entity\EntityInterface $referencedEntity */
$referencedEntity = $entityAdapter->getValue();

// At this point $referencedEntity is the referenced entity object.

Of course one can still get it via one liner call, but still, it is cumbersome and I wonder why EntityReferenceItem does not provide method that would return the reference entity object.
$referencedEntity = $node
  ->get($field)
  ->first()
  ->get('entity')
  ->getTarget()
  ->getValue()
;

Note: if you have php 8, you can use the nullsafe operator:
$referencedEntity = $node
  ?->get($field)
  ?->first()
  ?->get('entity')
  ?->getTarget()
  ?->getValue()
;

It's also worth noting that it's quite easy to get array of all referenced entities:
$node->get($field)->referencedEntities();

It works because for entity reference fields $node->get($field) returns instance of EntityReferenceFieldItemList which implements referencedEntities() method.


You should try to add a "Content pane" display on the view instead of using a page display (enable "Views content panes" module). "Content pane" allows to set the argument input from the views settings. On the "argument input" you can select "From context" as source, and the required term context.

EDIT: Like I've wrote on the following comments, the correct contextual filter settings is:

1) Content: Has taxonomy term ID (with depth). Provide a default value: Taxonomy term ID from URL (Load default filter from term page). Specify validation criteria: Taxonomy term, Filter value type: Term ID

2) Content: Has taxonomy term ID depth modifier


How to keep Ajax refresh action when 'Use Ajax' option is disabled?

@sumit madan's approach then is the best, leave your view ajaxified, and remove the paging, simplest seems to me by overwriting this method of the behavoir in your theme:

/**
 * Attach the ajax behavior to each link.
 */
Drupal.views.ajaxView.prototype.attachPagerAjax = function() {
  this.$view.find('ul.pager > li > a, th.views-field a, .attachment .views-summary a')
  .each(jQuery.proxy(this.attachPagerLinkAjax, this));
};

just make it an empty function (add this code in your theme behavoir)

Drupal.views.ajaxView.prototype.attachPagerAjax = function() {};

this function also needs to be overwirtten:

Drupal.views.ajaxView.prototype.attachPagerLinkAjax = function() {};


How to get $nid inside hook_menu_alter function

Menus are cached; unless you have something funky going on, loading a node won't rebuild that cache (it would be frightfully expensive to do so).

You need to make 'live' decisions in a callback, e.g.

function MYMODULE_menu_alter(&$items) {
  $items['foo']['access callback'] = 'MYMODULE_access_callback';
}

function MYMODULE_access_callback() {
  $node = menu_get_object();
  if ($node && $node->bar) {
    return TRUE; // Allow access.
  }

  return FALSE; // Default for anything that doesn't match your criteria.
}

The above is a contrived example, real-world will be different depending on exactly what you need to do.


How to display only parent terms of hierarchical terms  in Views field

I think my answer to a similar question would be useful:

I believe that your problem would be solved by adding a relationship to your view. Here are the steps:

Add Relationship: taxonomy terms on node
Select the vocabulary you want to use.
Add Relationship: parent term

Now you should be able to add fields from any of the terms or their parents, and to use them as contextual filters as well.

Note that this is for Drupal 7


Webform module - Contact form will not send webform emails to users with the same domain, but will send to all other email accounts I set

You using a shared hosting?  Could be that the recipients mail server is thinking your mails are junk if the originating mail is not coming from the resolved hostname.  This problem is common with shared hosting since they use virtual hosts.


What does a value like node:{node_type} mean?

That definition isn't about what is passed to NodeAddAccessCheck, that is solely defined by the slug definition in the path and the type hinted argument.

Instead, it is configuration for its implementation. Which it doesn't actually use. So yes, it is pointless. See \Drupal\Core\Entity\EntityCreateAccessCheck for an access check that actually uses that definition to dynamically get the value it wants from the route match parameters.

I suppose this initially used that and was switch to a different implementation, without removing the now unnecessary configuration.


No, that would not be advisable; instead, use the jQuery Update module.


I believe that could happen if you have a Javascript error on your page, or that you have Javascript disabled in your browser. For the former, open the error console (Ctrl+Shift+J in Firefox and Chrome) and try to figure out what might be causing it.


Don't print $title on certain content types

There is also a module for this:

Exclude Node Title

  Info

  This module handles a very simple functionality, decide whatever to
  exclude a node title from full node page or node teasers.

  It provides a checkbox on node-edit pages for easier exclusion.

  Also provides the option to hide all titles of a certain Content type.
  From the administrative interface you can select a content type to
  hide title for.

And if you have Display Suite installed then this article explains how to do it with that module:

Hide “Page Title” quickly using Display Suite in Drupal 7

  This is something that is so simple to do, once you have figured out
  the steps to get to the right little click boxes to appear. I wish
  that it were more intuitive to find, but for all those who struggle
  with “hiding” the page titles, Display Suite makes it really easy to
  choose to hide the page title for a specific Content Type or for a
  particular Node.


Is taxonomy a good choice for managing Code Lists, instead of creating tables of their own?

Since there isn't anything common between codes and labels, I think you should create your own table.

Also see How to Decide Between Using Taxonomy Terms and a CCK Field


Events showing on a calendar is radically different formats

Well I half-way solved my the issue by changing a Multi-day event to a single column. I have some more reading and research to do on importing calendar events but for now, the rendering is correct.

This setting is found in the Views Format box by clicking Settings next to Format: Calendar.


show a form in a popup when a button is pressed

Another solution is to use Ctools Automodal module. This approach is less complicated to @Web-Beest answer.

Here is the example on how to use it.

function mymodule_menu() {
  $items['mymodule/form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('administer mymodule'),
    'modal' => TRUE,
  );
}

The most important line in the above code is 'modal' => TRUE,.


The PDF Reader module sounds like what you're looking for.


How can I remove or overwrite the YAML validation from a Webform Entity?

I was able to achieve this, thanks to some guidance in the comments, by overriding a service.

This involved work in two custom module files.  The first was modules/custom/mymodule/src/MymoduleFormParserServiceProvider.php

Within that file I used ::alter to alter which class is called for a particular service.

<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;

/**
 * Replace Webform validator service.
 */
class MymoduleServiceProvider extends ServiceProviderBase implements ServiceProviderInterface {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('webform.elements_validator');
    $definition->setClass('Drupal\mymodule\MymoduleWebformElementsValidator');
  }

}

What this does is tell Drupal that when the webform.elements_validator service is called, use the MymoduleWebformElementsValidator class instead.

The second piece of the puzzle was to create that class.  I did that by extending the original class WebformEntityElementsValidator with my own MymoduleWebformElementsValidator class and doing the logic there.  That way I was able to keep most of the validation from the original, but make the changes to the validate method that were needed.

I was able to find many of the answers after googling override service thanks to the comment on the question by @jrockowitz


When you want to display an entity field based on the "Manage Display" settings, you should go just {{ content.my_field }}. If you "kint" content (var dump it) you can see that each content field element has also "theme" key/property, which tells twig how to render that field


Customize what fields show on Views Exposed Filters Block

Simply rearrange the fields i.e. put field image before the taxonomy name. You can get the rearrange button at right side of FIELDS in view configuration.


You're looking at the same information rendered in different ways:

The menu along the top is quite simply reading from the database for any link in that menu.

The page is constructing itself based on the hierarchy of the hook_menu implementation. You're going to need to implement hook_menu for your new link to get it to show on the 'page' version of the menu.


Ajax Multiple Callbacks is not working for first callback?

You don't need multiple ajax callbacks, you need multiple ajax commands.

First wrap each form element in a separate div container and then return for each one an ajax command from the same callback:

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;

...

  function example_ajax_callback(&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#example-wrapper1', $form['field_example1']));
    $response->addCommand(new ReplaceCommand('#example-wrapper2', $form['field_example2']));
    return $response;
  }


Add a button in user orders view requesting info about current order Drupal Commerce 7

You can use the Rules module.

Create a component with the Action Send mail. Use tokens to customize the subject and message body as you like.
Edit the view and use VBO to trigger the rules component.


In view, select full/mini pager & do necessary settings. Please check screeshots below

Change pager type

Change settings


In Node References, how to show a custom field, instead of the Title?

As dobeerman says you can use a View as a source, but CCK does some playing with the View behind the scenes (I just found out as a result of this question;). If you look in nodereference.module at the function _nodereference_potential_references_views() you'll find the following code:

// We do need title field, so add it if not present (unlikely, but...)
$fields = $view->get_items('field', $display);
if (!isset($fields['title'])) {
  $view->add_item($display, 'field', 'node', 'title');
}

// If not set, make all fields inline and define a separator.
$options = $view->display_handler->get_option('row_options');
if (empty($options['inline'])) {
  $options['inline'] = drupal_map_assoc(array_keys($view->get_items('field', $display)));
}
if (empty($options['separator'])) {
  $options['separator'] = '-';
}
$view->display_handler->set_option('row_options', $options);

So this means that

if you don't include a title field then it will be included for you;
if you don't make all fields inline and define a separator then it will be done for you.

So if you configure the title field to be hidden, and specify an appropriate separator, you should be able to create just about any effect. If you can't achieve what you want with a view (eg. ordering nodes by their menu position) then you want to use a different approach.

You could create your own CCK widget, or (simpler) you can use a form_alter hook. If you do the latter, you can't edit the form the normal way because CCK hasn't processed the form at this stage - you'll want to use a #after_build function.

I have an example of the second approach used to show nodereferences ordered by the menu if you're interested.

/**
 * Implements hook_form_alter().
 */
function banners_form_alter(&$form, &$form_state, $form_id) {

  // Modify nodereferences for banners so that pages are shown in primary links
  // order.
  if ($form['#id'] === 'node-form' && isset($form['#field_info']['field_pages'])) {

    if (!isset($form['#after_build'])) {
      $form['#after_build'] = array();
    }
    $form['#after_build'][] = 'banners_after_build';
  }
}

/**
 * After_build callback for modifying CCK field select options.
 */
function banners_after_build($form, &$form_state) {
  // Get the menu data
  $new_options = banners_generate_page_options();

  if (isset($form['#field_info']['field_pages'])) {
    $old_options = $form['field_pages']['nid']['nid']['#options'];
    $final_options = banners_process_options($new_options, $old_options);
    $form['field_pages']['nid']['nid']['#options'] = $final_options;
  }

  // Return new form
  return $form;
}

/**
 * Uses the old options to filter out unreferenced nids and add those that
 * weren't detected in a menu structure to the other option group.
 * @param $new_options
 *   The options list created by scanning the menus.
 * @param $old_options
 *   The options list originally passed to the form.
 *
 * @return
 *   The final options list with option groups for each menu and for orphans.
 */
function banners_process_options($new_options, $old_options) {
  // Have to assume that $old_options could get quite large, whereas
  // $new_options is based on menus, and shouldn't get too large.

  // Iterate through $new_options (the menu nids) and remove nids from
  // $old_options that exist in $new_options, and remove nids from $new_options
  // that don't exist in $old_options. After this $old_options has valid nids
  // that aren't under the menu hierarchy.
  foreach ($new_options as $menu_title => $options) {
    foreach ($options as $nid => $title) {
      if (isset($old_options[$nid])) {
        unset($old_options[$nid]);
      }
      else {
        unset($new_options[$menu_title][$nid]);
      }
    }
  }

  $final_options = array();

  // If the field is not marked required, there'll be an option for - None -
  // and it's keyed to the empty string.
  if (isset($old_options[''])) {
    $final_options[''] = $old_options[''];
    unset($old_options['']);
  }

  $final_options += $new_options;

  $final_options['Others'] = $old_options;

  return $final_options;
}

/**
 * Generates FAPI options for the allowed menus' node links.
 *
 * @return
 *   A FAPI options array with all node links on the allowed menus (NB this has
 *   not been filtered in any other way).
 */
function banners_generate_page_options() {

  $menus = array('primary-links', 'menu-top-menu');
  $options = array();

  foreach ($menus as $menu_name) {
    $tree = menu_tree_all_data($menu_name);
    $menu = menu_load($menu_name);
    $options[$menu['title']] = _banners_process_tree($tree);
  }

  return $options;
}

/**
 * Recursive function to generate the options array, keyed by nid.
 */
function _banners_process_tree($tree, $depth = 0) {

  $options = array();

  foreach ($tree as $item) {
    $matches = array();
    if (preg_match('~^node/(\d+)$~', $item['link']['link_path'], $matches)) {
      // Link points to a node
      $nid = $matches[1];
      $options[$nid] = str_repeat('--', $depth) . ' ' . $item['link']['title'];
      if ($item['below']) {
        $options += _banners_process_tree($item['below'], $depth + 1);
      }
    }
  }

  return $options;
}


If all else fails, you could try using the Bbcode module.  The advantage here is that you can turn Email address encoding on, so your address isn't spammed.  (If you want this feature without the Bbcode module, you could use the SpamSpan module.)

Sorry, I can't tell you how to fix your issue... but this may possibly be a workaround if all else fails?


How can i filter taxonomy by another taxonomy term with views (term)?

Finally i found a solution with references module :

https://drupal.org/project/references

If some of you want to use custom taxonomy, may be it's better to use nodes with "node reference" than taxonomy...


Migrate module showing 0 processed on production server

I guess I didn't take as much time to look into this and then had a light bulb moment.  Migrate actually creates a table in the database of the one it is importing from (probably skimmed over this in the docs).  So I need to do a sync of those tables from my local to production.


How to set Class for a particular image style?

In Drupal 8 you can do this with hook_preprocess_image in your themes mytheme.theme file.

/**
 * Implements hook_preprocess_image().
 */
function mytheme_preprocess_image(&$variables) {
  if ($variables['style_name'] == 'my_custom_image_style') {
    $variables['attributes']['class'][] = 'my_css_class';
  }
}


Add a class to all title text fields in all content add forms

The content title is a property rather than a field, so overriding theme_field() isn't the way to do this.

Instead you might want to use a hook_form_FORM_ID_alter() (which can also be used in your theme's template.php file):

function ccom_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#attributes']['class'][] = 'span6';
}


Function hook_entity_presave acts on an entity before it is about to be created or updated

Code:

  function hook_entity_presave($entity, $type) {
    $entity->changed = REQUEST_TIME;
  }

source :  Drupal API


What drupal function do I use to rename files when saving nodes programatically?

Drupal uses the file_create_filename() function to do that, you can call it like this:

$basename = drupal_basename($local_path);
$directory = drupal_dirname($local_path);
$local_path = file_create_filename($basename, $directory);

$file = new stdClass();
$file->filename = drupal_basename($local_path);
$file->filepath = $local_path;
// etc...


Block showing users of a specific role is only showing up for the administrator

My guess is that there is an access check somewhere that is failing. When logged in as user 1, it's impossible for a standard access check to fail, so this would be why you're seeing the block.

To solve this, try granting ALL permissions to RoleX (make sure you do not do this on a live site) and see if the block appears when you log in as the test user who has RoleX. If the block starts showing up, start disabling permissions a few at a time until you find which one is causing the issue.


How to update block with step links based on AJAXified multipage entity form state?

This was implemented by patching/extending FGAM module and the following jQuery code:

/**
 * @file
 * Connect jumplist to their corresponding multipage panes.
 */
(function ($) {
  Drupal.behaviors.multipageJumplistFix = {
    step: 1,
    maxStep: 1,
    attach: function(context) {

      // Wrapper changes its id but it's id must be static!
      $('div[id^="foo-entityform-edit-form"][id$="form-ajax-wrapper"]').attr('id', 'foo-entityform-edit-form-form-ajax-wrapper');

      this.step = $('.multipage_step_change.active').attr('step');
      this.numSteps = $('.multipage-jumplist > li').length;
      this.maxStep = Math.max (this.maxStep, this.step);

      this.updateActive ();

    },
    updateActive: function () {
      $('.multipage-jumplist a').removeClass('active');
      $('.multipage-jumplist a[step=' + this.step + ']').addClass ('active');

      for (var i = 1; i <= this.numSteps; ++i) {
        if (i > this.maxStep + 1)
          $('.multipage-jumplist a[step=' + i + ']').addClass ('disabled');
        else
          $('.multipage-jumplist a[step=' + i + ']').removeClass ('disabled');
      }
    }
  };

  $(function () {
    $('.multipage-jumplist').html($('.multipage-jumplist').html());

    $('.multipage-jumplist a').each(function (index, el, e) {
      el.step = index + 1;
      $(this).click (function (e) {
        console.log (this.step);
        if (!$(this).hasClass('disabled')) {
          $('.multipage_step_change[step=' + this.step + ']').trigger('mousedown');
          return false;
        }
      });
    });

    Drupal.behaviors.multipageJumplistFix.attach();
  });
})(jQuery);

which is loaded from the theme and then few enhancements in template.php:

/**
 * Implements hook_form_alter().
 */
function theme_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, 'entityform_edit_form') !== FALSE) {
    drupal_add_js(drupal_get_path('theme', 'foo') .'/js/eforms.js');

    $step = empty($form_state['storage']['field_group_ajaxified_multipage_step']) ? 1 : $form_state['storage']['field_group_ajaxified_multipage_step'];
    $curr_step = &$_SESSION[end((arg())) . '-step'];
    $curr_step = max($step, $curr_step);

    unset($form['actions']['prev']);
    unset($form['actions']['next']);

    if (!empty($form['#multipage_jumplist_instances'])) {
      $num_steps = count($form['#multipage_jumplist_instances'][0]['panes']);

      for ($i = 1; $i <= $num_steps; ++$i) {
        $active = $step == $i;
        $is_prev = $i == ($step - 1);
        $is_next = $i == ($step + 1);
        $form['actions'][$is_prev ? 'prev' : ($is_next ? 'next' : ('step' . $i))] = array(
          '#type' => 'submit',
          '#value' => $is_next ? t('Continue') : ($is_prev ? t('Previous') : ('Step' . $i)),
          '#id' => 'step' . $i,
          '#attributes' => array('step' => $i, 'style' => (($is_prev || $is_next) ? '' : 'display: none'), 'class' => array('multipage_step_change', ($active ? 'active' : ''))),
          '#submit' => array('theme_multipage_step_change_submit'),
          '#ajax' => array(
            'wrapper' => 'foo-entityform-edit-form-form-ajax-wrapper',
            'callback' => '_field_group_ajaxified_multipage_form_callback',
          ),
        );
        if ($i < $step) {
          // We don't want validation when going back.
          $form['actions']['step' . $i]['#limit_validation_errors'] = array();
        }
      }
    }

  }
}

function theme_multipage_step_change_submit(&$form, &$form_state) {
  $step = substr($form_state['triggering_element']['#id'], 4);

  $form_state['triggering_element']['#array_parents'] = array('actions', 'step' . $step);
  $form_state['triggering_element']['#parents']       = array('actions', 'step' . $step);

  _field_group_ajaxified_multipage_form_submit($form, $form_state);

  $form_state['rebuild'] = TRUE;
}

This can be also extended by theme overrides for: theme_multipage_jumplist() and theme_multipage_jumplist_item().

Hope that helps.


Using AJAX to access the content of a view

First, enable Ajax on the view. On window load, bind the click event to a custom function, let's call it getInfo(arg) and pass the arguments you need (nid, tid, or whatever you need)

Then, on getInfo() add the following code.

function getInfo(args) {
  $.ajax({
    url: '/views/ajax',
    type: 'post',
    data: {
      view_name: 'your_view_name',
      view_display_id: 'block_1', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
      if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#myDiv').html(viewHtml);
        Drupal.attachBehaviors(); //check if you need this.
      }
    }
  });
}

You pass the arguments in the data array, and you get the #myDiv replaced with the view content.


Drupal 8 Display True/False instead 0/1 on checkbox value in ConfigFormBase

In drupal8, you can easily handle this from "Manage Display" of your content type.

  Go to /admin/structure/types/manage/article/display
  Select your "view_mode". Ex- Default.

  Go to the boolean field and click on its settings icon which is placed at atmost right side of the field.
  Change the output format to "True/False".

Hope, this works for you.


No, there isn't any way to do that now (in 6 or 7). Simply put, that's not how Drupal was designed.

Inspect tables created by Drupal. See any increment here? No. It was design decision not to perform any id assignment in database, but leave it all to code. If you go against that decision, you need to implement your own solutions, using more basic db_select, if, db_update and db_insert. Or prepare your own query using db_query.


Feed import of CSV file only in imports the title and nothing else. It also has paragraph fields

I checked the csv file in an editor it found the culprit was because I deleted a bunch of records using excel and it left alot of empty commas everywhere. You have to go into the csv file and edit it manually.

Also it wasn't importing because the values need to be in quotes.


How to run drush make on remote using relative path?

For workaround, the following command should work:

$ drush @remote.test make --no-core $(drush @remote.test dd)/profiles/foo/contrib.make

Command drush dd will return the webroot path and pass it to outer command.


Is there a way to print out a list of all possible template files for a page?

I suggest review Theme Developer module http://drupal.org/project/devel_themer, it will help to find possible templates that can help to modify (theming) specific parts of your site.

in this resource http://drupal.org/node/209561 you will find how to use the module.


extra 'field_' prepended to fieldnames in views $rows (Drupal 7)

The drupal field api enters fields in the database with the field_ prefix (to avoid conflicts with other existing tables). If you use field in your name as well, it will become field_field_... in the database.

And since views loads the fields directly from the database, the prefix is there as well.


How to pass parameters by reference to a batch?

Alfred is right. You can achieve that by using the $context parameter.

public static function someFunction($a, $b, &$context) {
  // Store data in $context['results'] entry.
  // my_var will keep that value.
  $context['results']['my_var'] = 20;
}


node translations and too many menu items

No it's not possible because each menu link can point to a specific (one) node. When using node translation the different translations of a node are other nodes.


How to Display a Single Image Gallery per Album in Content Teaser?

Okay Drupalizer!  You don't need any special coding or modules to fix this.  I figured it out.  So basically, I just needed to create a NEW view of the Album Image Gallery Teaser with the same settings except for the Pager which I made to be "Display a specified number of items | 1 item".

Then I use this view as the Content Teaser for the Category Level and the Content-type 'ALBUM" I set the teaser display to be this EVA view.

See attached screenshot ...


I ended up using a slightly different approach. Just in case somebody else is interested in this I'm posting my final solution here.

PROBLEM

"Estimate" a ship date based on the turnaround times of all the products in cart whenever a product is added or removed from the cart and at checkout (just in case the customer decides to check out days after adding the products).

Additional modules and fields:

Using the interval field module I added a "Turnaround Time" field to the product variation type.
I also added a date field to the order entity - "field-due-date".

RULES

I created 3 items under rules.

Reaction Rule: Set the estimated shipping date

+ Events
    + After adding a product to the cart
    + After removing a product from the cart
    + Completing the checkout process
+ Actions
    + rule set: Set the estimated shipping date
        // these settings ensure that you run through each and every line item, instead of just the current item; spend a long time doing that - over and over. :(
        + Line Item
          Data Selector: commerce-order:commerce-line-items:0
        + Order
          Data Selector: commerce-order
        + Commerce Product
          Data Selector: commerce-product

Ruleset: Get Line Item Turnaround Value
rules_get_line_item_turnaround_value
This rule gets the integer value of each line-item's turnaround time (in days in my case) and writes it to "line-item-turnaround-time" variable which is passed along to the next ruleset. I could probably have used a regular Rule instead of a Rule Set here.

Date Type
    Commerce Line Item, Line Item, line_item, Parameter
    Commerce Order, Order, order, Parameter
    Commerce Product, Product, product, Parameter
    Integer, Line Item Turnaround Time, line_item_turnaround_time, provided

+ Rule: Get the Line Item Turnaround Time as a Number
  Provides variables: Line Item Turnaround (line_item_turnaround)
    + Conditions
        + Entity has field
          Parameter: Entity: [line-item], Field: commerce_product
          //exposes the line item to the rule
        + Entity has field
          Parameter: Entity: [line-item:commerce-product], Field: field_turnaround_time
          //exposes the line item's product variation to the rule
    + Elements
        + Add a variable
          Parameter: Type: Integer, Value: [line-item:commerce-product:field-turnaround-time:interval]
          Provides variables: Line Item Turnaround (line_item_turnaround)
          //pulls the turnaround time as an integer
        + Set a data value
          Parameter: Data: [line_item_turnaround_time], Value: [line-item-turnaround]
          //write's the turnaround time to the "line_item_turnaround_time" variable

Ruleset: Set the estimated shipping date
rules_set_the_estimated_shipping_date
This rule pulls the turnaround time from a list of the line items in the current order, compares them and uses the largest value to adjust the estimated delivery date. Again, I could probably have used a regular Rule here instead of a Rule Set.

Date Type
    Commerce Line Item, Line Item, line_item, Parameter
    Commerce Order, Order, order, Parameter
    Commerce Product, Product, product, Parameter

+ Rule: Calculate the estimated shipping date
  Provides variables: Order Turnaround Time (order_turnaround_time), Conversion result (conversion_result), New Estimated Shipping Date (new_estimated_shipping_date)
    + Conditions
        + Entity has field
          Parameter: Entity: [line-item], Field: commerce_product
          //exposes the line item to the rule
        + Entity has field
          Parameter: Entity: [line-item:commerce-product], Field: field_turnaround_time
          //exposes the line item's product variation to the rule
        + Entity has field
          Parameter: Entity: [order], Field: field_due_date
          //exposes the current order to the rule
    + Elements
        + Set a data value
          Parameter: Data: [order:field-due-date], Value: [site:current-date]
          //set the order's due date to the site's current date. This does two things: 1. ensures that the shipping date is based on the exact time the order is completed, as opposed to a previously calculated value, or the order creation date. 2. rules fail if no value is set
        + Add a variable
          Parameter: Type: Decimal number, Value: 0
          Provides variables: Order Turnaround Time (order_turnaround_time)
          //set the base turnaround time to 0 so we have something to compare our line item turnaround times to
        + Loop
          Parameter: List: [order:commerce-line-items]
          List item: List of Line Items (list_of_line_items)
          //loop through a list of the current order's line items
            + rule set: Get Line Item Turnaround Value
              Parameter: Line Item: [list-of-line-items], Order: [list-of-line-items:order], Product Display: [line-item:commerce-product]
              Provides variables: Line Item Turnaround Time (line_item_turnaround_time)
              //runs the "Get Line Item Turnaround Value" and pulls the "line_item_turnaround_time" for the current loop line item
            + Calculate a value
              Parameter: Input value 1: [line-item-turnaround-time], Operator: max, Input value 2: [order-turnaround-time]
              Provides variables: Calculation result (result)
              //check to see if the current loop line item's turnaround time is larger than the value of the order-turnaround-time
            + Set a data value
              Parameter: Data: [order-turnaround-time], Value: [result]
              //if the current loop line item's turnaround time is larger than the value of the order-turnaround-time write it as the new "order-turnaround-time" otherwise keep the old value
        + Convert data type
          Parameter: Target type: Integer, Value to convert: [order-turnaround-time], Rounding behavior: Always up (9.5 -> 10)
          Provides variables: Conversion result (conversion_result)
          //converts the order-turnaround-time to an integer, just in case it's not, so we can apply it as an interval
        + Apply an interval to a date
          Parameter: Interval number: [conversion-result], Interval period: Days, Date: now
          Provides variables: New Estimated Shipping Date (new_estimated_shipping_date)
          //add the new "order-turnaround-time" to the "site:current-date[field-due-date]" to calculate the estimated shipping date
        + Set a data value
          Parameter: Data: [order:field-due-date], Value: [new-estimated-shipping-date]
          //write the new estimated shipping date to the field-due-date field on the order

Hope that saves someone a couple of hours.


How to disable one specific translation page?

Since translations in D7 are new nodes, you can simply Unpublish the English node, while keeping the Danish one Published.


How do you change which content type a field is attached to (which one owns it?)

Well, this isn't the perfect solution, but may be a way to find it.

Change your content type to what you want to have it and export the feature. Them take a difftool (winmerge) and look at the diffrences between the old version of your features module and the new  one.

There's a good chance that you find out what to change.

Don't forget to take a DB Backup before you start.


How to configure the fields in the report created by the Content Audit module?

Have a look at the article about "Content inventory and content audit with Views". Here is an intro of it:

  Do you know the exact state of the content in your large Drupal site? Thinking of revamping, redesigning or upgrading your site? If you answered 'no!' to the first question or 'yes!' to the second question, it's time for content audit.

  In this blog post, I cover the what, why, who, when, where and how's of content audits. I've conducted a few small content audits, and I'm leading a much bigger one, on Drupal.org.

It's a pretty old article already (from 2011), and still contains Views2 screenprints. But it includes a lot of interesting details that should help to answer your question.

What is also interesting in this article are the recommendations to actually "evaluate your content", via a combination of these options (quote from the same article):

  Option A (Export): export this view to CSV and manage your content audit in spreadsheet software or Google Docs. The Views Bonus Pack module will let you export the view as a CVS file.
  Pro: Less data to store in your database
  Con: Your inventory is almost immediately outdated; will be extra time-consuming to update on a regular basis
  Option B (Flags): 'Flag' content that needs to be updated using the Flag module. You can adjust the flag settings so that only certain roles can use this flag, and then set which content types can be flagged (or set it as global). You can then add the Flag to the content audit view, and/or create a separate view of nodes that have been flagged. However, marking something as "needs work" doesn't provide enough detail, so you'll want to record notes somehow (see Option C). You can create additional flags for each type of action to be taken, e.g. "needs style review" or "redundant", without the casual visitor even knowing, while keeping your content team in the loop.
  Option C: Keep 'audit notes' field on each content type in Drupal site database with the Annotate module or by creating a field on the nodes.
  Option D: Use the Content Audit feature module, which constructs the View, and will soon have configured Annotation (this hasn't been built yet).
  Option E: Create another node type called Audit notes, and once filled in, then nodereference the node it covers. Then, it's easy to build a view of the Audit notes (I'm also wondering whether this could be a custom bit of code to automagically do this, then include in the Content Audit module).

Some more module suggestions to further enhance your content auditing experience (which you may want to use as complements to configuration facilities available in the Content Audit module):

Consider using the Flag module (as in that "Option B" above). And then possibly combine anything that might get flagged with the Rules module to trigger things like:

Unpublish and/or delete this content.
Add it to some type of review (workflow) process, like content accuracy, spell checking, etc.
Notify authors via eMails, like: "Please review this content, and use any of the available flags to indicate what your recommended action for it should be".

Auditors often like charts to visualize what's being audited (a picture is worth more then 1000 words ...). By simply installing (and enabling) the Charts module, and without any additional configuration, you get some Out-of-the-box examples that come with this module (in the format of some charts and/or a Views table display). They contain data about the total number of nodes for each of the available content types. And these data are limited to the nodes for which the user has permission to view them. Visit the Charts demo site for an online preview of of these out-of-the-box examples.


Is there a way to resolve a list of references in a view without cloning entire rows of data?

Depending on how you want to use the results of the query, you could use a GROUPBY option within the Views config.
Find the GROUPING options by clicking on the word "Settings" under FORMAT. The link for "Settings" appears to the right of the pipe symbol which separates the chosen format from the "Settings" link.
Once you do this, it should remove the duplicates.


Assigning revision owner when moderating backwards with Workbench

Old question, but in response to the comment, this is the solution that I deployed.  As far as I know, it has been working well:

/**
 * Implements hook_node_update().
 */
function mymodule_node_update($node) {
  db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('nid', $node->nid)
    ->condition('vid', $node->vid)
    ->execute();
}

/**
 * Implements hook_workbench_moderation_transition().
 */
function mymodule_workbench_moderation_transition($node, $previous_state, $new_state) {
  if (isset($node->nid) && isset($node->vid) && isset($node->uid)) {
    mymodule_node_update($node);
  }
}

This covers the case where a user updates a node via the edit form, and when a user pushes a node through moderation via the workflow forms.


"Call to a member function label() on null", while it's defined

You have to check if you are in a node hook:

if ($hook != 'node') {
  return;
}

In other hooks you don't have a node object and the function label() is called on null.

Though you might want to check the machine name of the node type, because the display name can change when you have multiple languages:

$node->getType()


Use drush upwd to reset your password

drush upwd --password="givememypasswordback" "admin"

If you don't have drush installed do it via MySQL. Here is a related article.


How to reuses page--front.html.twig for multiple pages

Implement hook_theme_suggestions_page_alter(), and you can suggest the template file used for those land pages.

I assume you are doing it from a theme; if you are doing it from a module, you can implement either hook_theme_suggestions_page_alter(array &$suggestions, array $variables) like for themes or hook_theme_suggestions_page(array $variables).

function mytheme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($your_condition) {
    $suggestions[] = 'page__front';
  }
}

The code you write for $your_condition depends from how you check which pages are your land pages. The following are some useful snippets you could need.

To get the internal path for the current page

$internal_path = Url::fromRoute('<current>')->getInternalPath();

Alternatively, the current path can be obtained with \Drupal::service('path.current')->getPath() (Drupal core uses both of those)
To get the node being viewed

if (!empty($variables['elements']['#node'])) {
  $node = $variables['elements']['#node'];
  // Get the content type.
  // $bundle = $node->bundle();
}


How to add a 3rd party library and call it using Libraries

The Libraries project page has good documentation on how to use version 2.x API. Essentially, there are 2 components to it.

You're defining an implementation of hook_libraries_info(), that returns an array that defines the library's machine name, resources to load, & a means to validate the library version (either an version arguments element that defines the array passed to libraries_get_version() or a custom version callback function).

/**
 * Implements hook_libraries_info().
 *
 */
function MYMODULE_libraries_info() {

  // Define 'simple' as the machine name of library
  // which will be stored in sites/all/libraries/simple
  $libraries['simple'] = array(

    // This gets passed to the $options array in libraries_get_version()
    'version arguments' => array(
      'file' => 'simple.js',
      'pattern' => '/Version (\d+)/',
      'lines' => 5,
    ),

    // Alternatively, MYMODULE_version_callback could be defined.
    // this function returns TRUE/FALSE if it finds a valid version of the library
    //'version callback' => 'MYMODULE_version_callback',

    // Defines the PHP,JS,CSS files to load for the library
    'files' => array(
      'js' => array('simple.js'), //this can be a path to the file location like array('lib/simple.js')
    ),
  );

  return $libraries;
}

The 2nd component is to load the library using libraries_load() wherever you need in your module.

//Load the 'simple' library
libraries_load('simple');

See the linked documentation for more information.


How can I auto-rotate an image on file upload in a custom form?

you can try the next code. You will have to create a new image style which rotates the image and then use it in prerendering on image preview.
$form['product_img'] = [
  '#type' => 'managed_file',
  '#description' => 'Upload a PNG or JPG image of the product.',
  '#multiple' => FALSE,
  '#required' => TRUE,
  '#upload_location' => 'public://',
  '#upload_validators' => [
    'file_validate_is_img' => [],
    'file_validate_extensions' => ['png jpg jpeg']
  ],
  '#process' => array('custom_managed_file_element_process'),
];

// Process callback

function custom_managed_file_element_process($element, &$form_state, $form) {

  $element = file_managed_file_process($element, $form_state, $form);

  $element['#pre_render'][] = 'custom_managed_file_element_preview';

  return $element;
}

function custom_managed_file_element_preview(array $element) {

  if (empty($element['#file'])) {
    hide($element['remove_button']);
  }
  else {

    $file = $element['#file'];
    hide($element['upload']);
    hide($element['upload_button']);

      $info = image_get_info($file->uri);
      $variables = [
        'alt' => $file->filename,
        'path' => $file->uri,
        'style_name' => 'thumbnail', // change your style name here
        'attributes' => [
          'class' => ['upload-preview'],
        ],
      ];

      if (is_array($info)) {
        $variables += $info;
      }

      $element['preview'] = [
        '#type' => 'markup',
        '#weight' => -150,
        '#markup' => theme('image_style', $variables)
      ];

  }

  return $element;

}


CSV migration always returns "id is defined as a source ID but has no value"

I already had the same error you've got; in fact it's a mistake :
Please double check that the delimiter set in the yml file is the same as in your source file (edit it with notepad++ to be sure). Sometimes Excel change delimiter when reopening csv file before resave it without settings file format.

Also, note the column_names key is not mandatory, as the plugin will automagically extract column from your file (see migrate_source_csv\src\Plugin\migrate\source\CSV.php line 110 ... 123). Here you can also print the $column_names array to check if it contains same number of items as your file columns.

BR


Set default "Quantity" dropdown select in product. Commerce Kickstart

I know its already a year ago, but if someone bump in this question here's one of the solution, I don't know if there's a module that already existing changing the widget type of quantity in add to cart form but you can achieve this using
hook_form_commerce_cart_add_to_cart_form_alter like this

Example:

function example_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  // Change widget type of quantity to select list
  $form['quantity'] = array(
    '#title' => t('Quantity'),
    '#type' => 'select',
    '#datatype' => 'integer', // <-- I added this one to fix Notice: Undefined index: #datatype in commerce_cart_add_to_cart_form_validate() when you click add to cart button
    '#options' => array(
      1 => '1',
      2 => '2',
      3 => '3',
      4 => '4',
      5 => '5'
    )
  );
}


How do I make the file description field required?

Code snippet for making a file's description field required:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_MYFIELD' && $context['instance']['widget']['type'] == 'file_generic') {
    $element_children = element_children($element, TRUE);
    foreach($element_children as $key) {
      $element[$key]['#process'][] = 'MYMODULE_file_field_description_required';
    }
  }
}

/**
 * Require description to be set.
 */
function MYMODULE_file_field_description_required($element, &$form_state, $form) {
  $element['description']['#required'] = TRUE;
  return $element;
}


After applying this Patch, these errors are reduced however not fully rectified. This patch prevents empty delete queries being run and thus reducing the load on the domain_source table.


Here is how you would create an auto save after selecting an upload file(s) in D8.

upload_autosave.libraries.yml

auto:
  version: 1.0
  js:
    js/auto.js: {}
  dependencies:
      - core/jquery

upload_autosave.module

/**
 * Implements hook_form_alter().
 * Adds JS file to all forms
 */
function upload_autosave_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['#attached']['library'][] = 'upload_autosave/auto';
}

/js/auto.js

(function ($) {
  Drupal.behaviors.upload_autosave = {
    attach: function (context, settings) {
    if ($('.image-widget-data').length || $('.field--type-file').length){
      $('.js-hide.button.js-form-submit.form-submit').remove();
      $('form', context).on('change', 'input.form-file', function() {
        $('#edit-actions .button.js-form-submit.form-submit')[0].click();
        $(".details-wrapper").html("<img src='/modules/upload_autosave/images/loading.gif'>");
        $('#edit-actions').fadeOut(1000);
      });
     }
    }
  };
})(jQuery);


How can I use the Add Product form as content in the main menu?

Admin > Structure > Menus > Main Menu > Add link

Title: Add product
Path: admin/commerce/products/add/product

Keep in mind, that is for admins to create backend products for the inventory, not front end product displays.

It will also only be generated for admins with the relevant permissions.

To add a link for creating a frontend product display, the path would be something like

node/add/product-display


Redirect to the registration page of the main domain

Follow below steps to solve your issue.

Install rules module in subsite.
Create a rule with condition as page being viewed is user/register
Add an action redirect to URL with url as main site user/register path

Other way to do is using custom module in sub site

Use hook_init in custom module

   <?php
      function yourmodule_init() {
         if (arg(0) == "user" && arg(1) == "register") {
           drupal_goto("http://www.abc.com/user/register");
         }
      }
   ?>


How to programmatically get the field cardinality

Thanks for the comments, I figured out a way to get the number(cardinality). Hope it helps someone.

(array) $user_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user');

foreach ($user_fields as $user_field_name => $user_field_definition) {
    (array) $cardinality = $user_field_definition->get('fieldStorage')->get('cardinality');
}


DrupalDatabaseCache is causing performance issues

If you concerned with performance then you want to maximise caching, not minimise it!

Caching is used to store data once expensive (time consuming) processes have been used to prepare it. Then future page requests simply return the cached data and don't have to do the slow processing again.

By default Drupal stores it's cache in the database but as you've spotted this isn't always that fast. Using a module like APC or memcache allows you to store the cache in the servers memory, as opposed to having to write it to the DB so this is much faster.

To make the most of Druapl's caching functions I would also recommend taking a read of lullabot's excellent article: A Beginner's Guide to Caching Data in Drupal 7


That is because of language switcher enabled.  Go the particular content type page, edit and in publishing options CHECK the check box Hide content translation links.


How to render entity referenced nodes field inside node.tpl.php?

If there is no compelling reason to render the fields from within the template, you could simply:

choose a certain view mode for your author content type, say: Token, and make it show only those fields you want to be visible in the book node;
set the display of the field referencing the author node from the book node to "Rendered entity" / "Rendered as Token".


How do I delete all the relations on my site?

There are many ways to delete relations on a site. Relations are Entities in Drupal.

The Delete All module can help with this process.
The Drush Entity command set has a delete function which takes a content type I believe.
With care you could by hand TRUNCATE the relation table, and destroy and drupal Fields that use relations. (I've done this on a few sites).


How to do file downloading in a controller function?

Never send the response with $response->send(). Instead return the response:

use Symfony\Component\HttpFoundation\Response;

public function myController() {
    $response = new Response();
    // prepare $response
    return $response;
  }

BTW, this is a standard Symfony Controller. The fact that you also can return the main content in a render array is because Drupal has added an event subscriber, which converts the main content to a response with the themed html page.

This works for all responses, in your case for example for a binary file response:

Drupal\system\FileDownloadController::download():

  public function download(Request $request, $scheme = 'private') {
    $target = $request->query->get('file');
    // Merge remaining path arguments into relative file path.
    $uri = $scheme . '://' . $target;

    if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
      // Let other modules provide headers and controls access to the file.
      $headers = $this->moduleHandler()->invokeAll('file_download', [$uri]);

      foreach ($headers as $result) {
        if ($result == -1) {
          throw new AccessDeniedHttpException();
        }
      }

      if (count($headers)) {
        // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
        // sets response as not cacheable if the Cache-Control header is not
        // already modified. We pass in FALSE for non-private schemes for the
        // $public parameter to make sure we don't change the headers.
        return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
      }

      throw new AccessDeniedHttpException();
    }

    throw new NotFoundHttpException();
  }


Change drupal language from neutral to en

You should use Language Assign to easily update all the languages of your nodes.


How to make sure my behavior is triggered before AJAX?

I got it working now. The way to do it was:

Get all elements that are in "exclusive" groups using classes, .each over them
For each element, change beforeSubmit using $(this).attr('id') as index for ajax table
Because I was not able to get element to point to a specific element (it always pointed to entire form), I used helper variable at the beginning of .each loop.

Resulting code is like this:

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

      $('select.exclusive', context).each(function(){
        var triggering_element = $(this);
        Drupal.ajax[$(this).attr('id')].options.beforeSubmit = function (form_values, element, options) {
          // Make all not selected
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option").attr('selected', false);
          // select "all"
          $("[exclusivity_group='"+triggering_element.attr('exclusivity_group')+"']").not(triggering_element).find("option[value='all']").attr('selected', true);

        };
      });
    }
  };
})(jQuery);


Change output of a field with PHP field?

it looks like you have the logic a little backwards:

Value Code:

if($row->field_fruit == 'lemon') return 'citrus';

Output Code:

<?php print $value; ?>


How to add Variables in Drupal (and how to visualize them)?

Are you aware of the devel module? It is typically used in dev versions of a site only, and is not recommended for production status sites.

After you enable that module, you'll get many features, such as dprint_r(), dpm() (I like the last one for debugging). For more details, refer to https://www.drupal.org/node/174575 ...


Nevermind I read on attributes: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

The attribute I was referencing 'highlighted_attributes' was blank. I just added a simpler solution, by referecing to the example of the API:

{% set classes = [ 'red', 'green', 'blue' ] %}

<div{{ attributes.addClass(classes) }}></div>


Authentication providers: no token_bearer

I think your yml syntax is wrong (or out-dated) look at rest.resource.entity.node.yml for a correct example.
Or use the "REST UI" module to specify your resources.

It should look more like:

configuration:
  methods:
    - GET
    - POST
    - PATCH
    - DELETE
  formats:
    - hal_json
  authentication:
    - basic_auth


How to programmatically add custom markup to every displayed user name

Seems hook_user_format_name_alter() is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.

The following won't work for Views for example. It will print just a string.

use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Implements hook_user_format_name_alter().
 */
function MYMODULE_user_format_name_alter(&$name, $account) {

  $name = new TranslatableMarkup('@name Foo Bar', ['@name' => $name]);
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {

    $name = $variables['title']['#markup']->__toString();
    $variables['title'] = new TranslatableMarkup('@name Foo Bar', ['@name' => $name]);
  }
}

So, what I'd recommend now is, you maybe take the *_preprocess_page_title hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.


feeds not update exist node and only add them

The problem is here NOT UNIQUE field set.after set a field as a unique field every time the nodes will update(replaced).
To  set a field as unique click a button below not set as unique , check unique checkbox and update then it will set as unique.


Dynamic local tasks to the same route with slug

The array key is not the route name, it's the machine name of the local task. It's pretty common to use the same string but that's in no way a requirement.

Just use a different array key and this should work.


How to restrict field formatter to selected fields?

Use default formatter in your field implemention

$field = array(
  'field_name' => 'field_csob_srcode',
  'type' => 'text',
  'settings' => array(
  'max_length' => 4,
  ),
  'default_formater' => 'csob_webpay_description',
);

it should works.