How to not print a Menu Block if a Menu Block exists

I had the same issue and resolved it by removing one of the blocks by calling  template_preprocess_page() in a custom module or in your theme's template.php. What I do is check to see if both blocks exist on the page, and if so, call unset() on the block I want to remove:

function mymodule_preprocess_page(&$variables) {
//Remove secondary menu block if tertiary menu block is on the page
if(!empty($variables['page']['sidebar_first']['menu_block_tertiary']) && !empty($variables['page']['sidebar_first']['menu_block_secondary'])) {
    unset($variables['page']['sidebar_first']['menu_block_secondary']);
}

The indexes in your $variables array will most likely be different. On my site, 'sidebar_first' is the region in my theme where my menu blocks (menu_block_primary and menu_block_secondary) are placed. If you're not sure what your variables are, you can use a call to dpm($variables) to find them (Make sure you you have the devel module enabled) like so:

function mymodule_preprocess_page(&$variables) {
  dpm($variables);
}


Remove the resizing of images that are bigger then the max resolution. (reject instead)

Set min/max on the FIELD ITSELF, under content types. Not on the image style.


In Drupal 8 (at least), there is a "Clean up" tab in the main configuration screen of the module (/admin/config/workflow/workflow), where you can delete inactive states.

In my case, I suddenly stopped seeing the "Actions" buttons, so the only thing I could do was activate/disactivate the states.

That may solve someone's problem...It solved mine


I have found the solution. Instead of using EntityType::setHandlerClass(), use EntityType::setFormClass().


How should I remove a region and zone in an Omega 3 sub theme?

Just remove the region and zone definition from the theme info file.


Drush doesn't detect drupal installation under sites sub-directory

You need to add an alias conf file named YOUR_SITE_NAME.aliases.drushrc.php in sites\all folder with that code.

// The site in sites/YOUR_SITE_NAME/
$aliases['YOUR_SITE_NAME.local'] = array(
  'uri' => 'YOUR_SITE_NAME_URI',
  'root' => '/path/to/drupal_root_folder',
  'path-aliases' => array(
    '%dump-dir' => '/tmp'
  ),
);

Then clear cache : drush cache-clear drush.

Test your alias : @YOUR_SITE_NAME.local status.

To run a command, for the sake of example : @YOUR_SITE_NAME.local mb MODULE_NAME hook1 hook2 --write

UPDATE : in order to create automatically Drush site aliases for many sites, place this code in your aliases.drushrc.php file.  Drush will look for aliases.drushrc.php in the ".drush" folder in your home directory (see this post to get sure where to put this file).

$aliases = array();
$drupal = '/var/www/drupal';

// Automatic alias for each Drupal site
$site = new DirectoryIterator($drupal . '/sites');
while ($site->valid()) {
  // Look for directories containing a 'settings.php' file
  if ($site->isDir() && !$site->isDot() && !$site->isLink()) {
    if (file_exists($site->getPathname() . '/settings.php')) {
      // Add site alias
      $basename = $site->getBasename();
      $aliases[$basename] = array(
        'uri' => $basename,
        'root' => $drupal,
      );
    }
  }
  $site->next();
}

// Get all site aliases
$all = array();
foreach ($aliases as $name => $definition) {
  $all[] = '@' . $name;
}

// 'All' alias group
$aliases['all'] = array(
  'site-list' => $all,
);

You can also read this : create your own drush aliases. You could even think about managing synchronization between remote and local systems (source).

EDIT : as per ericx comment, consider adding bash-completion. Drush comes with a bash-completion file, drush.completion.sh, which offer alias completions.


tpl.php files are called templates in the Drupal system. They render the HTML that you see on any given page, may it be a block/view/panel or anything.

Theme Developer is a popular module used to pinpoint the template file that's in play. I suggest you try it to better understand how template system works.
To understand more on customizing templates and naming conventions read through this guide on working with template suggestions.

If its a view you want to modify- Use views GUI to the maximum extent(changing the sort order, re-arranging fields etc.). Still not getting what you want ? Override view templates for maximum control.

(Helpful Articles on overriding view templates)

http://www.wdtutorials.com/drupal/views/how-to-create-custom-template-view-drupal-tutorial-article

https://www.interworks.com/blog/carmstrong/2013/02/27/quick-tutorial-overriding-drupal-views-using-templates


How to use Simple hierarchical select on a view starting at second level taxonomy?

I made a patch to allow you to choose the parent taxonomy at a level lower than the root. I will post a link to it soon .   If anyone wants to ask me about it in the meantime please write to me.


How to add margin between columns with Drupal Bootstrap View Grid

You can use only CSS for this, look for the columns classes and then add it in a CSS file that is loaded on your page.


Views Exposed Filters: how to get functionality shown in this image?

You would need to configure the Select2 or Chosen JQuery component to do this.

Create the list of object with count and apply the one of the above library.

For Drupal use Select2 module


try this:

function read_more_news_menu() {
    $items = array();
    $items['admin/settings/readmorenews'] = array(
        'title' => 'Read More News Module Settings',
        'description' => 'Set read more news outgoing link here',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('read_more_news_admin_form'),
        'access arguments' => array('administer readmorenews settings'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
function read_more_news_admin_form($form, &$form_state) {
    $form = array();
    $form['link_container'] = array(
        '#type' => 'container',
        '#attributes' => array('class' => array('some-class')),
        '#tree' => TRUE,
    );
    $form['link_container']['link'] = array(
        '#type' => 'link_field',
        '#field_name' => 'link_field',
        '#language' => 'und',
        '#field_parents' => array(),
        '#delta' => 0,
        '#default_value' => array(
            'title' => variable_get('link_title', ''),
            'url' => variable_get('link_url', ''),
        ),
    );
    return system_settings_form($form);
}

Or check this url: https://www.drupal.org/node/1111260

function read_more_news_permission() {
  return array(
    'administer my module' => array(
      'title' => t('administer readmorenews settings'),
      'description' => t('Administer read more news settings.'),
    ),
  );
}


turn off wysiwyg for full html filter format?

You can switch to HTML display in D8 by clicking on source tab. So that you can retain Full HTML processing and work without output.


You can use node_save() to do this; CCK will automatically hook into it and update the field values in the database for you:

// Load a node
$node = node_load(1);

// Update the field value
$node->field_field_name = array(0 => array('value' => 'A value'));

// Save the node. Field values are also saved, and the node modified time is updated.
node_save($node);


How can I display the field in the tab that was active on save?

I think it is being called multiple times. To avoid that try Change your JS as below

$(context).find('.single-link').click(function () {
  $(context).find('.option').prop('checked', true);
});
$(context).find('.multi-link').click(function () {
  $(context).find('.option').prop('checked', false);
});

OR

change the on click() event to hasClass() the will be classes added to the active tab


how to reset taxonomy term ids after deleting all term from all vocabularies

Open up phpmyadmin and do a query

ALTER TABLE `taxonomy_term_data` auto_increment = 1

or using drush

drush sql-query "ALTER TABLE taxonomy_term_data auto_increment = 1"

But not sure that this is recommended.

NOTE: I am assuming that all terms have been deleted from within the UI


How can I add context (or distinguish between contexts) to translations with t()?

Yes, you can pass a context to t(), see the third parameter, $options. However, you can only do this in the source code, which means that it is often not helpful. Might be possible in your case, because it's your own code.


Get the value of a form element returned from an ajax callback function

I too not sure why the name attribute is not adding to the field. but you can bring by explicitly defining the name in the field.

 $form['form']['template2_field1'] = array(
      '#title' => t('GSIS No.'),
      '#type' => 'textfield',
      '#name' => 'template2_field1',
      '#description' => "Government Service Insurance System number.",
      '#attributes' => array(
          'id' => $template . '_field1' ,
      ),
  );


After working with JDev518 on this we discovered this was a permissions issue with paragraphs. Although this should have worked as is, we ended up installing Paragraph Type Permissions" and assigning specific permissions to create/edit/view the paragraph fields in question for anonymous. This "forced" the permission check to work and started including the submitted values in the email. However the contact module is determining the view permissions on those paragraph fields when it's building the email seems to be the cause of this issue.


Conditional Fields module with Google Maps

I added a possible solution at https://www.drupal.org/node/1277888#comment-11680473.  Hope that helps someone.


How filter node inside view block by even nid (or odd nid)

@IsmaH answer is on the right track (use Regex for filtering nid). The problem in his answer is that this filter uses mySQL Regular Expressions - this is why his proposed regex is not working.

This worked for me:
^.*[13579]$

or this for even numbers: ^.*[02468]$

Notice: no slashes at the beginning and end of the expression.


Straight from the docs:

  Sets a persistent variable.

Yes, it will be available across different requests.


What's the difference between the two-column layout and two-column bricks layout?

Layouts are defined in the Layout Discovery module and can be used by different layout modules.

The difference between those two layouts is the number of regions,  the Two Column Brick layout has three more. See the yaml layout definition:

/core/modules/layout_discovery/layout_discovery.layouts.yml

layout_twocol:
  label: 'Two column'
  path: layouts/twocol
  template: layout--twocol
  library: layout_discovery/twocol
  category: 'Columns: 2'
  default_region: first
  icon_map:
    - [top]
    - [first, second]
    - [bottom]
  regions:
    top:
      label: Top
    first:
      label: First
    second:
      label: Second
    bottom:
      label: Bottom

layout_twocol_bricks:
  label: 'Two column bricks'
  path: layouts/twocol_bricks
  template: layout--twocol-bricks
  library: layout_discovery/twocol_bricks
  category: 'Columns: 2'
  default_region: middle
  icon_map:
    - [top]
    - [first_above, second_above]
    - [middle]
    - [first_below, second_below]
    - [bottom]
  regions:
    top:
      label: Top
    first_above:
      label: 'First above'
    second_above:
      label: 'Second above'
    middle:
      label: Middle
    first_below:
      label: 'First below'
    second_below:
      label: 'Second below'
    bottom:
      label: Bottom


In Drupal, content is made with nodes. Blocks are used to give more information that could be related to content (such as the nodes that are part of the same book the viewed node is part of, or the nodes that are in some other way related to the currently shown one), to the users (e.g. the last users who logged in, or the users who saw the current node), or to the site in general.

Drupal offers more feature for nodes, starting from the permissions associated to them. While for blocks a plain Drupal installation just has the administer blocks permission, which allows to create new blocks, but also delete the existing ones, for nodes a plain Drupal installation has permission for editing, deleting, viewing, and creating nodes.
Nodes have a more complex system to assign permissions to user for operations on nodes, which involves three hooks (hook_node_grants(), hook_node_records(), and hook_node_access()), while for blocks there is just a hook for that purpose.

You aren't forced to create a view for nodes, in the same way you aren't forced to create a block with a view. In both the cases, the Views module (which is now part of the Drupal core modules) helps you in making a list of entities. For example, when you enable the Views module in Drupal 8, there are some administrative pages that are served from a view, allowing the administrator users to extend those pages easily.

Also, for what I recall, you cannot add comments to blocks, but you can have comments for nodes. In a similar way, there are things that third-party modules implement for nodes, but not for blocks.


You can see the how to set the file system settings on File system settings. You can also change it, and specify the other folder for the files as per your requirement.


Require specific access for certain pages with only one input field

so the characters can be random or need to be verified against some database table entries?

best thing would be to have a custom code/solution for this, use ctools popup and custom javascript to check for the right cookies on the selected pages, we can add a field defining the setting whether the page requires verification or not, and overridden node tpl (template) for that particular content type which can contain drupal_add_js or inline javascript based on the field condition. Adding a module and customising will add more pain in my opinion.


The problem is (as your comment indicated) the user id from route. That uses the node id, or user id from the url. On an edit page that is node/123/edit, so it can load the node and obtain the user. For the create page node/create, there is no such id.

Can't you use the User ID from logged in user filter instead? That should work.


Is it possible not to use utf8mb4 as encoding?

MySQL (and libmysqlclient) have a minimum version requirement of 5.5.3 for Drupal 8 (see https://www.drupal.org/node/2558615, https://www.drupal.org/node/2473301, etc).

It's not often that requirements are applied arbitrarily, so there will almost certainly be something in MySQL >=5.5.3 that core/vendor code requires.

As such, I would have to assume that no, it's not possible to change this without hacking core. Maybe not even with hacking core, as vendor supplied code may rely on it.


If you just want to remove them for a less cluttered back end, that perhaps doesn't worry non-technical admin users you could maybe CSS them out?


Get Entity from Path or Url Object Retrieved from Menu (Node or Page)

I managed to come up with a solution by using the storage manager to load the entity using the path to load it.

$page = \Drupal::entityTypeManager()
  ->getStorage('page')
  ->loadByProperties(array(
      'path' => $path
  ));

I'm assuming you can use the same method for nodes.


How to set "Language Selector dropdown" required in node form

I found the solution here

You can enable i18n_node module that is included in i18n module. Then:

    Go to edit the content type (admin/structure/types/manage/page).
    Open the 'Multilingual settings' tab.
    Check the 'Require language' checkbox.

Done.

Multilingual content must be installed at first and then in content type, Multilingual settings tab will be added


Display an image in menu generated from taxonomy terms

Try the Taxonomy Image module

The taxonomy_image module allows site administrators to associate images with taxonomy terms. With the association created, an admin can then make a call to 'taxonomy_image_display()' from their theme or other PHP code to display the appropriate image.


Get list of taxonomy terms for current node through Views

Come on it's not that hard!
I'm assuming you want to display all taxonomy terms across multiple taxonomy reference fields/vocabularies.
You can however filter the list of taxonomy terms that the View returns using Vocabulary filters.

Create a new view on Taxonomy table. You are basically showing taxonomy terms.
In the View creation page, uncheck "create page" and check "Create block". Give it a title "Categories". Click "Continue and Edit".
In the Views UI, add a new Relationship  Taxonomy term: Content with term, and uncheck "require this relationship".
Add a new Contextual filter : Content: Nid  and choose the just-created relationship as the relationship, Provide default value > Content ID From URL under When the filter value is NOT available. Also add basic validation check to the contextual filter.

5 .  Save the View and put the block where you want to display.

You can check the view by entering a test node ID to the preview field. It should show all taxonomy terms attached to THAT node.


You can use one of these method.

Below method is used to print Main Menu in page.tpl.php file:

$main_menu = menu_navigation_links('main-menu');
$output = '
';
$output .= theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
      'id' => 'main-menu-links',
      'class' => array('links', 'clearfix'),
    ),
    'heading' => array(
      'text' => t('Main menu'),
      'level' => 'h2',
      'class' => array('element-invisible'),
    ),
  ));
$output .= '
';
print $output;

Or the example provided here:

$tree = menu_tree_all_data('main-menu');
menu_tree_add_active_path($tree);
print drupal_render(menu_tree_output($tree));


Easy database reconfiguration for migration

Berdir wrote about a very nice solution some time ago, which also made it into Drupal 8 now.

It means that you keep separate settings.php's, which are included whenever available with a small code snippet.


Theming/Aligning Multiple Views Blocks on Homepage

Please comment below if I have misunderstood anything and I can modify my answer.

First, I will clarify that I understand what is happening.

To the user, there appear to be 6 different pages on the site but in actuality, they are looking at the View Page that you posted above with contextual filters (each containing a different taxonomy term).

On the homepage, in a grid, you would like to display 6 Block Views that display the 4 most recent posts for their respective Taxonomy Term.

You would want Views to print out in a Bootstrap-like format so that they utilize the Bootstrap responsive grid.

This is what I recommend:

First we are going to create the first New Block.
Create a Block View called "Front Page News Blocks" (Or something along those lines) that lists Nodes of the Article type
Limit the View to only display 4 nodes
Ensure that it is sorted via post date (Ascending)
Add a "Custom text" field to the view and put the "More" link (with the btn and btn-primary classes) in the value
All of the above settings are "Applied to All Displays"
Now, you want to create some Block Views within this View. Have a total of 6 different Block Views
Within these, you can add categories Filters (but apply them only to the respective displays)
Also, override the URL in the "More" link in each view (Once again, don't forget to only apply it to the current display)
Create a template based on views-view.html.twig but name it after your View to override the default theme file
Within your custom TWIG file, you can add the "col-md-4" grid classes
You would also need to override the Homepage template so that you can add a div with the "row" class to the region where these blocks will be.
Now your CSS classes should be in the markup and you should be able to style your site as planned.

What I laid out was pretty generalized and high level. Definitely comment below if you need clarification on anything and I can edit this answer.

Hope this helps get you on the right track!


Track how many times a JSON file is requested from other websites

There is a core module for that Statistics. On the configuration of this module (admin/config/system/statistics) you can ask for 'Count content views' who should work on every page drupal display (so your json).

There are a lot of custom module to extends statistics.

A little warning : Angular may be cache your json, so if your user go two times on a page you can loose this data. Maybe smarter to do this on the angular side.


In Drupal 8.2.5 the option is available. See this picture:


You are right node--[content-type].tpl.php is what you are looking for ,, but you need to get the fields values which can be done with print_r($node) inside the tpl file.

clear your cache to be sure to see the result.


If you're using Drupal 7 you can use taxonomy_term_load()

$term = taxonomy_term_load($tid);
$name = $term->name;

If you've got a bunch of term IDs you can save having to run a single query for each load by using taxonomy_term_load_multiple():

$tids = array(1, 2, 3);
$terms = taxonomy_term_load_multiple($tids);

foreach ($terms as $term) {
  $name = $term->name;
}

If you're stuck using Drupal 6 you can use taxonomy_get_term():

$term = taxonomy_get_term($tid);
$name = $term->name;

There's no multiple-load option for Drupal 6 that I know of unfortunately.


Found follow errors in php logs:

PHP Warning:  Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini

PHP Fatal error: Unsupported operand types in public_html/dev/profiles/commerce_kickstart/modules/contrib/search_api_db/service.inc on line 970

Got the redirect loop to stop after increasing the max_input_vars to 9000. I feel it's more of a bandaid fix though. So I'm taking this further into the Commerice Kickstart community.


Printing Region With Content in Custom HTML

I haven't had any need for a blank page before, but couldn't you just create a new .tpl.php for the front?

Under site configuration, set a node as your front page, then create a copy of page.tpl.php and name it page--node--1.tpl.php (or whatever node ID you have) .

Delete all the divs and containers to make the page blank, and then render regions in php like normal.

  print render($page['your_region']);


How can I react when a commerce product is explicitly created via the UI?

If you're only wanting to respond do products created via the UI, then form submit handlers should work. As noted, this wouldn't work for products created by any other method.

The correct hook you should use is hook_commerce_product_insert(). This isn't documented, but it should be. Using this hook will ensure that no matter where the product gets added that the hook runs.

function MYMODULE_commerce_product_insert($product) {
  ...
}

If you're wanting to create 100 new products, you can still loop in this function but you'll just need to differentiate between products that are created and the one that you began looping by some particular method. This could mean, for instance that there is particular SKU format (e.g. all created products end in -XXX where XXX is some number and the one created via the UI does not) or some extra field (e.g. field_parent_product that is empty on the one created in the UI but isn't on the sub-products). It's then trivial to both skip products that have a non-empty field, but also be able to handle updates or deletes down the road.


You may be aware of this. Change file path for individual sites at Configuration/Media/File system. By default it is set to sites/default/files. So your both sites are addressing same path.

So just change the path there accordingly for both sites.


How to serve the same page for all URLs?

In case someone has the same issue, it only happens when connected to Drupal's admin panel. I solved it by disconnecting…


Landing page extension without 404 error

Like @Clive said, Drupal will try to resolve that path if it can. Just put a check in your page callback to see if there's an extra argument. If there is and it's valid the menu router will handle it. Otherwise it will fall back to your defined path, where if it finds something after /news, it will return drupal_not_found(). The 'return' is important, otherwise you might see the page render twice.

function MYMODULE_menu(){
    $items = array();
    $items['news'] = array(
       'title' => "Les news",
       'page callback' => 'landing_page',
       'access arguments' => array('access content'),
    );
    return $items;
}

function landing_page(){
    if (arg(1)) {
        return drupal_not_found();
    }

    return 'something';
}


In drupal, Show own unpublished comments

Try the view_unpublished module

  This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.

After installing the module, navigate to your user access page and assign the appropriate permissions to the roles you wish to be able to view unpublished nodes.

Similar module : Comment Access

  Comment Access allows your users to control the comments on their posts. It adds permissions to administer, approve, and delete comments on nodes they create without granting full comment administration access. Permissions are granted by node type, so it's a great way to allow your users to manage comments on their own blogs,


How to store some info while user is submitting rating with Fivestar module?

Submit handler was not working so I have decide to do it with validate handler like this

function recipe_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'fivestar_custom_widget') {
    $form['#validate'][] = 'fivestar_rest_api';
  }
}

function fivestar_rest_api($form, $form_state) {
   $ch = curl_init("http://www.example.com/xxx");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_HEADER, 0);
   $data = curl_exec($ch);
   curl_close($ch);
   $json = json_decode($data,true);
   $errorMessage = $json['errorMessage'];
   $errorCode = $json['errorCode'];
   $commands[] = ajax_command_remove('.field-name-field-fivestar-rating');
   $commands[] = ajax_command_append('#rating-wrapper', 'Thankyou for your rating.');
   return array('#type' => 'ajax', '#commands' => $commands);
 }

Now it is working fine form me.


Imported views from other site that didn't have any Master display in the UI. How to remove Master display from Views UI?

A view will always have a master display. You can set it to not display on the views settings page at 'admin/structure/views/settings'. To get rid of the error you are seeing, just a add field to the master display, or set the display to show content instead of fields.


How do I enable the "extra" stuff in the OpenPublic distribution?

It sounds like you've just installed the wrong profile. At the first step of the installation you get a choice like

Once you choose OpenPublic and follow the installation through, you won't have a vanilla Drupal install any more. For example your home page looks like this:

Don't forget it's still in beta so you're likely to see warnings/notices around the place; I wouldn't recommend using it for a production site yet. It's also pretty sluggish compared to a normal Drupal install so make sure you profile it before deciding whether or not to use it.


Is there a better way than twig files overwrite?

Yes, usually there is a better way: preprocess functions allow you to alter the render array that is passed to the twig template. Adding a class is, in most cases, possible, but you might need to check how the twig file is turning the render array into markup.

This article has more info: https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file


Recommend a slideshow module that can create a display from a view?

To be honest, I have never been satisfied with any of the existing slideshow modules.

Typically, I use Views to render out the HTML I want.  Sometimes I use field output, but lately I have been using node output with a custom view mode.

The I use some custom CSS and JS to make the slideshow do exactly what I want.

Normally, I wrap all of this up in a custom block.

It may sound complicated, but it usually only takes a few hours to do all of this.


Is it possible to change the fields' names of the JSON generated by Services module?

You can use hook_services_request_postprocess_alter(): http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x

For example, say you wanted to replace the node title property with nodeTitle when a node is being retrieved, you can do so like this:

/**
 * Implements hook_services_request_postprocess_alter().
 */
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller['callback'] == '_node_resource_retrieve') {
    $result->nodeTitle = $result->title;
    unset($result->title);
  }
}


Do I need hook_update_N if there are no database changes?

If the changes are just code, (not db schema changes, content changes, variable changes, data changes in general), then you don't need an update hook, no.

Basic rule of thumb: will your code updates break anything for existing or new users? If not, you don't need an update hook.


drupal Theme class is missing, I guess! How to fix it?

Make sure your theme has all the appropriate Theme Regions (more details about Theme Regions). Also, there may be some custom PHP overrides provided by the working theme, so you'll want to review the theme's template.php file for any custom PHP theme overrides you may want to help bring over to your other theme.


Only allow certain roles to publish content, other roles can save as unpublished?

You will need to alter insert / update node entity form:

Define a permission "Save unpublished content"
Make a hook_form_alter or hook_form_ENTITY_TYPE_form_alter
Check if you are alter the exact entity types you need.
Hide all buttons you don't need (based on permission)
Add button ('save unpublished content') (based on persmission)
When submitting: call the default submission and add yours to set the status 0.

Save button is an UL with two LI elements: save published, save unpublished:


Parameters and key value pairs for VotingAPI

I solved it. The entity ID is the node id (nid) if you are voting on a node for example. eg for nid of 75, it is entity_id: 75. Other parameters are 'percent', 'points' or 'options' for vote type. And for tag it is 'vote' or whatever custom tag you created as a field.  The 'value' of course is the number you are voting. If you are using standard settings for 5star, you enter eg 20 (for 1 star), 40, 60, 80 or 100 (5 stars). The mandatory parameters are entity_id, tag and value. I've read the system can work out the other details, eg user id from the currently logged in user.

eg this format worked for me: let newVote = ["votes":[["value":100,"uid":32,"entity_id":1,"entity_type":"node","tag":"vote","value_type":"percent"]]]

see Votingapi REST server call internal server error - 'services exception: missing entity ID'


Your route has no node parameter. See the documentation Structure of routes and the example from there:

book.export:
  # This path takes dynamic arguments, which are enclosed in { }.
  path: '/book/export/{type}/{node}'
  defaults:
    # Because this route does not return HTML, use _controller.
    _controller: '\Drupal\book\Controller\BookController::bookExport'
  requirements:
    _permission: 'access printer-friendly version'
    # Ensure user has access to view the node passed in.
    _entity_access: 'node.view'

You can access the route parameters in the controller directly in the function arguments:

public function bookExport($type, NodeInterface $node) {
  // get the id from the controller argument
  $node_id = $node->id();
}

\Drupal::routeMatch()->getParameter() is to get a route parameter outside of the controller, for example in a preprocess hook. For this to work the parameter has to be defined in the current route as well.


Where is the maintenance mode value in the database?

It's no longer a part of the config system; it's a part of the state system which is stored in the key_value table as a part of the state collection.


How to resolve my timeout during import of my Drupal database using phpMyAdmin?

Skip processing rows in cache tables
For any of the cache-tables, there is no need to actually import them in your dev environment. So it is OK to just skip those rows during your import. That might help to get around this issue. FYI: clearing the cache in the site where you are exporting from, before performing the export is another way to avoid such rows being imported (might help also).
Use module Backup and Migrate
Another possible work around, you may want to consider using the Backup and Migrate module. Here is a quote from its project page:

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

Refer to the readme.txt that comes with the module for details to get you going.
Your local environment is Win 7, though your hosted website probably runs in "some other OS" (Linux? Something else? consider clarifying in your question also ...). So that implies potential extra challenges (because of differences in the OS-es. I've had good experiences with Backup and Migrate between different OSes, which didn't cause any problems (worked fine) in situations where the typical MySql export / import failed before.


drush_set_error() has basically been deprecated in Drush 8 and has been removed in Drush 10. Hitting up Google for drush_set_error() will give you a blog post by one of the maintainers: Porting Commands to Drush 9. In there the following is stated.

Replace drush_set_error() with throw new \Exception()

Now let's compare a sample command in Drush 8 and in Drush 10 – the xkcd command.
In Drush 8 there's the following line:
drush_set_error('DRUSH_XKCD_SEARCH_FAIL', dt('The search failed or produced no results.'));

In Drush 10 this line became:
throw new \Exception(dt('The search failed or produced no results.'));

One more.
When you search the pull requests for drush_set_error() you'll find the following: Replace drush_set_error() and drush_log() via Drush::logger() #3810. In there drush_set_error() has been replaced by Drush::logger()->error().
Now what's the difference between Drush::logger()->error() and throw new \Exception()?

throw new \Exception(dt('My error messsage.')); is the last thing you do before Drush quits.
Drush::logger()->error(dt('My error message')); gives you the chance to print out multiple error messages and let your code continue.


You can use menu_get_item() to inspect what generated the page and add a class to the body element in template_preprocess_html(). I saw the code first in the Zen theme, where they also add a class if the page was generated by Views. Link to Zen template.php

    function MYTHEME_preprocess_html(&$variables, $hook) {
      // Store the menu item.
      $variables['menu_item'] = menu_get_item();
      if ($variables['menu_item']) {
        switch ($variables['menu_item']['page_callback']) {
          case 'page_manager_blog':
          case 'page_manager_blog_user':
          case 'page_manager_contact_site':
          case 'page_manager_contact_user':
          case 'page_manager_node_add':
          case 'page_manager_node_edit':
          case 'page_manager_node_view_page':
          case 'page_manager_page_execute':
          case 'page_manager_poll':
          case 'page_manager_search_page':
          case 'page_manager_term_view_page':
          case 'page_manager_user_edit_page':
          case 'page_manager_user_view_page':
            // Is this a Panels page?
            $variables['classes_array'][] = 'page-panels';
            break;
        }
      }
    }


How to easily create a landing page for contents with specific tag

You can still do this easily with view panes. They play very nicely together with panels.

First step is to create the vocabulary you want to use / filter on. Then create a view pane with this vocab as an (exposed) filter.  By exposing this filter when a user adds this view pane to a panel, that exposed filter becomes a pane configuration option.  You can even expose content type as a filter and the user can choose what content types and terms they want to filter on when they add the pane.


How to get menu tree from a node to build a customize breadcrumb?

Menu Breadcrumb

  Append the page title to the breadcrumb (either as a clickable url or    not)
  Hide the breadcrumb if it only contains the link to the front    page.
  Generate the breadcrumb from the URL structure if content does    not belong to a menu (7.x-1.6 and older only)

For more details click here

Custom Breadcrumbs

  Many new features have been added including support for Views, Panels,
  Taxonomy vocabularies and terms, paths, and a simple API that allows
  contributed modules to enable custom breadcrumbs for module pages and
  theme templates. These are implemented using optional, independent
  submodules that depend on the main Custom Breadcrumbs module.

  In addition to breadcrumb visibility, this version provides an option
  permitting PHP code snippets to be used in forming the breadcrumb
  titles and paths. Multiple languages are also supported.


How to allow user's of a certain role to change the node creation date

You want Override Node Options module.

  The Override Node Options module allows permissions to be set to each
  field within the Authoring information and Publishing options field
  sets on the node form. It also allows selected field sets to be set as
  collapsed and / or collapsible.

In addition you may be interested in Date Popup Authored to use a datepicker on that field.


Drupal 7 form_state[redirect] does not work

You need to pass $form_state in by reference, or the change won't be persisted outside of the function scope:

function ticketGenerator_list_submit($form, &$form_state) {


Once function not preventing behavior executing on AJAX update

The once method is a simple beast - it checks for a class of NAME-processed on the element (NAME being the string arg you pass it). If it doesn't find that class, it assumes this is the first execution; it runs the function, and adds the class to the element. When the code executes again, the class is there, so it doesn't run the function.

When your behaviour executes first time, there's no -processed class on the elements, so it gets added and your function executes. Everything's happy...

Then an AJAX call happens, and the textfields get replaced; they no longer have the -processed class on them, since they're new elements received from the from builder function, and once has no option but to start from scratch again, running the function and adding the class to the new elements.

2 ways you could solve this:

Keep using behaviours, and use your own flag:

(function ($) {
  var processed = false;

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      if (!processed) {
        $('#edit-arrival-date-datepicker-popup-1, #edit-departure-date-datepicker-popup-1', context).attr('disabled', true);
        processed = true;
    }
  };

})(jQuery);

Conclude that behaviours aren't appropriate for this particular op, and stick with jQuery.ready


This should work (at least it did for me). Put this code in your template.php and adjust accordingly.

I created a user field called 'type' as a select list (for future consideration). You could just as easily use a hidden field or a text field if you don't want the user to be aware of a difference (NOT FOR SECURITY PURPOSES - THIS IS VERY INSECURE).
Make it mandatory.

given a url of mysite.com/user/register?type=one  this will assign the field named 'type' to 'one', otherwise
it will assign it 'two' by default.

I added some comments to help with the code, but you can remove that later. Obviously you will need to adapt this to the profile selection - I don't profile2 setup on my test site so I can't really get into that, but this is the basics, and I can help guide through the rest.

function theme_form_alter(&$form, &$form_state, $form_id) // change theme to your theme name
{
    if($form_id == 'user_register_form')  // only check on user registration form
    {
      $urlGet = drupal_get_query_parameters(); // get URL parameters ?type=one, etc
      if($urlGet['type'] == 'one') // check ?type= against expected
      {
        $form['field_type']['und']['#options'] = array('One' => 'One'); // set select list option(s)
        //$form['field_type']['und']['#options'] = array('One' => 'One', 'Three' => 'Three'); // for multiple values
      } else
      {
        $form['field_type']['und']['#options'] = array('Two' => 'Two'); // default value
      }
    }
}


View with empty filter result visible only to admin user

So, in the end I followed some advice I found on another somewhat similar problem which said one can go onto the Advanced Settings on your view > Query Settings > check "Disable Query Rewriting"

This worked, but anyone following this advice should be aware of the security implications regarding visibility.


As with most things in Drupal someone else has already been there and done it...

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_region_content/7#comment-48353


Can fields validation errors be displayed below the fields?

I think you are looking for something like the Inline Form Errors Module. Here is a quote about it (from the module's project page):

... allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.
IFE provides three behaviors for the configured forms

Leave the messages in place, this option will copy the error messages and place them inline. The original error messages set by Drupal will remain in place
Show an alternative message, this option will replace the original messages with a generic error message such as 'Please correct all errors.'. This message can be set in the IFE configuration page. The original error messages are placed inline with the form elements
Remove all messages, this option will remove all error messages and place them inline with the form element

In all cases only the messages related to the form will be touched. All other messages will remain in tact.


What is the best way to overwrite a node display with a view

I think the Drupally way to replace node content with a views block would be to hide the fields via the Display Settings, add the fields to your views block, display the views block on the node.

If you cannot hide the fields on this content type, I would suggest creating a content type for this type of page and use case.

My personal vote, if you need truly "re-arrangeable" content, would be to start using Paragraphs.

https://www.drupal.org/project/paragraphs

I offer this as an answer because I feel that while things like 301 redirects, NID template overrides, or even hook alters might get the job done, they may be a little hacky for a content situation.

Paragraphs allow you to create re-useable pieces of content with as many or as little fields in each as you'd like. And by far Paragraphs has been the best content experience I've had in Drupal.


How to display parent Taxonomy ID in REST export

Unfortunately, this is currently not yet supported. We're working to add that capability in https://www.drupal.org/node/2543726.

Long story short: the $term->parent field is a special snowflake: it's not an entity reference field as you would expect!


Cannot get form_state storage or protected form values to work

This:
'#submit' => [$this, 'addAnotherImageSubmit'],

Should be this:
'#submit' => [[$this, 'addAnotherImageSubmit']],

Submit handlers are only called for #type submit and not #type button, so you'll need to change the type.
You will also need to use $form_state->set(), rather than a property on the class. This is because the form class is re-instantiated for each iteration (build, validate, submit), and therefore values stored in the properties of the form class will not persist. $form_state->set() persists values, as these are stored in the database, and are repopulated for each instance of the form class (as long as you call $form_state->setRebuild() as you have done).


I think you are looking for creating a block of similar node by term with one more filter "another content type". There is a module to do this exactly but it doesn't have the content type filter in it. I will still recommend you to have a look at it - Similarterms.

You can achieving the same with view. Please look into the answer given at these links, it has been explained in details --

https://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3

Recommend nodes based on current node field value in view block


As you want the suffix to be added when the save button is added you need to add a custom submit handler. In the hook_form_alter do something like       $form['actions']['submit']['#submit'][] = 'mymodule_form_submit'; and in the submit function mymodule_form_submit save the value you want.

function mymodule_form_submit(&$form, FormStateInterface $form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  // Get the value of your field
  $my_val = $entity->get('field_name')->getValue();
  // Set new value
  $entity->set('field_name', 'http://' . $my_val);
  //Save the entity
  $entity->save();
}


How to remove 'None' from forum options?

The forum is set as a taxonomy reference in the field list of the content type 'forum post'.

Can you not just set it to be a compulsory field at /admin/structure/types/manage/forum

This way if somebody entered a blank value it would reject the answer and ask them to resubmit, which works better than the default being one of the forums, in which case lots of topics still end up in the wrong place.

The only thing I'm confused by is that I thought this was the default setting for Drupal's inbuilt forum content type anyway? Buy maybe I'm wrong on that.


I found what I was doing wrong.

I assumed that the exposed filter block for the view was the same for all displays of that view, When it actually creates 1 block per display.

I disabled the block "Exposed form: filter_view-page" for the /mention path and added the another block "Exposed form: filter_view-page_2" for it.

Works fine now.


See line 398 of plugins/address.inc ? $format['#wrapper_id'] = drupal_html_id('addressfield-wrapper'); That's the root of the seemingly arbitrary field identifier stuff. The code gets there from line 460 of addressfield.module $element += addressfield_generate($address, $settings['format_handlers'], $context);

Make a custom module, set the weight higher than that of addressfield so it runs after the addressfield module's hooks, and alter the form. There aren't hooks inviting you to alter those IDs unique to addressfield, and altering them in this case is no different than any other, so long as the module weight is adjusted.


How do I create a time range form field?

Haven't tested this but if you install time field module you then could do this to simulate a range:

$form['from'] = [
  '#type' => 'time',
  '#title' => 'from',
];
$form['to'] = [
  '#type' => 'time',
  '#title' => 'to',
];


If you just want to add a new tab, then the module should just implement hook_menu(), using code similar to the following.

function mymodule_menu() {
  $items = array();

  $items['user/%user/new_tab'] = array(
    'title' => 'New tab title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_newtab_form', 1),
    'access arguments' => array('access new tab'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

function mymodule_newtab_form($form, &$form_state, $account) {
  // ...
}

mymodule_newtab_form() would get the user object in $account. That menu callback would build a form using the form API. If the purpose is to output, the menu callback declaration would be similar, except two array indexes, which would be:

'page callback' => 'mymodule_newtab_form',
'page arguments' => array(1),

The argument passed to the callback would be different too.


How can I translate the title of taxonomy term pages when using i18n?

Yet another interesting multi lingual challenge, this one related to taxonomies. The reason for your issue might be because of one reasons explained below.

Use a recent i18n version

Make sure you're using that the version of the i18n module is at least version 7.x-1.8, because it might be because of a bug in the 7.x-1.7 version of it.

Use the correct translation mode

You also want to check the "translation mode" that you've specified within admin/structure/taxonomy/categories/edit (whereas "categories" is the name of your specific category): by default that is set to "Localize", though it should be set to "translate". Attention: after changing this value, be aware that you then also have to:

enter a translated value for each of the tags and
revisit any of the existing nodes that are already using the specific taxonomy, so that they use the (translated) term that corresponds to the language of the node.

Obvious, if you have other taxonomies with the same issue (like "categories" in your case), you should repeat this for those others also.

Consider the Title module

Possibly related to this issue is that titles that do not get translated in a site using the i18n module, is most often because of the Title module that has not been enabled. From the module's project page (bold markup added here):

  After enabling the module as usual, visit the Manage fields page of the content type, taxonomy vocabulary or "comment type" which you wish to replace fields of and click the replace link. That's all.

FYI: I have not yet run into any situation where I had to install/enable this module to get multi language site to work as I want.


What is the protocol for adding a new module dependency to a module that has only had a dev release?

There's no sanctioned protocol for such a case. All I think of is to minimize the impact.

Consider that even if you create a new branch, users may update and neither realize there's a new dependency, and your module may end up silently disabled because of unmet dependencies. This happened to the update of views from 6.x-2.x to 6.x-3.x where a dependency on ctools was added. In that case, the impact was low because ctools usually is present.

On documentation, in addition to changelog or upgrade doc in the project page, I suggest to add it to the release notes. Since they can be read easily when updating with drush.

Last, if the dependency you're introducing is a popular module, you can alleviate the impact by enabling the new dependency in hook_update_N or raising an error if not available. Here's some untested code:

<?php
function MODULENAME_update_7001() {
  $enabled = module_enable(array('foo', 'bar'));
  if (!$enabled) {
    throw new DrupalUpdateException('foo required.');
  }
}


How to use media field with entity browser widget in a frontend theme?

I found the solution.

I just copied the media.html.twig template from classy theme to my custom theme which did not work.

We need to copy this file also container.html.twig to our custom theme's templates directory then it will work.


Drupal 7 Views: Use one views.tpl.php file for multiple views

In Views 3 you can add tag “template1” to your views and create template views-view--template1.tpl.php.

Multiple tags supported.


Take a look at the Special Menu Items module. What does it do?

"Special menu items is a Drupal module that provides placeholder and separator menu items" (1)

A placeholder is defined as

"A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it." (1)

Which matches your description of 'labels' in your question.


How do I configure the "input format" for the File Tree module?

If you want to get File Tree to work, after you set up the input filter, the directory you are referring in [filetree dir="dirname"] must be a directory contained in your site's "files" directory. If you want to display all the files in the "files" directory use [filetree dir="/"], or if you want to display a particular directory, put the files in a directory (say, dir1) under files and specify [filetree dir="/dir1"].


Where are functions being called from when errors are vague?

The Devel module can be extremely helpful in cases like this.
Once installed, go to the admin/config/development/devel path, and you will see an option for additional error handlers:

If you select the Krumo backtrace option(s), Devel will register itself as the PHP error handler, and it can then show error messages with the full backtrace!


Your administrative role probably lacks the "administer permissions" permission.

If you have Drush installed:

$ drush role-add-perm 'administrator' 'administer permissions'

You may also want to make sure your site still defines the 'administrator' role, since occasionally developers may manually delete the default roles from the DB (really not a good idea unless you know what you're doing). If you can't view available roles you can run this Drush command:

$ drush role-list

If it's not there, then you may have to create a new role to replace the admin role that was deleted and assign the role to yourself, and give your new role the 'administer permissions' permission:

$ drush role-create 'administrator'
$ drush user-add-role 'administrator' 'your username'
$ drush role-add-perm 'administrator' 'administer permissions'

If for some reason you don't have terminal access to your server, then you may need to download and enable the Devel module and PHP filter, then write a script that you can paste and run in /devel/php, but that should really be your last resort. https://drupal.stackexchange.com/a/56495/72084

p.s.: I believe Drupal gives user 1 the administrator role and completely unrestricted access by default. So if you are logged in as someone other than user 1, and/or if the administrator role has been deleted, that may explain how this problem came about. https://www.drupaleasy.com/quicktips/beginner-tip-what-special-about-drupal-user-1


How to remove wrapper when rendering page region?

Add a copy, or edit the existing copy, of the core (or your theme/sub-theme's) region.tpl.php file, to your active theme. You can change the wrapping markup to whatever you like in there.

Clear the cache, and you're done.


How do I get the translated node type of a node?

I have edited html.tpl.php

I have added this code before starting the body tag in order to replace body css classes with translated

<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>

after this modification, you can search css class name in translate page and put a suitable translation for it.

so final html.tpl.php is

<?php

/**
 * @file
 * Default theme implementation to display the basic html structure of a single
 * Drupal page.
 *
 * Variables:
 * - $css: An array of CSS files for the current page.
 * - $language: (object) The language the site is being displayed in.
 *   $language->language contains its textual representation.
 *   $language->dir contains the language direction. It will either be 'ltr' or 'rtl'.
 * - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document.
 * - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data.
 * - $head_title: A modified version of the page title, for use in the TITLE
 *   tag.
 * - $head_title_array: (array) An associative array containing the string parts
 *   that were used to generate the $head_title variable, already prepared to be
 *   output as TITLE tag. The key/value pairs may contain one or more of the
 *   following, depending on conditions:
 *   - title: The title of the current page, if any.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site, if any, and if there is no title.
 * - $head: Markup for the HEAD section (including meta tags, keyword tags, and
 *   so on).
 * - $styles: Style tags necessary to import all CSS files for the page.
 * - $scripts: Script tags necessary to load the JavaScript files and settings
 *   for the page.
 * - $page_top: Initial markup from any modules that have altered the
 *   page. This variable should always be output first, before all other dynamic
 *   content.
 * - $page: The rendered page content.
 * - $page_bottom: Final closing markup from any modules that have altered the
 *   page. This variable should always be output last, after all other dynamic
 *   content.
 * - $classes String of classes that can be used to style contextually through
 *   CSS.
 *
 * @see template_preprocess()
 * @see template_preprocess_html()
 * @see template_process()
 *
 * @ingroup themeable
 */
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<?php
    $body_classes_array = explode(' ',$classes);
    foreach($body_classes_array as $key=>$class)
    {
        $body_classes_array[$key] = t($class);
    }
    $classes = implode(' ',$body_classes_array);
?>
<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

I hope my post can help you.


Move views pager to top of node instead of bottom

Go to the View UI. Click Theme: information. The top list item will say Display output. There are several file names to go from the least specific to the most specific. These are the choices to override the default View template for Display output. If you want every view pager to be at the top choose views-view.tpl.php otherwise choose something more specific.

Create a file in your theme folder titled with one of these title options. Click the blue Display output link and copy the code into the file you just created. Save. Clear cache. Congratulations you have now overridden the View theme template.

Find the code

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

and move it to the top of the code where you want the pager to be. Save.


Don't even bother. This level of effort is not even necessary.

If you are just moving content from Drupal 6 to Drupal 8, use the built in Migration modules that come with core. It is designed to do this. I can't even quantify how long this would take to do in PHPMYADMIN of all things. You'd likely wind up corrupting the database itself. The schema is nowhere near as simple as it once was.

Please try using the tools and check the docs for more: https://www.drupal.org/node/2257723

All you have to do is point it at your Drupal 6 database and let it work. If you have basic content (sounds like Articles and blog posts) it should work very well. It will even build out the content type and taxonomy for you.

Even if the automatic route doesn't totally work, still attempt to use the Migration tools available to you. You will save a ton of hours (probably hundreds) vs editing a database manually.


Install CKEditor

This module will allow Drupal to replace textarea fields with the CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This HTML text editor brings many of the powerful WYSIWYG editing functions of known desktop editors like Word to the web. It's very fast and doesn't require any kind of installation on the client computer.

As mentioned by darol100, for Upload Install IMCE

IMCE is an image/file uploader and browser that supports personal
directories and quota.

Here is a nice video tutorial: Installing and Using CKEditor and IMCE


The trick is the combination of two things:

Instead of translation language, use the filter "Default translation", so that you only get the original/default/source translation for each node.
Then, in Language below Pager, for "Rendering Language", select "Interface text language selected for page". That will select the best available translation for the current language, just like accessing node/1.


Why does user_load($id) NOT return FALSE when an invalid id is passed in?

The account test probably is working, but this is wrong:

return "
Invalid acctid "+$acctid+"
";

If the $acctid is an integer, it's evaluating that and returning an integer.  The proper php concatenation operator is '.' (without the quotes), change your return statement to

return "
Invalid acctid ".$acctid."
";

It'll evaluate to the string you're presumably expecting.


Drush cc gives only two options even when I am in root folder

Use drush cr (container rebuild) rather than drush cc (clear cache)
for drupal 8.


Webform submissions to be seen on Drupalgap

Use a DrupalGap Views Render Array. With it you will:

Create the Views JSON page display in Views with contextual filter(s)
Create a page in the app to display the view
Use the Views Render Array to send up the contextual filter(s)
Build the render function to render each row of the table


Drupal 6 Feeds Module User Import & Ubercart

After searching high and low I finally found a workable solution.

Using user_import module in conjunction with this little custom module here I was able to import all of customer information from the old site.

It was exactly what I was wanting to do. All I had to do was match up the fields to my CSV file and I was able to get it all added in ot the appropriate uc_addresses tables.


Cant show Commerce Products in View on Taxonomy Term page

This isn't an official source, but it might help you.

Don't attach a block on your taxonomy page. Instead, create the View as a page and set the URL (under path) to override the the taxonomy term page (e.g. taxonomy/term/%).

Under contextual filter use : Content: Has taxonomy term ID

For the filters, use the settings in the screen shot (in the screenshot, my taxonomy terms belong to a vocabulary called Shop Categories).

Hope that helps!


You can create custom template suggestions for node using hook_preprocess_node... In your case it should be below code in your theme template.php file... You can read query arguments using $_GET variable..

function YOURTHEME_preprocess_node(&$variables) {
  if ($variables['type'] == "image" && isset($_GET['template'])) {
    $variables['theme_hook_suggestion'] = 'node__image__template' . $_GET['template'];
  }
}

Your template file should be...

node--image--template1.tpl.php

node--image--template2.tpl.php

node--image--template3.tpl.php etc...


How to mark calendar days between two dates?

I did this with the same date field and enabled the to date option.


You need a behaviour:

Drupal.behaviors.myBehavior = {
  attach: function(context, settings) {
    jcf.refreshAll();
  }
};

That will be called on DOM ready, and every time Drupal.attachBehaviors is invoked (i.e. after AJAX calls)


What happens to fields that don't have corresponding database columns?

Interesting question, had a quick read through the module's code.
I came across this comment that should answer your question:

@salesforce_pull.module:335

  // Flag this entity as having been processed. This does not persist,
     // but is used by salesforce_push to avoid duplicate processing.
     $entity->salesforce_pull = TRUE;

It seems that this is not an entity field (or rather an entity property) that is attached to an entity (and therefore stored in the db), but, as the above comment mentions, simply a short-lived flag.

The way this goes is like this:

The salesforce_pull module sets the flag on an entity (see @salesforce_pull.module:335)
salesforce_pull conditionally wraps that entity in an entity_wrapper object and calls the ->save() function on the object (see @salesforce_pull.module:341)
This call will call hook_entity_update implementations, including the one from salesforce_push (see @salesforce_push.module:20)
salesforce_push will call the salesforce_push_entity_crud function that checks the value of that flag before using the Salesforce API to sync data (see @salesforce_push.module:44)

All the steps above take place in the same request, which is why persisting the flag is not required.

Hope this helps, good luck!


How do I pull in a group of term descriptions instead of their names?

One quick way to solve it with code would be to add a custom field formatter:

function MYMODULE_field_formatter_info() {
  return [
    'taxonomy_term_csv_descriptions' => [
      'label' => t('Taxonomy term CSV descriptions'),
      'field types' => ['taxonomy_term_reference'],
    ],
  ];
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = [];

  if ($display['type'] == 'taxonomy_term_csv_descriptions') {
    $descriptions = [];

    foreach ($items as $item) {
      $descriptions[] = check_markup($item['taxonomy_term']->description, $item['taxonomy_term']->format);
    }

    $element[0] = ['#markup' => implode(', ', $descriptions)];
  }

  return $element;
}

That will give you a new formatter to use for taxonomy term reference fields in Views or the Manage Display pages for content types.

If you go with this solution you can remove the relationship to the Taxonomy Term from your View.


set new content-type as product in ubercart

Yes, you can. It is a bit confusing the first time you try, as Ubercart terminology is different for some reason; they call it product class, but it is just a new content type.


How to configure paragraphs module for multilingual

From the community documentation about Field Translation:

  Note: The Field Translation module does not provide content translation for fields. This functionality is provided by the Entity Translation (ET) module.

So could it be that the Entity Translation module is what is missing?


When a user has forgotten their password, how to let them set a new one?

Same problem here. My site had an action set to direct to the homepage on login. This helped me a lot to identify it. My solution was to disable the action an set a destination parameter by GET in my template to redirect user to the homepage on login. "/user?destination=/"


Flexslider field: number of thumbs, number photos and thumb slider

I ended up doing it from scratch. I created a custom node.tpl.php, got all the pictures with

$photos = field_get_items('node', $node, 'field_photos');

Then looping through all items and creating for each item the options

$photos_slide = array(
    'style_name'    => 'large',
    'path'          => $photo['uri'],
    'width'         => '',
    'height'        => '',
    'alt'           => '',
    'title'         => $title,
);

and then print the image:

print theme('image_style', $photos_slide);

You can follow this example http://flexslider.woothemes.com/thumbnail-slider.html in order to know how to set the HTML.


One possible way to handle this situation is for your Module B to define a default, stub service with the same type signature (ie, Interface) as the one you need).  Use that in the YAML.  Then, in your Module A, you can alter the service to the one that the module provides.

That said, I do agree with the comments that you may be bypassing one of the benefits of DI, and creating a tight coupling between your two modules.  Read the linked article to see when it is appropriate.  Core uses it for the language and workspaces subsystems.


d8 webform submission views how to exclude Action Apply to Selected Items

Just after posting I found the answer.  In fields section, the webform submissions bulk operation form entry can be deleted and that removes the pesky entry shown in the question.


How can I point to an internal anchor using core menu?

I don't think you can do that through the UI.

However, you should be able to specifify it with menu_link_save() in a module, for example in a hook_install() implementation. See the options key.

Looking at url(), something like 'fragment' => 'digital-anchor' should do the trick.


How can I load a block's subject and body, programmatically, for use in a module?

/**
 * Implements hook_block_view().
 */
function hook_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'block_1':

      $block['subject'] = NULL;
      $block['content'] = 'Full block body html here';
      break;

    case 'block_2':

      $block['subject'] = 'Block Subject Here';
      $block['content'] = 'Full block body html here';
      break;

    case 'block_3':

      $block['subject'] = 'Block Subject Here';
      $block['content'] = 'Full block body html here';
      break;

  }
  return $block;
}

Based on https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_view/7


"Drush cannot find your database connection details"

Drush no longer allows you to define a 'database' record in your site alias file for use with sql-sync.  This used to work in earlier versions, but is no longer supported.  Make sure that the source and target sites both have valid settings.php files that include the database information.

To test:

drush @hpc.dev sql-conf

If your database connection is correct, it will be displayed. Using sql-conf on each site can help isolate which one is having a problem with its connection info.


Removing second copy of ctools module from filesystem

Unless you have apc.stat = 0, then APC caching is likely not the problem.  You can always set apc.enabled = 0 as a temporary measure until you get the problem fixed.

What version of Drupal?

If you are on Drupal 7, you could try deleting the extra copy and then running Registry Rebuild via drush.  Follow the instructions on the project page.

The other method that should work for Drupal 6 and 7 would be to take a database backup, and then hand edit the {system} table.  If it has both "sites/all/modules/coots" and  "sites/all/modules/contrib/coots" in it, delete out the contrib entries.  If it just has the "sites/all/modules/coots" entries, edit them to take out contrib.  Then manually clear out all of the cache tables.

Make sure you backup your database no matter what you do.  Both of these are dangerous operations.


Turned out to be as simple as placing favicon.ico into the theme root folder (!)


I thought this can be done using hook_field_create_field, but it's not possible. Using that hook and then calling field_update_field will not work because the update does not allow this:

  if ($field['storage']['type'] != $prior_field['storage']['type']) {
    throw new FieldException("Cannot change an existing field's storage type.");
  }

Drupal doesn't want you to screw up existing data. So being careful and knowing what you are doing, the existing fields could be modified in the field_config table in the database. Reimplementing field_update_field you could do:

/**
* Implements hook_field_create_field().
*/
function mymodule_field_create_field($field) {
  if ($field['type'] == 'fieldtypetostore') {
    $field['storage'] = array(
        'type' => 'mymodule_custom_storage',
        'settings' => array(),
        'module' => 'mymodule',
        'active' => 1,
    );

    // Build record to update.
    $record = array(
      'id' => $field['id'],
      'storage_type' => $field['storage']['type'],
      'storage_module' => $field['storage']['module'],
      'storage_active' => $field['storage']['active'],
    );

    // Update the field storage.
    $primary_key = array('id');
    drupal_write_record('field_config', $record, $primary_key);
  }
}

/**
* Implements hook_field_update_field().
*/
function mymodule_field_update_field($field) {
  mymodule_field_create_field($field);
}

The best way to do this is to create the fields in your module that you need to use and at that time, set the storage for the field. It's cleaner than changing existing fields.


There are a number of ways you could do it, depending on how friendly you want the ui to be and how comfortable you are customising drupal.

I would look at the Field Collection module - http://drupal.org/project/field_collection. It should let you create a group of fields that can be treated as a single field.

ie you could create an 'Experience' field collection consisting of Title, Experience, Duration, Summary and whatever else you need. Then the end user should be able to add multiples of these if you set the field to allow multiple values.

I am saying should because I haven't directly used this module myself, in a similar situation I have created a custom form widget containing the multiple elements. Thats is potentially a more complicated exercise. You could see an example of what might be required there in the Examples for Developers module : http://drupal.org/project/examples


Drupal allows menu tabs on Views pages. Why, and why not on other kinds of content?

This functionality is built into the Drupal menu system but is not exposed as a configurable option through the web interface by Drupal core.  You would normally have to write some code that implements hook_menu to accomplish this.

Views happens to give a user interface for this functionality, so some people will take advantage of that to do things that maybe aren't best done in Views just because it lets them do it without having to touch code.  I should note that Page Manager and Panels also give you configuration that let you do this through the UI and that would be a better way to achieve this if you have pages that aren't naturally Views.


How to change the order in which Views SQL joins are executed?

You are looking for the following:
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
It will work roughly as follows:
You will find that there is a clauses array in your query object among others that will contains your restraints. Remove the particular element, and insert it into the correct order in the array. They will be executed 0 through N


How to pay with site credit in Commerce?

you can use user-points module with Commerce userpoints. they work nice togather.


How should I deal with Views URL parameter "page" in Google web master tool?

Try Nodewords module for Drupal 6 or Meta tags for Drupal 7.
These modules will allow you configure the NOINDEX and NOFOLLOW parameters for listing pages in order to get only 1st page in SERP.


Views Contextual filter: php code for getting the value from url

Though the solution you have implemented worked but my suggestion is to use the request_uri() instead of the $_SERVER['REQUEST_URI'] because of the following reasons:

$_SERVER['REQUEST_URI'] is only available on Apache, whereas request_uri() generate an equivalent using other environment variables.
Apache does nothing by default to sanitize the $_SERVER variables so directly using it without passing through the check_plain should be considered unsafe.

So its better to get the URL like this:

  $current_url = check_plain(request_uri());

Example: if the url is http://www.example.com/param1/param2/param3 than the $current_url will contain /param1/param2/param3.

Rest you can build the logic to get the last params, there are numerous ways of doing that.


Drush Omega Guard - "command could not be found" or "could not locate Gemfile"

Answer from the comments above, documented here per Molot's request:

In the case where your settings.php file is not in the 'default' folder, Drush needs you to specify --uri=site_name.com, unless it can determine the site to use via your cwd (e.g. if you have set your working directory to sites/site_name.com, as described in the question).  --uri is not necessary if you have a 'default' site, but it is necessary if you use any other name for your site folder, even if you only have one site in the Drupal installation.

Seems that the problem with finding the Gemfile was resolved by always setting the working directory to the theme directory, where the Gemfile was located.  Doing this while using --uri with Drush solved the problem.


Why are some menus created for authenticated users not displaying?

Some of the links are not visible to authenticated user, because the URL you provided to respective menu links are not accessible to authenticated user.

Example: Suppose menu link is Add Article and URL is /node/add/article. So here if authenticated user not having Article node add permission, then in such case Add Article will not be visible to that user.


How can I skip field validation if the field is hidden?

I've tacked a variation on this before and this was the only solution I found that didn't have problems of some sort.

The key is not to skip all validation as you may add security holes so you have to specifically skip required validation. - Specifically what I'm getting at here is don't use #limit_validation_errors.

You cannot stop drupal core from validating that required fields are not empty, so you have to make the fields not required when they get validated.

Note that this example will make all fields not required, so you'll have to add some logic to only do that for the fields you are interested in.
I couldn't add this because I don't have enough info about your setup.

In your form add this:

  // Add an after build callback so we can modify the form before validation.
  $form['#after_build'][] = 'MYMODULE_form_after_build';

Then add that after build function and a helper function:

/**
 * Form after build callback.
 *
 * We are using this to modify the form after it has been submitted,
 * but before it has been validated.
 * This means we can remove required flags for certain fields.
 *
 * @param array $element
 *   An associative array containing the structure of a form element.
 *   In this case the form.
 * @param array $form_state
 *   The form state array.
 *
 * @return array
 *   An associative array containing the structure of a form element.
 */
function MYMODULE_form_after_build($element, &$form_state) {
  // Check that the form has been submitted.
  if ($form_state['process_input']) {
    // Deal with required fields.
    _MYMODULE_remove_required($element);
  }
  return $element;
}

/**
 * Make elements of a form not required.
 *
 * This example function will make all required fields not
 * required.
 * In your case you want to only do certain fields so you will have
 * to add logic in here to only affect some fields.
 * You could do this based on field name or some other flag you have
 * set, or whatever.
 *
 * @param array $elements
 *   An associative array containing the structure of a form.
 */
function _MYMODULE_remove_required(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      _MYMODULE_remove_required($elements[$key]);
    }
  }
  if (!empty($elements['#required'])) {
    $elements['#required'] = FALSE;
  }
}


How do I display an array of entities from a controller?

Controllers need to return a render array. Let's imagine you process your articles for render in a new method renderMyPage() which you call from myPage() and pass your array of article objects.
If you're displaying multiple fields from the articles, you're best off building and configuring a view mode and then getting the view mode render array as described in this answer.
function renderMyPage($articleObjects) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

  $articles = [];
  foreach ($articleObjects as $article) {
    $articles[] = $view_builder->view($article, 'my_view_mode_machine_name');
  }

  return $articles;
}

If you want to render a single field from your article, you can get the render array for a field as described in this answer.
function renderMyPage($articleObjects) {
  $articles = [];
  foreach ($articleObjects as $article) {
    // You can pass a view_mode machine name or
    // an array of field configurations to view().
    $articles[] = $article->title->view();
  }

  return $articles;
}

Alternatively you can build your own render array, say to render the title as an h2.
function renderMyPage($articleObjects) {
  $articles = [];
  foreach ($articleObjects as $article) {
    $articles[] = [
      '#type' => 'html_tag',
      '#html_tag' => 'h2',
      '#value' => $article->title->value,
      // The other methods add cache tags automatically, but we need to add
      // cache tags manually here since we're building the array from scratch.
      '#cache' => [
        'tags' => $article->getCacheTags(),
      ],
    ];
  }

  return $articles;
}

Each of these examples returns an $articles array of renderable contents suitable as a return value from your myPage() method.


Drupal 6 and 7 use the URL of the page as the cache ID (the $cid, see drupal_page_set_cache()).  This should work.

$url = url('<front>',  array('absolute' => TRUE));
cache_clear_all($url, 'cache_page');

You will need to adjust the logic a bit if you can access the site through multiple URLs.


Problem assigning group members membership types other than default

You may want to use the rules module to accomplish that. It's pretty powerful and if you haven't used it before make sure to add it to one if your most favorite modules list. Here's some good advice that'll get you going  https://forums.acquia.com/acquia-products-and-services/dev-desktop/auto-assign-og-groups-user-roles


You should never use t() to translate variables, unless the text that the variable holds has been passed through t() elsewhere:

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/73#sec_translating_vars

In this case country_get_list() calls _country_get_predefined_list(), and inside this function country names are passed through t():

https://api.drupal.org/api/drupal/includes%21iso.inc/function/_country_get_predefined_list/7

So, if you have country strings translated in your database (as Molot says) translation should work.


Checking if referenced fields are empty in commerce product display node.tpl

you can render the field in advance, and save the html for your accordion.

the html variable will be empty if the field is empty:

$html = render($content['product:field_name']));
if (!empty($html)) {
  // accordion stuff
}


How to implement field formatters for entity properties

You could create a module providing a "property" field type. Store the the property to be formatted as an instance setting and then apply a formatter to that. It should be relatively straightforward. Relation module has a dummy field module which might help you in figuring out how to code this.


Is there a Drupal module that implements a (+/-) button with a counter textbox at the side?

There is already a module that gives you a vote up/down button, just like the one we have here on SE: https://drupal.org/project/vote_up_down.

  Allows votes on some drupal entities and provides the base for implementing votes on other entities.

It is still under dev for Drupal 7, but IMHO quite usable.  If you find any problems, it will probably be less work to help the developers fix those, compared to reinventing the wheel.


why filters are not working in view query alter?

I solved it by myself ,i have added condition for operator where i was doing mistake ,on first page load "IN" operator will work then "=" on selection of select list :

  function get_purchased_product_id() {
  //Get current user id
  $user_id = \Drupal::currentUser()->id();

  $uid = ($user_id ==1)? 267 :$user_id;

  $query_get_product_name =  db_select('commerce_order', 'c');
  $query_get_product_name->join('commerce_order_item', 'ci', 'c.order_id = ci.order_id');
  $query_get_product_name->join('commerce_product_variation_field_data', 'cf', 'ci.purchased_entity = cf.variation_id');
  $query_get_product_name->fields('c', ['uid']);
  $query_get_product_name->fields('ci', ['purchased_entity']);
  $query_get_product_name->fields('cf', ['product_id','title']);
  $query_get_product_name->condition('c.uid', $uid,'=');
  $query_get_product_name->condition('c.state', 'completed','=');
  $result = $query_get_product_name->execute();

  $arr_var=array();

  foreach ($result as $value ){
  $arr_var[]= $value->product_id;
   }
  return $arr_var;

 }

 function classroom_common_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

if ($view->id() == 'answer_key_form_management' && $view->getDisplay()->display['id'] == 'page_2') {
  //function call to get product id of purchased item by current user
  $arr_product_id = get_purchased_product_id();

  $product_target_id = Drupal::request()->query->get('field_akfp_select_product_target_id');
  if(!empty($product_target_id)){
     $arr_product_id = $product_target_id;
  }
  $operator = !empty($product_target_id) ? '=' : 'IN';

foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'node__field_akfp_select_product.field_akfp_select_product_target_id') {

          $condition = array(
            'field' => 'node__field_akfp_select_product.field_akfp_select_product_target_id',
            'value' =>  $arr_product_id,
            'operator' => $operator,
          );

        }
      }
    }
}


How can you use multiple lines in a text area?

Change the input format (just below the textarea) to Filtered HTML or Full HTML.


View doesnt work properly when logged out

A possible cause is that anonymous users don't have access to the content or fields. The inspect images aren't helpful to determine what permissions could be missing. In the UI, go to People > permissions and check that:

Anonymous users can see published content
If there are field-level permissions, anonymous can see all the fields involved in the view
There aren't restrictions to access the view (this is unlikely, the view wouldn't render at all)


Node Create/Edit Form - Multistep with dynamic fields

There are three module(may be two in your case), which can together to achieve what you want in D7. I have done this & client use it on daily basis..

Field Group

Multi Step

Then I have used Conditional Field module to have fields dependent on one another & it works great.

If you find any error in setup, please try the issue queue for patch.


Need to limit Commerce Shipping Condition to only fire if there are no items that do not match

Unfortunately, the way that condition was written, it only matches for, "Order contains any products from these categories." The logic you're looking for is, "Order contains only products from these categories." For that, you'd need to write a custom condition plugin. This would be a reasonable core feature request for Drupal Commerce and would apply for the other "contains" conditions as well ... which leads me to believe we might implement it as an "operator" select list on the condition itself.


What happens with modules and themes when I rebuild the cache?

To create a page Drupal needs to make several database queries. This can slow down websites with a lot of traffic. To make websites faster Drupal stores web pages in a cache.

Before Drupal 8, the common mantra was drush cc all (i.e. drush clear-cache). Now, in Drupal 8, it's drush cache-rebuild OR drush cr.

Caching is widespread in Drupal and creates many interdependencies. Improperly or incomplete cache flushing operations can cause the site to fatal error. In order to guarantee that old data is properly flushed and the site stays up and running,  drush cache-rebuild both rebuilds or re-bootstraps the Drupal site in    addition to clearing the cache

In-short, Drush's cache-rebuild command does the following:

Clears the APC cache
Bootstraps Drupal
Calls drupal_rebuild()
Clears the Drush cache (to maintain consistency with Drupal 7's drush cache-clear command)

If you would like to dig more into this check out https://github.com/drush-ops/drush/blob/659f67712adab143a2c921f9f23828782e414e8d/commands/core/cache.drush.inc#L263 at the end of the file, look at function drush_cache_rebuild().

Thanks!


How to union two views and pass on arguments

What you can do is to load and execute the $view_by_author view as you are doing but passing the by_year  arguments/contextual as this:
$arguments = [$view_by_year->build_info['parameter_you_need']];

$view_by_author = Views::getView('music_by_author');
$view_by_author->setArguments($arguments);
$view_by_author->setDisplay('block_1');
$view_by_author->preExecute();
$view_by_author->execute(); // or build, etc

I believe something like this would work for you.
Also, there is a module called Views Field View that might do what you are trying to do.


How do I run unit tests against datasets? (DrupalWebTestCase and DrupalTestCase)

Drupal 8 contains tests for verifying an upgrade from Drupal 7 would be executed correctly. Those tests basically create Drupal 7 tables, fill them with the required values, and call update.php.

You could need to create a upgrade/update test for your module, or you could test how a function behaves when it reads data from the database that are not in the format it expects.
In the first case, you would need to override the setUp() method, and avoid calling parent::setUp(); in the second case, you would fill the database table used from the test with the test data, call the function, and check what the return value is.

Apart from testing an update, I can think only of a case where a test would need to fill a database table, since:

If the table contains what entered from users, then the test should verify the form validation handler correctly shows error for wrong input
If the table contains data entered from another module, that module should be using a function your module implements, and the test should just check what the function does when it receives wrong/unexpected values

It could be your module is using data from a table that is created from another module, which is not exposing an API to load/save data in that table. In that case, if you know there is another module that enters unexpected data, you could need to verify your module is able to handle that data.


Undefined property error in custom module

Most likely  $router_item['page_arguments'][$key]->type is undefined.

Try with :

if (is_object($argument) && isset($router_item['page_arguments'][$key]->type) && in_array($router_item['page_arguments'][$key]->type, array('article', 'page'))) {

Same thing for that foreach loop. Just add an if isset() before that loop and you'll be ok.

if (isset($data['tabs'][0]['output']) ) {
    foreach ($data['tabs'][0]['output'] as $key => $value) {
        ....


I think you are looking for Field Permission module. It says :

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


I think you should write it like below code.
   /**
    * Implements hook_theme() to add the template definition.
    **/
    function lotus_theme($existing, $type, $theme, $path) {
      return [
        'lotus_template' => [
          'variables' => ['test_var' => NULL],
        ],
      ];
    }

In your controller file
public function build() {

    return array[
      '#theme' => 'lotus_template',
      '#test_var' => $this->t('Test Value'),
    ];

  }

Then in your lotus-template.html.twig
<p> This is the lotus template with a value of {{ test_var }} </p>

Source Define a custom template for module output


Render template file for view if no result?

Even though there is no results to display, views will call the appropriate theme functions and template files to render other information.

For example, If you go to views-view.tpl.php file you could see that views is rendering lot of information conditionally. For example if you have some exposed filters and there is no result for the execution, still view will call this template file to render the exposed form

If you specified No Results Behavior or exposed some filters you can check this.

Below is the sample code on how the views is rendering conditionally,

<?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

If there's nothing to render it will skip all the conditions and will not render anything.

If you want to override the way views is rendering the output, then you can create your own template for your view and place it in your theme directory. Template name should be something like this - views-view--.tpl.php


Rewrite labels on fields rendered via php

The label is usually in the #title key in each content member of the array, so something like

$content['field_product_reference']['#title'] = t('Something new');
print render($content['field_product_reference']);

should update it.

If not, try installing the Devel module and running dpm($content['field_product_reference']); to see whereabouts in the array the label value is.


How to enable modules through configuration?

This will not works because you are only saying to Drupal that your module is installed, but when you install a module there are other process that need to runs to import the configs and execute the .install functions.

But you can create a new module that will install all the other modules, create a .install file and add this inside:

/**
 * Implements hook_install().
 */
function MY_MODULE_install() {
  $modules_list = [
    'nbsp',
    'typogrify',
    'other_module',
  ];
  \Drupal::service('module_installer')->install($modules_list);
  drupal_flush_all_caches();
}

And then you only need to install this module that will install all the other modules.


Using Composer in a multisite installation

Short answer: you cannot do it The (new Drupal) Composer Way™ (still).
The composer is mostly project-oriented, however, based on the fact that they are projects of the projects, there is a chance that a composer.json could be made that would operate on a subsite level.
As far as we can go would be to hope that something will be done in the coming 9.2 release, somewhere south of Spring 2021. Until then, workaround and search for the best practices and other experiences (however sparsely) seems the only way
#2847218: Improve documentation around the multisite functionality
The (temporarily and incomplete) solution:
The only thing you are left with is to use the composer for the common, shared modules and to use drush or manually download modules and themes according to Drupal multisite structure:
-- sites
   -- site1
         -- modules           ----> site specific modules
            -- custom
            -- contrib
         -- themes            ----> site specific themes
            -- custom
            -- contrib
         -- files

Beside official documentation, you can read this post too: Drupal Multisite Setup: Are There (Still) any Valid Reasons to Use It? Should It Get Removed in Drupal 9.x?


Drupal 7 Domain Access Module Gives 500 error, WSOD for subdomains

OK, might as well add a tentative answer on this one.

Add your subdomains using ServerAlias within the same single VirtualHost, because they all have the same document root.

ServerName www.example.com
ServerAlias drupalx.example.com
ServerAlias drupaly.example.com

Fix the stray rewrite stanza in virtualhost scope.

e.g put it inside the Directory block.

<Directory "C:\xammp\www">
  <IfModule mod_rewrite.c>
    RewriteEngine on
    # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !=/favicon.ico
    RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
  </IfModule>
</Directory>

However, the latter isn't really needed if using the default .htaccess file in your doc root. Alternatively, remove .htaccess and copy its contents to the Directory block instead.


How to add another field collection instances on Add Form page load programatically

I had to do this recently on a product.  What I ended up doing is copying the instance of the field collection and then looping through and creating them.  If your session variable keys are numerical from 0 on then you dont need the $item_count.  In my case it was not so I could not simply use the foreach($value as $key => $val).

$my_loop = array(); // Array of items with your default values
$item_count = 0;
$field_collection_clone = $form['field_my_field_collection']['und'][0]; // Clone the field collection form element

//Loop through and create a new instance of the field collection form
foreach($my_loop as $loop){
 $form['field_my_field_collection']['und'][$item_count] = $field_item_base;
 $form['field_my_field_collection']['und'][$item_count]['field_my_field']['und'][0]['value']['#default_value'] = 'my default value';
$item_count++;
}


Theoretical limits of CCK (Field API) unlimited Multi Value Field - 170 000 values

No chance, hiding doesn't help, drupal will still load all values even if the field is hidden.

You could add the reference field on the item type and then load them through a view.

Or use the relation project, but it's ui might break too.


Keeping track of date when user profile has been updated

I used the Rules module for this. There is a condition like "User Profile Updated" or something like this which you can use. You have then the changed and the unchanged values as tokens available for example to e-mail somebody about the changes.


Disable profile field when module that created it is disabled?

I managed to accomplish it through code by setting the field instance:

    'display'       => array
      'default'     => array(
        'label'     => 'above',
        'type'      => 'hidden',
        'weight'    => '1',
        'settings'  => array(),
      ),
    ),


Duplicating drupal site without login info

One way of solving your issue would be to update super admin (first user) password pragmatically, by creating a temporary php file under Drupal root folder and add the following code to it then access it from a browser.

<?php

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// load super admin user
$account = user_load(1);

// save user password
user_save($account, array('pass' => 'admin'));

echo "Super admin password has been changed";

Make sure to replace admin with desired password