HTML tags removed during Views Rewriting

HTML tags, ugh, finally I understand your Q.

You can re-write your field using template files.

Go to /sites/all/themes/YourTheme/templates folder and

create views-view-fields--[view-name]--[machine-name].tpl.php

  For Example:

  If you view is called "Hello World" and the machine name is
  block_1

  then it would be views-view-fields--hello-world--block-1.tpl.php

Inside your template file you put:

<?php

$fields["path"]->content = '<loc>' . $fields["path"]->content . '</loc>';

$fields["field_image"]->content = '<image:loc>' . $fields["field_image"]->content . '</image:loc>' . '<image:title>' . $fields["field_image-atl"]->content . '</image:title>';

echo $fields["path"]->content;
echo $fields["field_image"]->content;

When you are working with template files, remember to clear/flush the cache to see the changes.

Now your HTML tags should not get removed.


How to print the paragraph field translation value in twig template

Normally it's a better idea to process (or even better let Drupal process) the field values in PHP.
If there is no other way you can use Twig Tweak and its newly added entity translation filter:
{% set entity = item.entity|translation %}
{{ entity.field_award.value }}

See https://git.drupalcode.org/project/twig_tweak/-/blob/3.x/docs/cheat-sheet.md#entity-translation


In my case, I was getting this in the apache error log:

.../sites/default/files/.htaccess: Option MultiViews not allowed here

Checking .htaccess, I found:

# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

Even though it's turning MultiViews off, it's still not allowed, and removing it fixed the CSS.
Enabling sites to set it int he global apache config would also resolve it.


Restrict access to a section of the site implemented by a custom module

If you implement hook_permission in your custom module, you can control the access of your client administration section.

Set up roles. You've done this already with the client role.
Implement hook_permission():

function MODULE_permission()
{
    return array(
        'access client administration' => array(
            'title'       => t('Access Client Administration'),
            'description' => t('Allow users to access client administration'),
        ),
    );
}

When you define hook_menu(), make sure you set the permissions accordingly:

function MODULE_menu()
{
    $items['client_administration'] = array(
        'title' => 'Client Administration Page',
...
        'access arguments' => array('access client administration'),
    );

    return $items;
}

Go to admin/people/permissions and set the permissions for 'Access Client Administration' to your client role.


How can I detect AJAX request inside Drupal?

For Drupal 7 there's nothing special in the API, just use plain PHP:

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  // AJAX request
}

For Drupal 8, the Symfony request object has a helper method:

// Example for brevity only, inject the request_stack service and call
// getCurrentRequest() on it to get the request object if possible.
$request = \Drupal::request();
$is_ajax = $request->isXmlHttpRequest();


How to create a block to remind special dates as stored in user profiles?

Step 1: Flag appropriate users/nodes

I assume you want to show a Block with such reminders (not "sending eMails" ...). To do so, use the Flag module to create a global flag, say you name it "Show Reminder", and then use the Views module to create a block of all "flagged content" (using this flag), similar to what is explained in Creating global flags and listing flagged content in Views.

Step 2: Use Rules to automate the flagging

You don't want to manually flag (and unflag) all such content every day, right? But that's what the Rules module is for: create a (1st) rule to "flag" whatever node, user, etc fits your criteria for "current day", and a similar (2nd) rule to later on "unflag" them again.

Step 3: Trigger both rules once a day

Use the Rules Once per Day module to schedule both rules described in Step 2.

Bonus Features

Handling invalid or missing dates

In case any node or user that "should" show up, doesn't show up on a specific date (since its date is missing or wrong), it's a matter of just flagging such node or user to have it also appear in the block.

Spotlights

For some node or user you for which you don't have a date, but which for some reason you also want to be shown, just flag it and it shows up also.

Creating reminders does not require edit permission

Flagging a node or user can be configured in such a way that you can separate its required permission from editor permissions. That opens possibilities for having various types of users contribute to producing such reminders (if that is what you'd want).


Turn location CCK 'city' field into taxonomy autocomplete field

What you can do is use hook_form_alter.
You will define an #autocomplete_path and use hook_menu to create a menu item for this path. In hook_menu, you will define a page callback. This will be a function that will return the list of cities from your taxonomy items.


How can I sort Labels in config entity list builder?

To answer my own question I guess.

Config entities list builder extends the ConfigEntityListBuilder class,
which comes with a few built in methods, among which

  /**
   * Loads entity IDs using a pager sorted by the entity id.
   *
   * @return array
   *   An array of entity IDs.
   */
  protected function getEntityIds() {
    $query = $this->getStorage()->getQuery()
      ->sort($this->entityType->getKey('id'));

    // Only add the pager if a limit is specified.
    if ($this->limit) {
      $query->pager($this->limit);
    }
    return $query->execute();
  }

To sort, in whichever you ones desires, the display list itself all that needs to be done is overwrite the function in the child class.

In my case it was something like this:

protected function getEntityIds() {
  $query = $this
    ->getStorage()
    ->getQuery()
    ->sort('notification_creation_date', 'DESC');

  // Only add the pager if a limit is specified.
  if ($this->limit) {
    $query->pager($this->limit);
  }
  return $query->execute();
}


Updates: keep panels pages, views, etc.. updated via hook_update_n?

Well, this can not be the best solution but it works:

function mymodule_update_7001(&$sandbox) {
  // Views.
  if (is_callable('views_save_view')) {
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_delete_view($view_object);
    }
    // Rebuild it.
    $views = module_invoke_all('views_default_views');
    foreach ($views AS $view_object) {
      views_save_view($view_object);
    }
  }

  // Pages
  module_load_include('inc', 'page_manager', 'plugins/tasks/page');
  if (is_callable('page_manager_page_save')) {
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_delete($page_object);
    }
    // Rebuild it
    $pages = module_invoke_all('default_page_manager_pages');
    foreach ($pages AS $page_object) {
      page_manager_page_save($page_object);
    }
  }
}

Basically just keep updated the views and pages definitions (views_default_views and default_page_manager_pages), the delete and rebuild them.

Obviously, this remove all customizations done via the Drupal's UI, so only do it for the views and pages you need to update!


I managed to grab just the child submenu of the current page. Each subtree has a getRouteParameters() fn that contains the node ID that it links to. I simply test if that route param node id == the current pages node id.

function mytheme_preprocess_page(&$vars) {
  if (isset($vars['node']) && is_numeric($vars['node']->id())) {
    $nid = $vars['node']->id();
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      array('callable' => 'toolbar_menu_navigation_links'),
    );
    $tree = $menu_tree->transform($tree,$manipulators);
    $subtrees = array();
    foreach ($tree as $element) {
      $link = $element->link;
      if ($element->subtree) {
        $routeId = $element->link->getRouteParameters()['node'];
        if ($routeId == $nid) {
          $vars['menu_children'] = $menu_tree->build($element->subtree);
        }
      }
    }
  }
}


1. Add Content: Link to Content field to your View . Your view fields will look as shown below.

2. Make sure that your Title field is outputted as plain text. In the Content:Title field settings uncheck the checkbox "Link to the Content". This is done because you'll use plain title text as a token for the link text. Exclude Title field from display, as it will be displayed later as an absolute link text.

3. Create settings for the absolute link output in Content: Link to Content field settings.

Open REWRITE RESULTS fieldset in Content: Link to Content field settings and check the following boxes:

✓ Override the output of this field with custom text (set {{ title }} as text)
✓ Output this field as a custom link
✓ Use absolute path


How to pipe output of "drush sql-dump" without warnings

Seems -q should do the job.

$options['quiet'] = array(
  'short-form' => 'q',
  'description' => 'Suppress non-error messages.',
);

Source: function drush_get_global_options


Add rule for a webform checkbox to autosend email after specified time

You will also need Webform Rules, but once you can react to the submission, you should have no problem getting this going. You'll need to schedule the rule to run in the future and will probably need to add a Rules Component containing the actions to run at that time.

In your triggered rule that reacts to the Webform submission, you need a condition checking if that checkbox was checked and an action that runs the Rule Component you defined earlier. You will want to pass the user object to it (or uid, or email address, or Webform submission - whatever you need) to make sure it works correctly.

I am using Drupal 7 terminology here, but this is achievable in Drupal 6 as well. Just replace "Rule Components" with "rule sets."


How to get the CID number of comments from comment table?

$result=db_query('SELECT cid FROM comment WHERE nid = :nid',array(':nid' => $node->nid));

Hope this helps you.


How to find a field name/column name of a field in database where I have only the label of that field?

You can derive the database table name by the host entity and the field name. The name schema is ENTITYTYPE__FIELDNAME

Views don't directly show the field name, but you can look at the entity's "Manage field" page to get the field name by label. (e.g. for nodes /admin/structure/types/manage/BUNDLENAME/fields)

Examples:

node__body
node__field_image
users__field_whatsapp
taxonomy_term__field_text

Exception:
Some special fields (like title or created) are stored as a column on the base table of an entity. Base tables follow the schema ENTITYTYPE_field_data, e.g.

node_field_data
users_field_data
taxonomy_term_field_data


You can use hook_preprocess_html() to override this value:

function MYTHEME_preprocess_html(&$vars) {
  $vars['head_title'] = 'Some other title';
}

The title for the content won't be affected by that, just the <title> tag.


field_get_items('user', $user, 'field_name') empty?

I was experiencing the same issue. field_get_items was always empty when trying to get a field attached to a user. The problem was that the $user object you get when you do a

global $user

isn't the full entity. So when you pass it into the field_get_items function, it doesn't match anything.

Do a full user_load on the $user->uid and THEN pass the resulting object to field_get_items, and everything should work.


As per @Andrew comment, instead what you have try printing your HTML start a var outside your foreach and then:

$template .= '<html>';

adding to it, then print it out after your foreach has finished looping.

In addition make an array outside the foreach, e.g.:

$newarray = array();

Try not using the entity_metadata_wrapper, as it seems like an extra layer of stuff to deal with.


Problem with showing custom html.twig content

I've tried this on my site and used main navigation and it worked. block--mainnavigation.html.twig

What you can check:

Of course check if you have some typo in file name, or try with
default navigation to see if it works.
https://www.drupal.org/node/2598914 Try to disable Twig cache while you are developing.
Try to use cache rebuild with Drush https://drushcommands.com/drush-8x/cache/cache-rebuild/

I don't think that you are doing something wrong, problem is with caching I believe.


Show page with child terms when clicking parent term

Follow these steps

Create a view
Add a relationship "Content: Tags", (Tags is vocabulary name I want to show content for)
Add a contextual filter "Content: Has taxonomy term ID (with depth)" (you can provide a depth of taxonomy term here to display content, if set to 0 it will show content tagged with that particular term id only, if 1 then that particular term id + its first child term content)
And provide proper value for this contextual filter.

Here is the screenshot of view I've created:

Hope this helps.


How to show contextual links buttons in templates with minimal markup?

In Drupal 8 the contextual links markup is still printed via the {{ title_suffix }} variable (D7: print render($title_suffix);).

block.html.twig (default):

{%
  set classes = [
    'block',
    'block-' ~ configuration.provider|clean_class,
  ]
%}

  {{ title_prefix }}
  {% if label %}

{{ label }}

  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}

So a minimal version would still work:

{{ title_suffix }}
{{ content) }}

Printed result for user without the permission "Use contextual links"

BlaBlaBlaContent

Printed result for user with the permission "Use contextual links"

    <button type="button" class="trigger focusable visually-hidden" aria-pressed="false">Open configuration options</button>

Configure block

Edit

Delete

BlaBlaBlaContent

The default formatting will be destroyed because the outer class .contextual-region is missing and it's defined like this in contextual.theme.css:

.contextual-region .contextual .contextual-links {...}
.contextual-region .contextual .contextual-links li {...}
...

So you have to overwrite (https://www.drupal.org/node/1876600) this file or copy the definitions in one of your theme css files and change for example like:

.contextual-region .contextual .contextual-links, .contextual .contextual-links {...}
.contextual-region .contextual .contextual-links li, .contextual .contextual-links li {...}

Or you place manually in the template or via JS ".contextual-region" into an outer dom element or print {{ attributes }} there.

Printed result:

        <button type="button" class="trigger focusable" aria-pressed="false">Open configuration options</button>

Configure block

Edit

Delete

    BlaBlaBlaContent

Remark: Without the upper .contextual-region the mouseover visibility of the contextual links icon is not working ...

Note: Current version of Drupal 8 is Beta 6 - so things may still change!


Error message when deleting folders/files on Maintenance mode

Rather than the two step deleting the folders and then uploading the new ones, I would recommend just copying over the old ones with new ones. You'll probably have to tell your FTP program to overwrite but when I upgrade in this fashion, I select all the files and directories except for sites folder and push them to the server.

When possible, I use the Drush tool via a terminal window as it is a much quicker and easier solution.


How to enable module when there is a WSOD (blank page)?

Using phpMyAdmin or any other database management software (or via command line mysql if you are comfortable with that), find the name of the module you wish to enable or disable in the system table. Set the status for that module to 0 for disabled or 1 for enabled.

mysql command:

UPDATE  `database_name`.`system` SET  `status` =  '1' WHERE  `system`.`name` =  'module_name';

phpMyAdmin screenshot:

I also recommend installing Drush on your server. This will allow you to execute commands like enabling/disabling modules, clearing caches, etc. from the command line, which is very handy in situations where you cannot access the Drupal admin because of a WSOD.


How do I set a cookie using $response->headers->setCookie() in a form submission handler?

You can't send a response from custom code in Drupal. You have to return it from a controller.

You can also set a response or add the cookie to an existing response in an event subscriber. In your case set the response in form submit, then Drupal does this for you in a core event subscriber:

$form_state->setResponse($response);

To avoid the empty page you probably want to fill the response with content or add the cookie to a redirect response to display a different page.

Don't $response->send()

To explain why not to send a response. When you find a code example for the Symfony component HttpFoundation sending a response, it isn't valid for custom code in Drupal. See the warning in this doc:

  This article explains how to use the HttpFoundation features as an
  independent component in any PHP application. In Symfony applications
  everything is already configured and ready to use. Read the Controller
  article to learn about how to use these features when creating
  controllers.

In addition the Drupal kernel is wrapped in stack middlewares using Stack/Builder. So sending a response can even be a security risk if you have for example installed a middleware providing security checks.


Create field collection item in drupal 7

I found the problem, it was related to the workflow of content publishing (specific to my site ). Field collection item is created after a user with required permissions approve the content.

The code in question works and could be helpful for anyone else trying to create a field collection item containing a geofield.


Is there a way module to tell if you're logged into Dev, Stage, or Production

Try Environment Indicator, it does exactly what you want.

  This module will help you to keep sane while working on your different
  environments by adding a configurable color bar to each one of your
  environments.

It also integrates nicely with Admin Menu.


Simplenews Scheduler Sending Newsletter Twice a Week

There is a way of solving it without Rules, you can use Simplenews Scheduler.

Simply create two different Simplenews nodes of the same Simplenews category. You can use the same views token (or whatever you use to fill in the content of the newsletter) in both nodes.

Then set one node to send on Sunday weekly, and the other on Thursday weekly.

This can be done because Scheduler is set per node, not per category, and also subscribers are subscribed to Categories, not nodes, so each time all of the subscribers will receive the news, no matter if Sunday or Thursday nodes happen to be sent.


Auto remove uber cart product attributes's option

Try to use Commerce Product Attributes module. I haven't use this module. But I hope you will get that you want.

  This module provides some enhancements to the Drupal Commerce
  attribute handling.

  The improvement contains:

  Attribute field for line item
  Edit option for attributes

Or

Try this Refer Link also if you will not getting any solution from above module.

Or

You can do this by adding below code to Ubercart Attribute module.

contributions/ubercart/uc_attribute/uc_attribute.module, line 831

uc_attribute_option_delete

function uc_attribute_option_delete($oid) {
  // Delete the class attribute options.
  uc_attribute_subject_option_delete($oid, 'class');

  // Delete the product attribute options (and the adjustments!).
  uc_attribute_subject_option_delete($oid, 'product');

  // Delete base attributes and their options.
  db_delete('uc_attribute_options')
    ->condition('oid', $oid)
    ->execute();

  return SAVED_DELETED;
}


Saving and retrieving value in hook_node_form_alter()

Unlike building a settings form in Drupal using system_settings_form(), you need to do more than define the form field so that it's processed. You need to define a submit handler so your custom field can be processed. In your hook_form_alter() add a submit handler:

$form['#submit'][] = 'myModule_form_node_form_submit';

Then define your submit handler to process the form value for saving.

function myModule_form_node_form_submit($form, &$form_state) {
  variable_set('node_uaid', $form_state['values']['node_uaid']);
}


How to add javascript with #attached in a node which contains a specific paragraph bundle

Try this code for attaching

$variables['#attached']['js'][] = 'myfile.js';

Or

$variables['#attached']['library'][] = 'myfile.js';


Update Webform Submission from subsequent form on confirmation page

Looks like you are you using the wrong function, rather then retrieving a single webform submission you are retrieving multiple entries.

$nid = 3389;
$webform = node_load(3389);
$sid = $form['sid']['#default_value'];
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submission = webform_get_submission($nid, $sid); // note function name
$email = check_plain($form['your-email']['#value']);
$submission->data[14]['value'][0] = $email;
webform_submission_update($webform, $submission);


It is possible to use Drush with a Drupal site that is running on a remote server that does not have Drush installed.  This is possible because the Drush commands drush rsync and drush sql-sync work by composing ssh commands; if you set up your site alias configuration carefully, then you can copy your site to a local machine to operate on it.

In order for sql-sync to work without Drush on the remote system, you must define the 'databases' and '%dump-dir' variables in your site alias.  Otherwise, Drush will try to use Drush on the remote system to look up these values.  See example.aliases.drushrc.php for more information.

Note that it is really useful to be able to at least run drush updatedb on the remote server, so that you can update your database after you rsync new code over. Of course you can do this through the GUI too, but Drush is faster.  The Resources page on drush.org lists some hosting providers that are Drush-friendly.


why is admin not bypassing restrictions at views?

In your 2nd screenprint, within "filter criteria", the last line of it is says "Content: Author uid (=aziz)". That doesn't seem to be correct ...

Make sure the filter criteria only has "Content: Author uid" without "Author user: current". And keep the ID blank for the author uid, because specifying the user will only refer to the nodes published by THAT user only.


How do I not cache dynamic content but cache everything else (or similar workaround)?

"unless there's a way to get Drupal to render a minimal uncached page without building any of the rest of the site"

There's the clue - yes, there is. This is what AJAX callbacks do, after all. In your menu callback you print the desired output instead of returning it, and return NULL. IIRC, the result won't be subject to page caching either, but if it is, you can use the cache exclude module to ensure it is not cached.


Set custom timer for Slick slideshow based on field value

Here's my final mrpeanut.js:

(function($, Drupal, drupalSettings) {
    Drupal.behaviors.mrpeanut = {
        attach: function(context, settings) {
            var slider = $("#slick-views-slideshow-page-1-slider");
            var slideTime = drupalSettings.slideTime;
            var nodeIdArray = []
            $('article').each(function(i){
                var nodeAbout = $(this).attr('about');
                var nodeID = nodeAbout.substring(6, $(this).attr('about').length);
                nodeIdArray.push(nodeID);
            });

            slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
                slider.slick('slickSetOption', 'autoplaySpeed', slideTime[nodeIdArray[currentSlide]], true);
            });
        }
    }
})(jQuery, Drupal, drupalSettings);


How to pass current loged in user id in Drupal view page settings

First you sure create contextual filter with default value "get default uid from url"(also if you want get logged in user you can get default value from logged in user) then test it in "preview" section. if everything work  in your views correctly try  clear the cache.
If not work update your question with snapshot if your contextual filter settings.


How to use hook_form_search_block_form_alter?

So What is the method to connect this all dots, from Hook name to what can we change with that hook.

There isn't one - each hook is different, has different input, different output, different contents, affects different parts of the system, and so on. You have to look for documentation contextual to what you're working with, each time you have something different.
In this case, you're working with a form, which means you should be referring to the Form API. From there it's an easy search to find information about #attributes:

Description: Additional HTML attributes, such as 'class' can be set using this mechanism.
Values: Any HTML attribute not covered by other properties, e.g. class (for control types), enctype (for forms).

It's basically an arbitrary pass-through of the key/value, so
$form['search_block_form']['#attributes']['foo'] = 'bar';

Will get you (e.g.)
<input type="text" foo="bar" />


How to reload page after ajax form submit

For the purpose of the question, an easy-ish way to do a redirect after ajax is with ctools and ctools_ajax_command_redirect

// In your ajax form submit callback
ctools_include('ajax');
ctools_add_js('ajax-responder');
// Path to redirect to
$path = 'node/12';
$commands[] = ctools_ajax_command_redirect($path);
// you can also use ctools_ajax_command_reload() –  xurshid29
print ajax_render($commands);
drupal_exit();

Note, it depends on ctools, which is a popular contrib module.


Webform2PDF doesn't display arabic characters

It solved, I just changed the font to 'DejaVu Sans' in Generate-PDF settings.


Drupal 7 Fields, when adding an existing field during content type creation, how to tell where else its used?

There's no UI for this anymore. The UI is in admin/reports/fields (h/t Clive)

Here's a good stack about how to find this info with drush:
Is there a listing of Drupal fields?

Or you can grab it from the database:

SELECT entity_type, bundle FROM field_config_instance WHERE field_name = '$MY_FIELDNAME'


How to use downloaded images, for specific field?

You need to get the file fid; you can use EntityFieldQuery.
Then insert/update the "file_managed" table, using code similar to the following one:

db_update('file_usage')
  ->fields(array('id' => $user->uid,))
  ->condition('fid', $file->fid)
  ->execute();


How to get plugin configuration through plugin manager?

The plugin manager is not responsible for storing the configuration, that happens somewhere else.

Typically plugin configuration is then stored in a config entity, either in a 1:1 relation (e.g. blocks) or 1:n (e.g. views, view/form displays, filter formats).

I'd suggest that you look at those modules to see how they work, block is probably one of the simpler cases in core. You can also ask more specific questions if you're stuck on implementing that


Dull Ax....

$path='';
$with_trailing_slash=$base_url . '/';

if (strpos($user_input, $with_trailing_slash)===0) {
  $user_input=str_replace($with_trailing_slash, '', $user_input);
  if (strpos($user_input, '?q=')===0) {
    $path=substr($user_input, 3);
  } else {
    $path=$user_input;
  }
} else {
  // this isn't on the local system so there is no way to figure it out
}

if ($path) {
  $normal=drupal_get_normal_path($path);
}


For Drupal 7, fetch the XML at https://www.drupal.org/node/3060/release/feed?api_version[0]=103 to get the release history. The first item's title contains the latest version.

<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xml:base="https://www.drupal.org/node/3060/release?
    api_version[103]=103" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Releases for Drupal core</title>
    <link>https://www.drupal.org/node/3060/release?api_version[103]=103</link>
    <description></description>
    <language>en</language>
      <item>
    <title>drupal 7.32</title>
    <link>https://www.drupal.org/drupal-7.32-release-notes</link>
    <description>...

If you want information for all major versions (including 8 and 9), you may simply use https://www.drupal.org/node/3060/release/feed. You are then required to go through the items until yo find a release for the major version you are looking for.


How to Pass argument from URL to field in Views

This is done using contextual filters. The easiest way to do it is to set up a "page" display by clicking Add+ on the views page. Give the page the URL of http://[path]/event/% (you may also have to try %.json depending on the exact call you are trying to make, the json files are known to drupal right?). The % gives you the argument you are looking for. Then you need to set up a Contextual Filter found under the advanced section of the view. Here you pick the field you are passing the number 4 or 4.json to and choose the correct settings. You may find that you need to pick Provide Default Value for this exact case and then use raw value from url or even php code and do some magic on the $argument (depending on exactly what it is you are doing).


You need to configure Drupal to connect to your new database.
Also, make sure you have copied all the dot-files (.htaccess) as well. You will realize using a version control system is faster than rsync (although rsync is much faster than copying all files again and again).

Site migration instructions are nicely said in this drupal.org article. It's a lengthy one, so I'm quoting the part that you probably need to fix your site from current state.

  Make changes to the “Database settings” section of the settings.php
  file, to ensure that they are pointing to the new database, with the
  right user (which may be different that the one you used on the old
  computer) and the right password. You may also have to adjust the
  “base URL” if you are moving between a sub-domain and a domain level.
  If you are moving the site to a new domain, or to localhost, also
  check that "$cookie_domain" is not set to your old domain.


How does Acquia Dev Desktop create the connection to the database?

Thank you all for your help and point me to the right direction !

I will give a detailed explanation because i believe this will benefit plenty of people with common error as mine !

Acquia Dev desktop 2, while creating/importing you website, will create a hidden file (loc_your_site_dd.inc) within its folders where the database connection code is located and then it will refer to that file by adding at the bottom of your setting.php file, few lines of codes similar to:

// <DDSETTINGS>

// Please don't edit anything between <DDSETTINGS> tags.

// This section is autogenerated by Acquia Dev Desktop.

if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL SETTINGS_DIR'] . '/loc_sitename_dd.inc')) {
require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_sitename_dd.inc';
}

// </DDSETTINGS>

Actually this is not a problem and this is how Acquia Dev desktop handle the database connection and other configuration codes.

However, if you are using Drush with your Drupal 8 website but you are using it from a Git Bash instead of using the built-in cmd inside Acquia Dev Desktop, you will be facing a problem similar to this one:

The drush command 'XXX' could not be executed.
[error] Drush was not able to start (bootstrap) the Drupal database.

The problem here is that Drush won’t be able to find the  which it was added to your sites settings.php file and so it will not be able to find a connection to the database and in result will display the above error.

SOLUTION:

The best solution here is to find the hidden file created by Acquia Dev Desktop which is usually in Windows is located at (*C:\Users\username.acquia\DevDesktop\DrupalSettings*) and copy and pasted all of its contents to your settings.php file and then from inside the settings.php file, delete the code  codes added by Acquia Dev desktop.

Doing so, now Drush will be able to find a connection to the database and all will be working as expected.


Do these people need to login to the website? Do they have to change those profile settings themselves? do you plan that those entities will interact on that page? If any of these is yes, than you probably want users.

In all other cases this is probably a no and you are good to go with content types/ custom entities.

for keeping a record of past positions, you might want to try out field collections, you could create a field collection with start, end, position for instance and allow n entries of it.


Search API Solr integration with fivestar (or similar) rating system (fascet and sort)

You can best create a new Entity property in a hook_entity_property_info_alter(), and add a custom field "rating" with a custom getter callback. Like so:

...
      $properties = &$info['flatrow']['properties'];
      $properties['my_indexable_rating_axis_1'] = array(
        'type' => 'integer',
        'label' => t('Rating axis 1'),
        'query callback' => 'entity_metadata_table_query',
        'getter callback' => 'rating_axis_one_get_properties',
      );
      return $properties;
...

Use it to extend the node entity. The getter callback is where you retrieve the value to be indexed,

function rating_axis_one_get_properties($entity, array $options, $name, $entity_type) {
  $value = $node->field_fivestar['average_rating']; // I made this up, check how to do it

  return $value;
}

Then index the field with Search API.


Display entityreference field in search-result.tpl

I solved this by using teaser view as my search result. My search-result.tpl file now looks like:

<li class="<?php print $classes; ?>"<?php print $attributes; ?>>

<?php $v = node_view($result['node'], 'teaser'); print render($v); ?>

</li>


Exclude node referenced from Related Views

THis things might be solved in many ways, but the 2 solutions which we can use is.

We can add entity reference filter in Filter section of view. Entity Reference Filter is a view of type entity reference, and it should return node id based on arguments, and in our parent view, we can apply condition, that is not one of.
We can add a contextual filter of NID, with option of provide default value >> fixed value, and under more section, we can check exclude checkbox. After that we can use hook_views_pre_view, to set the argument, if it is first contextual filter, then using $arg[0], if it is second contextual filter, then using $arg[1].


Responsive jcarousel doesn't resize images

I think JCarousel still uses 0.2.x version of the JCarousel library and the example you're refering uses version 0.3.3 of the library which brings wider responsive support. Since 0.2.x and 0.3.x are not compatible as one can read here https://github.com/jsor/jcarousel, I think it will be difficult to achieve the features of the 0.3.x library in the drupal module. Look at the roadmap on https://www.drupal.org/project/jcarousel


How to add only unrefered node of a content type in an entity reference field of another content type

The Entityreference unique sounds what you're looking:

  This modules adds a checkbox to an entity reference instance to enable a check for unique multiple entity reference fields. With this option enabled it is not possible to add one and the same entity to a multiple entity reference field.


What happened to the og-list view in organic groups?

I don't know why it was removed, but here's a sample view you can import and tweak as needed. To import, go to /admin/structure/views/import.

$view = new view();
$view->name = 'og_list';
$view->description = 'A list of all Organic Groups';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'og list';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'All Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
$handler->display->display_options['row_options']['links'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'group' => 'group',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'og-list';
$translatables['og_list'] = array(
  t('Master'),
  t('All Groups'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);


Render link in twig with 'entity:node/n' as uri in array

You can render a link with core's link function:

This helper function accepts as first parameter the text and as second parameter the uri
Examples:
{{ link(item.title, item.uri, { 'class':['foo', 'bar', 'baz']} ) }}

In your case, this might look like:
{% for link_item in my_settings.field_links %}
  <div class="field__item">
    {{ link(link_item['title'], link_item['uri']) }}
    // or
    {{ link("My link text", "entity:node/123") }}
    // or
    {{ link("My link text", "internal:/some/internal/path") }}
    // or
    {{ link("My link text", "route:my.module.route_name") }}
    // or
    {{ link("My link text", "https://drupal.stackexchange.com/") }}
  </div>
{% endfor %}

Alternatively, and preferably imo, you can just render the field from the config_page entity (as with any content entity).
For example, in your preprocess:
// Load your config page.
$my_config_page = \Drupal::entityTypeManager()
  ->getStorage('config_pages')
  ->load('my_config_page_identifier');
// Build the render array for my links per the config page's `default` view mode.
$vars['my_links'] = $my_config_page->field_links->view('default');

Then, in twig:
{{ my_links }}


What is faster: hook_form_alter or hook_form_FORM_ID_alter?

The hook_form_FORM_ID_alter is faster than hook_form_alter.

Modules can implement hook_form_FORM_ID_alter() to modify a specific form, rather than implementing hook_form_alter() and checking the form ID, or using long switch statements to alter multiple forms.

Form alter hooks are called in the following order:

hook_form_alter()
hook_form_BASE_FORM_ID_alter()
hook_form_FORM_ID_alter()

I hope this helps :)


Functional testing without using simpletest

I ended up working with Behat (http://docs.behat.org/en/latest/) and Mink for Behat (http://mink.behat.org/en/latest/) to write tests that emulated a user using a browser on my website.

However, I still needed Drupal integration for quick access to nodes, users, and roles.  I found this project (https://www.drupal.org/project/drupalextension) which incorporates Behat, Mink, and the Drupal API.  This allows me to write tests like this:

@api
Scenario: Logged out user can access the custom Landowner registration page
    Given I am not logged in
        And I am on the homepage
    When I click "Register here"
        And I am on "/register"
        And I click "Register as a Landowner"
        And I am on "/register/landowner"
    Then I should see "Landowner Registration"

Now I can test a Drupal site without the issues involved with Simpletest.


Export config, then you'll have the fieldset in the resulting webform's Yaml. Then simply copy the whole fieldset in the Yaml, paste it to somewhere else in the Yaml and rename the elements. Now import the config again and your elements will appear in the form.
Export, paste, rename, import. That's it.


How do you programatically create decimal fields in Drupal forms?

I can't think of a better solution than to use a standard textfield with the element_validate_number() validator:

$form['element'] = array(
  '#type' => 'textfield',
  '#title' => t('Title'),
  '#element_validate' => array('element_validate_number'),
);

If you need something more complicated than the is_numeric() that gets run by element_validate_number() you just need to provide your own validation function, or if you want to mess with the widget itself then create your own element type using hook_element_info()


Does Views RSS display deals with relationship

It sounds like you want the Views RSS module.  It will add a new plugin that will allow you to map arbitrary fields to RSS elements at the channel and item level.

So, if your view is fielded out with the proper relationships already, you can just add a new display, map the fields, and assign it to a path, all in about 10 min.

The help in the module is also excellent.


How to use view to display a list of nodes?

Install

Menu Node API

  Manages relationships between node ids and menu items.

and Menu Node Views

  The Menu Node Views module provides Views integration for nodes
  assigned to the menu system.

Create a view something like this:

View of Content (nodes)

Contextual filter:

Add a contextual filter of Content: Nid

Fields:

Content: Title, and exclude from display.
Menu: Link title (The link text used for the menu item.)

Format: Unformatted list, with settings of Grouping field Nr.1 -> Content:title

That should do it.

This is not the only module solution available so research others as well.


Found the issue the Language Selection Page module is causing the issue https://drupal.org/node/2283985. You can see the styles exemption in the code. For you I would add in the advagg and cdn paths to the language_selection_page_blacklisted_paths variable. You should find it under "Paths blacklist" on the admin/config/regional/language/configure/selection_page page.

Gotta run will add in the exact paths tomorrow, but it will be something like

  farfuture/*
  sites/default/files/advagg_css/*
  sites/default/files/advagg_js/*
  httprl_async_function_callback


Views Bulk Operations with Field Collection Item tokens

You can create a view of nodes, rather than field collections, then add the collection as a Relationship.

Your node tokens should now be available for application to the field collection fields.


Unanswered Questions only show for admins

Apart from the customizations you described (within your "customizations I have made ..."), you also seem to have customized the 2nd (last) filter that you're using: it says "(in Answered ...)", while in your exported view it shows the machine names of content type "Question" and content type "Answer". While the view shipped with the Answers module (disclosure: I'm a co-maintainer of it) uses ONLY the "Question" content type.

I suggest you adapt that 2nd filter back to how the shipped version looks like, i.e make that filter only check for nodes of content type "Question". And if you then need any other data (columns in your view) specific to the "Answer" content type, those should be made available via the 1st relationship (entity reference) you already have in place (and which still matches the shipped version).

I'm not yet sure if this is the only change you'll need, but at least it will get you closer to the view you're trying to create (depending on possible updates to your question, I might further improve my answer afterwards).

PS: I noticed you also turned of "aggregation" (another customization). Not sure (yet) if that has anything to do with your issue.


Do not put styling in pane title, move html/css in a template file, you can override next templates for that: panels-pane.tpl.php or views-view.tpl.php


Parsing bad dates automatically with feeds and date api?

I am not certain if Feeds can handle this, but if you are importing CSV files, maybe OpenRefine is the quickest fix.


What you want, is not (simple) with only views and CCK. That is because both lack a system for persistence in filters and arguments.

I can advise you to add a new module to your stack: Domain Access. This is a large module, which is not simple to configure right, but it sounds like it is the exact solution to your problem. It will allow you filter content, based on the domain (franchise) it is posted into.

The mayor concern with this module is its complexity. The second concern would be its use of Drupal's content access hooks and system. Modules like Domain Access, i18n, Organic Groups all use this system, which has very severe penalties for performance. IOW: Domain Access, or any access-module, will make your site notably slower and less performant.


I would do this with rules:

Event

After adding a product to the cart

Action

Add a product to the cart

Parameter: User: [site:current-user],
Product SKU: [other product
sku] Provides variables: Added product line item
(product_add_line_item)


Select an Image style depending on external/dynamic factors (theme region or other field content)

You could use Viewmodes (Layout Plugin / Display suite) in order to use different image styles.

E.g. Use a view with rendered viewmode "Teaser-Big" in Header and "Teaser small" in footer and pass an context argument to the view.


Display a message during form submission and prevent multiple submissions

This can be achieved by creating an AJAX form. If you fear that the max execution time of the server will be a problem you should look into batch operations as mentioned by Kevin.

An easier alternative is to add a custom JavaScript file and react on the form submission.

Alter the forms you want to behave as requested in a custom module. Use the #attached property to add your custom JavaScript file (in your custom module directory).

$form['#attached']['js'][] = drupal_get_path('module', 'MODULE_NAME') . '/MODULE_NAME.js';

Then add something like the following to your JavaScript file:

(function ($) {
  Drupal.behaviors.formSubmitFeedback = {
    attach: function (context) {
      // Get the forms we want to modify by form ID.
      var $forms = $('#form_id_x, #form_id_y'),
        submitCount = 0;

      // Make sure the form is only submitted once.
      $forms.once('submit-feedback').submit(function(e) {
        if (submitCount) {
          e.preventDefault();
        }
        else {
          var $submits = $forms.find('input[type=submit]');
          // Hide all submit buttons so that they can't be clicked twice.
          $submits.hide();
          // Add a class to the form so we can do some specific styling.
          $forms.addClass('submit-wait');
          // Add a wait message with throbber after the submit buttons.
          $submits.after('
' + Drupal.t('YOUR MESSAGE') + '
');
          // Make all input fields (except the submit buttons) readonly.
          $forms.find('input').not($submits).blur().prop('readonly', true);
        }
        submitCount++
      });
    }
  };

})(jQuery);

This piece of code hides the submit button and cancels later submits.
A message is added to the DOM with a Drupal throbber (depending on your theme). You may need some CSS to make it look nice. There will be a 'submit-wait' class on the form after submission.


Views does not show content if any of fields from relationship are empty

You can achieve your requirement by unchecking Require this relationship option on relationship field.


If you look at the View Source of the webpage in your browser you will see that the CSS says class=" ... grid-N ... " so part of the answer is that they are using a Grid based CSS framework to layout the node content.

This type of stuff is easily achieveable with Field Group, Display Suite or Fences to layout a content type in this fashion.


How do I make a form field go back invisble after I uncheck a radio button?

Hello try this ...

$form['field_prestation_walk']['#states'] = [
  'visible' => [
    ':input[name="field_prestation_type"]' => [
        'value' => 'walk'
      ],
    ]
  ];


Drupal 8: how to generate options based on Ajax callback

The below code is working well forme.

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  if ($selectedValue = $form_state->getValue('example_select')) {
    $arr = array('1' => 'Nice way', '2' => 'Good way');
    $form['example_select2']['#options'] = $arr;
  }
  $form_state->setRebuild(TRUE);
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand("#first", ($form['example_select2'])));
  return $response;
}


Create new content when an image is uploaded, using rules

In your conditions, add entity has field: web form > image field.

That should allow you to set a data value on your created node with that image.


After 1 week searching and trying things at home i decide to make a separate module for the form.

When i pass the code to a module all works fine with the same code.

I think for any reason Drupal needs to render form by his own, not forced like i was doing with the next code in a simple view:

$form = drupal_get_form('ajax_load_all_admins');
print drupal_render($form);

Hope this help, dont try to make Ajax calls inside a simple view like i tried.


So I mailed my hosting provider for some addition information about the server, the logs and such. And it turns out that they did not allow any traffic on port 587 except for traffic going to the google ip addresses. However google has recently changed the addresses for their smtp servers and the hosting provider did not.

So if there is anyone with a similar problem, I suggest you contact your hosting provider to see if they allow traffic to the google ip's on port 857 and if those ip's are correct.


How to fix my Rules Actions to copy data from geofield to geofield?

Debugging is the art of taking away all possible reasons that may cause your issue ... Read on for more details to find out which one it might be, and how to possibly solve it.

Option 1: After updating actually happens before updating

Have a look at the issue about "After updating existing content" runs before content is saved, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". Therefor I'm about sure this is not a bug, but simply how the Rules module works.

A possible compromise to avoid these kind of issues, is to transform what you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules Component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected).

Option 2: Add an extra Rules Action 'Save Entity'

Another cause of possible confusion is within the Rules module, where sometimes it gets tricky to "save entities". So possibly adding an appropriate "save entity" action (after the 2 Rules Actions you already have) may also help (if nothing else helps).

Option 3: Rules debugging

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging (further detailed below), but a Keep-It-Super-Simple technique I often use, is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think). If tis doesn't help, then there are typically 2 ways of more advanced debugging:

Rules Evaluation Log

Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).
Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the Rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


Each text format that you create has some different processing options.

If you select

  Display any HTML as plain text

Then the result is what you explained, where HTML code is escaped and displayed instead of having any effect.

Instead

  Limit allowed HTML tags

Can be used to limit the kind of html tags which are allowed, but if disallowed tags are used, they will not take effect.

It sounds like you are confusing the two.

Update

The text processing and input filters are not related.

You have filter called plain text, but you could call it anything, like super input field, pony or whatever. When you select filtered input, you get to choose which filter to use.

The other text formatting option is plain text. Selecting this means that you wont use any text filter, not even the one you might call plain text. The result of using this kind of text processor is that the text will be rendered as plain text.


Passing multiple array to drupal_json_output() is not giving correct output in jquery ajax

To setup a service which returns a json formatted data, you should set the delivery callback to drupal_json_output. This will only output the service data and not all the HTML defined in your theme.

For example

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

    $items['service/ajax'] = array(
        'title' => t('Ajax service'),
        'page callback' => 'YOURMODULE_ajax',
        'delivery callback' => 'drupal_json_output',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function YOURMODULE_ajax()
{
    for($i = 0; $i < 10; $i++) {
        $arr = array('message' => 'test'.$i, 'data' => 'data'.$i);
        $arrs[] = $arr;
    }

    return $arrs;
}


In Drupal 8, /modules and /themes are already in the root for you. Within them, you can also do /contrib and /custom for further organization.

I have never put files in the root, but I suppose you could as long as you ignore it with git.

See this answer for more detail: https://drupal.stackexchange.com/a/84851/57


Is there any way to display a taxonomy sorted by another taxonomy?

I would look into the Flag module.  With it, you could flag certain content and then use Views to show just that content. You could also create different flags for different sections, etc.


With imagecache_actions module you have several actions. One of then is "File Format switcher" so you can serve JPEG instead of png without converting the source images.

For more information:
https://www.drupal.org/project/imagecache_actions


Nesting forms in other forms is not valid in html.
see this post
html nesting forms in forms

You can always try calling the form directly via the actual form function instead of via drupal_get_form since the function returns a valid array of form elements.
you'll have to somehow compensate for the missing hook_form_alter and hook_form_FORM_ID_alter.

Note I haven't actually tried this, so I'm not sure how it will react on the empty $form/$form_state params.

That already gets you all the fields in a dynamic way.
Perhaps you can build a similar work around calling the submit/validate handlers directly too.


This a improved version of your code

  if ($form_id == 'user_login') {
        $form['#validate'][] = 'wemusic_user_login_validate';
        $form['#submit'] = array();
        array_unshift($form['#submit'], 'wemusic_user_login_submit');
    }

function wemusic_user_login_validate($form, &$form_state){
    $username = $form['name']['#value'];
    $user = user_load_by_name($username);
    if ($user && $user->status != "1"){
            drupal_set_message("Baba Taid kon bad boro to",'error');
            drupal_goto('registration/confirm', array('query'=>array(
                'user'=>$username,
            )));
    }
   else {
        drupal_set_message("Sabenam nakarde mikhay beri to akhe amo ?!!!",'error');
        drupal_goto('user/register');
    }
}

When you are in user_login and user is going to login don't empty $form_state  with $form_state = array(); Let Drupal Handle it's way to log on user  you just check what you want before it.

This will work for you , but I think is better when the situation is not satisfied in validator set error and set a destination variable on $form_state  ( maybe $form_state['redirect'] or your custom $form_state['my_redirect'] )  then in form_alter  check if  your error exists redirect to that destination with Drupal_goto.

Any way mentioned code ( up code) satisfy what you want.


One way is to preprocess the menu and inject it as a variable, then print the variable:

use Drupal\block\Entity\Block;

/**
 * Implements hook_preprocess_menu().
 */
function mytheme_preprocess_menu(&$variables) {
  $block = Block::load('myblock');
  $variables['myblock'] = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
}

Then in your template:

{{ myblock }}


How to redirect to another URL if visitor is anonymous when clicking a menu?

you can use Menu per Role module:

  This module allows you to restrict access to menu items1 based on user
  roles. It depends on the Drupal core menu.module—just activate both
  modules and edit a menu item as usual. There will be a new fieldset
  that allows you to restrict access by role. The fieldset also appears
  in the node edit form.


Migrating a Drupal 7 domain to another domain while keeping dynamically generated URLs intact?

If the two websites should be identical but available at separate domains and you use relative URLs throughout your site this is actually quite simple. This is assuming you want all links available at both domains.

Direct the new domain name to point your Drupal install.

Depending on your system configuration there are several ways you may need to do this.  If you have a dedicated IP you can simply point your domain to the appropriate IP and ff you use virtual hosts you may need to setup a symbolic link.

ln -s /var/www/example.com /var/www/newdomain.com

All relative URLs should inherit the currently loaded domain name.

I believe for this to work though you will need to leave $base_url commented out in settings.php.

/**
 * Base URL (optional).
 *
 * If you are experiencing issues with different site domains,
 * uncomment the Base URL statement below (remove the leading hash sign)
 * and fill in the URL to your Drupal installation.
 *
 * You might also want to force users to use a given domain.
 * See the .htaccess file for more information.
 *
 * Examples:
 *   $base_url = 'http://www.example.com';
 *   $base_url = 'http://www.example.com:8888';
 *   $base_url = 'http://www.example.com/drupal';
 *   $base_url = 'https://www.example.com:8888/drupal';
 *
 * It is not allowed to have a trailing slash; Drupal will add it
 * for you.
 */
 # $base_url = 'http://www.example.com';  // NO trailing slash!

Using this method I rarely have to make custom edits. This includes views output. Just make sure you always use relative URLs.

If you want the content split up between the sites or want to make change the theme or layout you may need to do something a bit more complex.

There are other more robust and complicated ways to separate out your content. A few modules and concepts that come to mind include...

Domain Access
Multi-Site (Added for reference, does not meet your requirements.)
Virtual Sites (Disclosure: I haven't used this.)
Duplicate your sites (As you mentioned in your question)

I will try to update my answer to be more appropriate with your feedback. Feel free to add details about your hosting environment and how and if the content will be split.


@pvorb, you can also use EntityFieldQuery.  See the first comment on https://api.drupal.org/api/drupal/includes%21file.inc/function/file_load_multiple/7 for an example.  Something along the lines of:

$filename = 'myfirstpony.png';
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'file')
  ->propertyCondition('filename', $filename)
  ->execute();
// if you are guaranteed there is exactly one result, then:
$file_object = reset($result['file']);
$fid = $file_object->fid;
// but beware you might get 0 or many results

If you have more information -- such as the path (from which you can generate a URI) -- then change the query condition to something like ->propertyCondition('uri', 'public://path/to/myfirstpony.png').


Only show view tab for current user profile

set your view path to:

user/%/listings

Add a contextual filter of: author uid, and set 'WHEN THE FILTER VALUE IS NOT IN THE URL' to User ID from logged in user.

Add a menu 'Menu Tab'.

For access you have various options. Here is a simple one.

Install Views PHP and set access to PHP, then add this bit of code in there:

global $user;
return $user->uid == arg(1);


How to add additional information to shipping methods?

I know this is an old thread, but I encountered the same problem. So in case you have the same issue:

This isn't really a commerce question, rather a general one.

There is a hook, where you can simple add new fields to an existing entity: HOOK_entity_base_field_info

So in this case:

/**
 * Implements hook_entity_base_field_info().
 */
function yourmodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'commerce_shipping_method') {
    $fields['shipment_description'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Description'))
      ->setDescription(t('The shipping method description.'))
      ->setRequired(FALSE)
      ->setTranslatable(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);
    }
}

This will add a simple textarea field type, but you can add any field type you like.

This will only add the field visually, you must also do an update to your database table. In a .install file, do something like this:

/**
 * Implements hook_install().
 */
function hartmann_add_field_install() {
  $entity_manager = \Drupal::entityManager();

  $desc_definition = $entity_manager->getFieldStorageDefinitions('commerce_shipping_method')['shipment_description'];
  $entity_manager->onFieldStorageDefinitionCreate($desc_definition);
}

/**
 * Implements hook_uninstall().
 */
function hartmann_add_field_uninstall() {
  $entity_manager = \Drupal::entityManager();

  $desc_definition = $entity_manager->getLastInstalledFieldStorageDefinitions('commerce_shipping_method')['shipment_description'];
  $entity_manager->onFieldStorageDefinitionDelete($desc_definition);
}

Then reinstall your module.
In more recent versions of Drupal 8, entitymanager is deprecated. I don't now the updated code for .install, but some research and you will find it.


getting the value of line item entity field in CommerceLicenseRemoteBase class

Generally you'd do something like this:

$wrapper = entity_metadata_wrapper('commerce_license', $license);
$wrapper->PROPERTY_YOU_WANT->value();

(See here for more detail: https://www.drupal.org/documentation/entity-metadata-wrappers)

You could always ask in the issue queue for the module:

https://www.drupal.org/project/issues/commerce_license?categories=All


How to sort translation under Translate tab?

Have you checked on "admin/config/regional/language"?
There you can sort languages and the order is reflected throughout the system (e.g.: the language switcher block)


Inserting search terms into a search input in Drupal 7

If you're using Apache Solr (http://drupal.org/project/apachesolr) you can use

$query->getParam("q")

in your search-result.tpl.php template.

Otherwise, you can use the slightly modified version of the function above:

function get_current_search_terms() {
// only do this once per request
static $return;
    if (!isset($return)) {
        // extract keys from path
        $path = explode('/', $_GET['q'], 3);
        // only if the path is search (if you have a different search url, please modify)
        if(count($path) == 3 && $path[0]=="search") {
            $return = $path[2];
        } else {
            $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
            $return = $keys;
        }
    }
    return $return;
}

edit: no need for check_plain here


node/add page shows 2 of every type. How do I fix this?

I've fixed it.

The problem was that the table menu_links had duplicates in it for the content types.  How they got there, I have no idea.

The fix is to find the menu_links table using phpMyAdmin and search for the links there were duplicates of (title link_field using LIKE %...% operator). Then simply, drop them from the table.  The reason is because the node/add page is just a page (or Overlay) view of the items in the "Add content" menu.


Custom module stopped executing after 30 seconds

You need write batch operation:

  Functions allowing forms processing to be spread out over several page
  requests, thus ensuring that the processing does not get interrupted
  because of a PHP timeout, while allowing the user to receive feedback
  on the progress of the ongoing operations.

http://api.drupal.org/api/drupal/includes%21form.inc/group/batch/7


how to edit multiple menu itmes on menu management page

i dont think there is a module that lets you do bulk menu item edits. another option you might want to try is just show the weights of each item and manaually adjust it in that manner so you dont have to drag each one.


This is probably what's happening...

node_add() calls drupal_get_form() internally, which finalises the form and commits submit/validate handler data to the cache.
You're modifying the data in the form array after it's been saved to cache.
When the form submits, the page reloads and the API grabs the cached submit handlers from the store. As your submit function was never saved alongside that data, the API doesn't know about it.

You should use hook_form_alter() as already noted by Jimmajamma in the comments, then you won't have this problem at all.


Where are the primary and secondary tab blocks?

They are available under other names (I think one is called "Tabs") when you used the the minimal installation profile.

But you can import the blocks by entering the code of the files

profiles/standard/config/install/block.block.seven_primary_local_tasks.yml
profiles/standard/config/install/block.block.seven_secondary_local_tasks.yml

into the Single config import located at

admin/config/development/configuration/single/import

(this requires the config management module to be enabled)


Unique Identifier of Every Drupal User Instance

If you want to uniquely identify browsers, Drupal tracks browser sessions via the sid & ssid column in its sessions table.

If you're looking to uniquely identify computers, you could try the IP address manager module.

  IP address manager records user IP addresses, and allows admins to
  view which IP addresses have been tracked against a user, and which
  users have been known to use a certain IP address. This can be
  currently used to identify duplicate accounts.

  The aim of this module is to provide a way to identify a user when
  they are not logged in to provide some action or context to their
  presence by maintaining lists of users for some purpose - such as, but
  not limited to, banning them.

The caveats with this approach is, depending on the network setup between the client & host, you might get false duplicate IP addresses for users (e.g. a home network router using NAT).


How do I add description and keyword to the front page?

In drupal 6 I used Nodewords which allowed you to set meta tags on the front page as a configuration. In D7 this has been replaced by Meta Tags which may do the same thing or you.


Looks like it was an issue with the Entity Reference module after all.

This site is part of a multi-site setup that was using an older version of Entity Reference which I was hesitant to update due to potential repercussions. After updating the module, everything is working as intended.


Trying to access and print the values from the fields within Paragraph

Here's what worked for me to manually get parts of a field in a paragraph template.

This is in a field template for the actual paragraph, so for me field--field-paragraph.html.twig. I have an image field with the machine name field_image. This prints just the alt text of that image.

{% for item in items %}
  {{ item.content['#paragraph'].field_image.0.alt }}
{% endfor %}

I looked here for working with paragraph templates: https://www.drupal.org/project/paragraphs/issues/2662766#comment-12528934 and here for general drupal 8 field-getting: https://blog.usejournal.com/getting-drupal-8-field-values-in-twig-22b80cb609bd


Creating a product page with a template file

You should start off with copying the template from the Commerce module /modules/contrib/commerce/modules/product/templates/commerce-product.html.twig:

{#
/**
 * @file
 *
 * Default product template.
 *
 * Available variables:
 * - attributes: HTML attributes for the wrapper.
 * - product: The rendered product fields.
 *   Use 'product' to print them all, or print a subset such as
 *   'product.title'. Use the following code to exclude the
 *   printing of a given field:
 *   @code
 *   {{ product|without('title') }}
 *   @endcode
 * - product_entity: The product entity.
 * - product_url: The product URL.
 *
 * @ingroup themeable
 */
#}

  {{- product|without('variation_attributes') -}}

You can then adjust the display according to your custom fields, so something like:

  {{ product.field_header }}

      {{ product.body }}

  {{- product|without('field_header','body') -}}


Get file field alt text value using entity_metadata_wrapper

The file object does not contain the image metadata (Title, Alt,..). You must load the parent node to which the image is attached.

For example to get the Title of the 3rd image in the field "field_image" you would use:

$obj = entity_metadata_wrapper('node', $nid);
$obj->field_image[3]->title = $data;

Note 1: you do not have to load the node object first - the $nid variable can be the node id (entity_id)

Note 2: You should use the dpm() function to inspect the entity instead of var_dump. If you want to see also values of properties in the inspected entity, you can use a custom function. Google _wrapper_debug function to get it.


Drupal 7, Entity Reference user autocomplete field

Set up a view for the autocomplete.

You can use this tutorial: http://speaksdrupal.com/blog/custom-entityreference-handlers-using-views

Then add that as the view to use for autocomplete.

http://screencast.com/t/8m0O7F8zV

Whatever fields are searched will show up in the drop down.  So if you remove e-mail from the list of fields searched, it won't show up in the drop-down.


sure you have to use node reference
I think you need a node reference in efforts and objectives to select users or group so you need a node reference to a view (you can reference to a view it should not be node)

the same user/Group make a view reference to objects and efforts

If you have any problem make a comment


finally I managed to send the fields I need from the node through to post in the view send php code, creating a variable to calculate the node id and then use that variable in the token

<?php
$var=token_replace('[current-page:url:args:value:1]', array('node' => $node));
?>

[aet:node:<?php echo $var; ?>:title]

This is the list of modules:

tokens,
token filter,
views send,
token tweks,
Advanced Entity Tokens,
mime mail,
mailsystem,
phpfilter


Navigate to

  admin/people/permissions

and check if u have permissions for authenticated user.

Do you using the field permissions module?


How to ignore default roles in drupal roles

If you call user_roles(TRUE), the function will not return the anonymous user role.

Drupal always sets the role ID for anonymous user role, and the authenticated user role to the value of the constants DRUPAL_ANONYMOUS_RID, and DRUPAL_AUTHENTICATED_RID.

The following code is executed by user_install() in Drupal 7, and similar code is executed by system_install() in Drupal 6.

// Built-in roles.
  $rid_anonymous = db_insert('role')
    ->fields(array('name' => 'anonymous user', 'weight' => 0))
    ->execute();
  $rid_authenticated = db_insert('role')
    ->fields(array('name' => 'authenticated user', 'weight' => 1))
    ->execute();

  // Sanity check to ensure the anonymous and authenticated role IDs are the
  // same as the drupal defined constants. In certain situations, this will
  // not be true.
  if ($rid_anonymous != DRUPAL_ANONYMOUS_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_ANONYMOUS_RID))
      ->condition('rid', $rid_anonymous)
      ->execute();
  }
  if ($rid_authenticated != DRUPAL_AUTHENTICATED_RID) {
    db_update('role')
      ->fields(array('rid' => DRUPAL_AUTHENTICATED_RID))
      ->condition('rid', $rid_authenticated)
      ->execute();
  }

The following code works also in Drupal 5; the $roles array will not contain information about the anonymous user, and the authenticated user roles.

$roles = user_roles(TRUE);
unset($roles[DRUPAL_AUTHENTICATED_RID]);


Changing product price depending on node field in commerce node checkout

Ohhh!!!!!!!!

Power Of Rules

 { "rules_update_amount_female" : {
    "LABEL" : "Update amount Female",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Update amount" ],
    "REQUIRES" : [
      "rules",
      "commerce_line_item",
      "commerce_product_reference",
      "commerce_cart"
    ],
    "ON" : {
      "commerce_product_calculate_sell_price" : [],
      "commerce_cart_product_prepare" : []
    },
    "IF" : [
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item" ],
          "field" : "commerce_node_checkout_node"
        }
      },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-node-checkout-node" ],
          "field" : "field_ap_gender"
        }
      },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-node-checkout-node:field-ap-gender" ],
          "value" : "Female"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : "500",
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}


Add description to each entity reference

If you are looking for a code solution, you can do this in a custom field type, see this answer https://drupal.stackexchange.com/a/231162/47547.

If you want to do this in UI, you can use Field Collection or Paragraphs to bundle the two fields entity reference and description.


data export import module how to keep alias drupal

The solution i did is created gradle script that import/exports url as following:

         task exportUrl(type:Exec){
            doFirst{println "exporting Urls..."}
                executable "sh"
                args "-c", "mysqldump -u ${user} -p${pass} ${db} url_alias>sites/default/files/data_export_import_${view}/url_${db}_import.sql"
         }

 task importUrl(type:Exec){
     doFirst{println "exporting Urls..."}
         executable "sh"
         args "-c", "mysql -u ${user} -p${pass} -h localhost ${db}<sites/default/files/data_export_import_${view}/url_${db}_import.sql"
  }

it works well because i can also use drush to do the node import/export in the gradle script as well.

            task exportNodes(type:Exec){
                   doFirst{println "exporting Nodes..."}
                       executable "sh"
                       args "-c", "drush dei-ex nodes --content-types=address,article,blog[other content types]"
                }

task importNodes() << {
       def dir = new File("sites/default/files/data_export_import/nodes").list().toList()
       for (fileName in dir ) {
              println "ipmorting file ${fileName}..."
                    exec {
                        executable "sh"
                        args "-c", "drush dei-im nodes --file=${fileName}"
                    }
       }
}

I hope its useful for anyone


Having a field output custom markup when empty

This is what I eventually did to get it to work.

function MY_MODULE_entity_display_build_alter(&$build, $context) {
  $view_mode = $context['view_mode'];
  $object = $context['entity'];
  if (empty($build['field_machine_name']['#field_type'])) {
    $field = 'field_machine_name';
    $build['field_machine_name'] = global_events_faux_element($build, $field, $view_mode, $object);
  }
}

function MY_MODULE_faux_element($build, $field, $view_mode, $object) {
  $element = array(
    '#theme' => "field",
    '#title' => "Field Name Here",
    '#label_display' => "hidden",
    '#view_mode' => $view_mode,
    '#language' => "en",
    '#field_name' => $field,
    '#field_type' => "text_long",
    '#field_translatable' => FALSE,
    '#entity_type' => "node",
    '#bundle' => "bundle_name",
    '#formatter' => "smart_trim",
    '#is_multiple' => FALSE,
    '#object' => $object,
    '0' => array(
      '#markup' => "&NoBreak;",
    ),
    '#weight' => 2,
  );
  return $element;
}


Found the error: the problem is that I'm not resetting $context['sandbox']['file_pointer_position'].
This causes batch pointer start reading the CSV file in the wrong position.
To correct this, it's enough to add

$context['sandbox']['file_pointer_position'] = 0;

to the check for EOF

if (feof($file_handle)) {
    // complete the batch process
    $context['sandbox']['file_pointer_position'] = 0;
    $context['finished'] = 1;
    // end loop
    break;
}


In D7, Where can you go to get a list of Access Arguments to be used with user_access()?

You can get a list of arguments for the site by running this in the terminal:

drush sqlq "select distinct(permission) from role_permission \G"

Make sure you clear cache after making permission adjustments. As my changes weren't showing.


How to manipulate different regions from a module

If you want to exactly put content in $page['sidebar_first'], then you can implement hook_page_build() or hook_page_alter(). The difference between the hooks is that the latter is used when the module needs to alter some elements added by another module with hook_page_build() as the first hook is executed first.

Examples of hook_page_build() are the following functions.

function toolbar_page_build(&$page) {
  $page['page_top']['toolbar'] = array(
    '#pre_render' => array('toolbar_pre_render'),
    '#access' => user_access('access toolbar'),
    'toolbar_drawer' => array(),
  );
}

function dashboard_page_build(&$page) {
  global $theme_key;

  if (dashboard_is_visible()) {
    $block_info = array();

    // Create a wrapper for the dashboard itself, then insert each dashboard
    // region into it.
    $page['content']['dashboard'] = array('#theme_wrappers' => array('dashboard'));
    foreach (dashboard_regions() as $region) {
      // Do not show dashboard blocks that are disabled.
      if ($region == 'dashboard_inactive') {
        continue;
      }
      // …
    }
    // …
  }
}

As alternative, your module could define a block, but in that case, the block will be placed in the region set by the administrator users (or any user with the right permission), which could be place the block in a different region. If there isn't a reason to place the content your module is adding in a specific region, then I would rather opt for implementing blocks.


The final solution was much easier than i could possibly hope for.

I ended defining my own hooks and allow the sub-modules to implements the changes using said hook,s after checking the role of the user.
Using the example above, it became:

function sub_asl_info_alter( $page, $id)
{
  if( has_role('sub'))
    $page->content .= sub_asl_dip_info( $id);
 }


Imported site doesn't displays CSS styles

Make sure you've properly configured Temporary Directory inside Admin => Configuration => Media => File System, and check if "Public File System" and "Temporary Directory" have valid permissions to them. Once confirmed, clear site cache.

If not required you can also disable CSS Compression by navigating to "Admin => Configuration => Performance". So they will be accessed directly for there original location.


Try the examples module:

  This project aims to provide high-quality, well-documented API
  examples for a broad range of Drupal core functionality.

  The Examples project contains many modules which hopefully illustrate
  best practices for implementing various Drupal APIs. These modules can
  be enabled individually, and will typically add menu items to your
  site, which should guide you through their features. You can then look
  through the code to see what they are doing.

It has a drupal 7 & 8 entity example in which has a test as well.


How to add the relationship for tittle of content type of other in view

You need to relate the two content types somehow. One of the most popular ways of doing it is using the module entity_reference.

After you install the module, create a field of type "entity_reference", and by then you should be able to add a relationship in your view using this field, allowing you to use all fields of the second content type on the primary content type's view.


After one day search i'm found solution in
https://api.drupal.org/api/examples/form_example!form_example_tutorial.inc/function/form_example_tutorial_9/7
this example adds default values so that when the form is rebuilt, the form will by default have the previously-entered values.


How to have a 'Has Photo' (true or false) views filter

You definitely can do that in D7/V3.3. Just add a filter field that reads like: Content: IMAGE_FIELD_NAME:fid (not empty)


What is difference in the referencing entity options while adding a relationship in a views?

Lets say that Content A references Content B via an entity reference.

Content B is the Referenced Entity, while Content A is the Referencing Entity.

It really depends on what you are trying to see.  Say for example you pull a view of all content type B but want data from content A.  In that case you would use Entity Reference: Referencing entity.  If you have Content A and want data about Content B you would then use Entity Reference: Referenced Entity.


Twig/variable support in Custom block HTML

You can't use twig variables in the body field of a block (or a node). But you can use tokens. Install the modules Token and Token Filter. You need to add the token filter to the text format you are using in the body field.


Programmatically create node using feeds

From the description what I understand is that you are trying to create a node with all the contents from the feed except the Title which you have set manually.

You have created a feed which would run when you create a node of the type "boardgame" with an HTTP Fetcher.

The way feeds work in this case is when you create the node with the attached feed. It creates a node for the feed itself and also creates additional nodes with the contents in the feed. So in effect the feed is not meant to update the node executing the feed but to create additional nodes from the feed itself. And I guess that is happening without any issue in your setup.

To achieve what ou want to do you can install the following module

Feeds Self Parser

What this does it to update the node being created from the feed it self and not create another node instead.

Note : You might have to clear cache for the module to work other wise you might get an error FeedsMissingPlugin_feeds_form in drupal_retrieve_form()

This way you dont really need to create a module just create a node with the with the title entered and the url as well. But if there is some other reason from creating the module then yes that would work fine as well.

Second option is to not use the feeds module itself. Just parse the xml manually and add the required fields and call the node_save() function. This would mean you wouldn't have to run the feed script after you create the node it would be done automatically by just calling the url. and it will also take you off the overheads of using the feeds module.


Fatal error: in boostrap.inc line number 2913

modules/user/views_handler_field_user_name.inc is one of the Views files.
Delete the /home/myapp/myapp.com/sites/all/modules/views directory (and the files it contains), and copy the Views files from the archive file you download from the project page. Just be sure to download the same version you installed before, and to copy the files in the same directory they were before. (The views.module file must be in /home/myapp/myapp.com/sites/all/modules/views/views.module, not /home/myapp/myapp.com/sites/all/modules/views/views/views.module, or /home/myapp/myapp.com/sites/all/modules/views.module.)


Snippet to hide the editing of one vocab

You will need to create a custom module with:

Drupal 6:

/**
 * implements hook_form_alter()
 */
MYMODULE_form_alter($form, $form_state, $form_id) {
  if ($form_id == 'type_node_form') {

    global $user;

    // Check to see if $user has does not have the administrator role.
    if (!in_array('administrator', array_values($user->roles))) {
      //to turn all vocabularies off
      $form['taxonomy']['#access'] = FALSE;

      //turn off a single vocabulary *BELOW*
      //if you select 'tags' from your vocabulary settings
      if(issset($form['taxonomy']['tags']) {
        $form['taxonomy']['tags']['vid'] = FALSE;
      }
      else {
        //if you do not selet 'tags' from your vocabulary settings
        $form['taxonomy']['vid'] = FALSE;
      }
    }
  }
}

So there is 3 options, depending how your vocabularies are setup.  You must subsitute 'vid' for the vocabulary id.

Drupal 7:

inside hook_form_alter() like

if ($form_id == 'type_node_form') {

  global $user;

  // Check to see if $user has does not have the administrator role.
  if (!in_array('administrator', array_values($user->roles))) {
    $form['name_of_field']['#access'] = FALSE;
  }
}


How to speed up Reference module's Views plugin?

I wound up replacing references_plugin_style with a custom, bare-bones plugin style in my_references_plugin_style.inc:

/**
 * @file
 * Handler for my_references_plugin_style.
 */
class my_references_plugin_style extends references_plugin_style {
  function render() {
    if (!empty($this->options['grouping'])) {
      throw new Exception(t('References list (fast) does not support grouping.'));
    }

    $options = $this->display->handler->get_option('references_options');

    // Play nice with View UI 'preview' : if the view is not executed through
    // _*_reference_potential_references_views(), just display the HTML.
    if (empty($options)) {
      // "Render" rows quickly
      foreach ($this->view->result as &$row) {
        $row = $row->node_title;
      }

      $function = new ReflectionMethod('views_plugin_style', 'render');
      return $function->invoke($this);
    }

    // Foreach supposedly has better performance than array_map
    // @see http://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function
    $results = array();
    foreach ($this->view->result as $input) {
      $results[$input->nid] = array(
        'rendered' => $input->node_title,
        'group' => '',
        'title' => $input->node_title,
      );
    }

    return $results;
  }
}

Then registering it with:

/**
 * Implements hook_views_plugins().
 *
 * references.module's references_style plugin was way too slow (110s to render ~5k rows),
 * so fork that style plugin and strip most of the functionality away.
 */
function my_views_plugins() {
  $plugins = array(
    'style' => array(
      'my_references_style' => array(
        'title' => t('References list (fast)'),
        'help' => 'Returns results as a PHP array of names + rendered rows. (Less bloat than "References list").',
        'handler' => 'my_references_plugin_style',
        'theme' => 'views_view_unformatted',
        'uses row plugin' => FALSE,
        'uses fields' => TRUE,
        'uses options' => FALSE,
        'uses grouping' => FALSE,
        'type' => 'references',
        'even empty' => TRUE,
      ),
    ),
  );
  return $plugins;
}

And including the .inc file in my module's .info file:

files[] = views/my_references_plugin_style.inc

Finally, I went to my Views' UI and updated the Formatter to the new "References list (fast)" format.


The way I've typically seen that type of thing done is using Contextual filters (formerly called "Arguments" in Drupal 6). The Drupal 7 Advanced Views Tip: Contextual Filters screencast or this tutorial on Using Views Contextual Filters should provide a starting point for using them. In short, contextual filters are like regular filters, except that they allow arguments to be passed in dynamically rather than the filter criteria having to be statically set ahead of time.


How to use CSS preprocessor LESS.js with Drupal 7?

There is the LESS CSS Preprocessor module for drupal.


Add value to existing field value db_update

I think you mean something like this:

db_update('custom_table')
  ->expression('count', 'count + 1')
  ->condition('id', $id)
  ->execute();


Drush: "Unknown engine type outputformat" module conflict

The solutions is one of 3 things:

1.- Update drush

2.- Clear drush cache

3.- If you have the module "module_missing_message_fixer" the best solutions is to disable the module make the changes on drush and enable it when you are done, for some reason that module stops drush from working.

I hope this helps someone else.


Is there anyway to get the $form_state inside a hook_block_configure?

You don't have this information, but you can access to it with hook_form_alter. But to access to this form (that call block_configure) you have two form_id block_admin_configure and block_add_block_form.


How to change the autocomplete for a user reference to show First/Last name instead of username?

Similar to Show node IDs along with titles in Entityreference Autocomplete list except in the rewrite of your user name field use {{field_first_name}} {{field_last_name}} and you need to add those fields ABOVE your user name field, in order to get access to those replacement patterns.


Insert *whatever* every nth row in Views

In under Theme: Information you'll find Style output: views-view-table.tpl.php .... Override that. I selected the Theming info as opposed to other template overrides available because that is the one that has a foreach for rows. In your override you can add a counter to the foreach() along with an if($counter%10 == 0) { ... } with some markup or call to a block or something like that.


Drupal 6: Custom Menu not Expanding when Parent (generated by views) is selected

Five lines of code placed in a views template file solved the issue:

 <?php
    $path = drupal_get_path_alias(check_plain($_GET['q']));
    $menu_item = menu_get_item($path);
    $menu_item['href'] = $path;
    if($path && $menu_item) {
      menu_set_item(NULL, $menu_item);
    }
  ?>


Node teaser with a different size than other nodes

That particular bit of text is wrapped in a <span> that includes inline styles that change the font size of that text.

If your content is entered via a WYSIWYG editor, you may want to adjust the settings for that WYSIWYG so that it strips out inline styles like this.


How can I restrict that only sender and receiver can download the attached file with the private message?

Your question is fully answered here http://drupal.org/documentation/modules/file

Please read sections:

Managing file locations and access
Accessing Private Files

  You can also specify whether files are stored in a public directory or in a private file storage area. Files in the public directory can be accessed directly through the web server; when public files are listed, direct links to the files are used and anyone who knows a file's URL can download the file. Files in the private directory are not accessible directly through the web server; when private files are listed, the links are Drupal path requests. This adds to server load and download time, since Drupal must resolve the path for each file download request, but allows for access restrictions.


There is still no native way within Drupal core to expose config entities via REST. There are 2 contrib modules which claim to allow retrieving menu items via REST, neither of which I have used.

REST Menu Items

Allows you to specify maximum and minimum depth in the request.

REST Menu Tree

Returns the menu tree. Not yet covered by Drupal's security advisory policy.

Update 28 March 2017

REST Menu Items works as advertised but check the issue queue for any outstanding bugs. For example, currently the alias for a menu item isn't returned.


How to get video length of a youtube video in drupal7

You can follow the function youtube_get_remote_image on how to make a call to youtube api and retrieve video length.

Youtube public api provides this info without any authentication, for instance - http://gdata.youtube.com/feeds/api/videos/dc4UltkRJsw contains video length in the tag: yt:duration. I have not tested the below function, but should work.

function youtube_get_video_length($id = NULL) {
  $path = 'http://gdata.youtube.com/feeds/api/videos/' . $id;
  $query = array(
   'v' => '2',
   'alt' => 'jsonc'
 );
  $url = url($path, array('query' => $query));
  $result = drupal_http_request($url);
  $data = json_decode($result->data);
  $video_length = $data->data->duration;
  return $video_length;
 }

Also I dont suggest that you write this in youtube.inc of youtube module, write in your custom module or template.php of custom theme.

Hope that helps.


What hook to use to update history table

You are looking for the node_tag_new() core function.

function node_tag_new($node) {
  global $user;
  if ($user->uid) {
    db_merge('history')->key(array(
      'uid' => $user->uid,
      'nid' => $node->nid,
    ))->fields(array('timestamp' => REQUEST_TIME))->execute();
  }
}

Normally you'd just pass the full node object to the function, but if you only have the nid, you can just pass a dummy object.

$node = new stdClass();
$node->nide = 1234;
node_tag_new($node);

Modifying the OP's own answer, this would be:

function answers_exit() {
  $router_item  = menu_get_object();
  if (isset($router_item) && $router_item->type == "answers_question") {
    if ($user->uid) {
      $results = db_select('field_data_answers_related_question', 'rq')
        ->fields('rq', array('entity_id'))
        ->condition('answers_related_question_target_id', $router_item->nid)
        ->execute();
      foreach($results as $row) {
        $node = new stdClass();
        $node->nid = $row->entity_id;
        node_tag_new($node);
      }
    }
  }
}

However you should probably be using EntityFieldQuery since it will handle all all the specifics about which tables/columns to use:

function answers_exit() {
  $router_item  = menu_get_object();
  if (isset($router_item) && $router_item->type == "answers_question") {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'answers')
          ->fieldCondition('answers_related_question', 'target_id', $router_item->nid);
    $result = $query->execute();
    if (isset($result['node'])) {
      foreach ($result['node'] as $answer) {
        node_tag_new($answer);
      }
    }
}


Sure, you can do this with Views.

Build a view that displays your dishes.
Set a FILTER for 'Has taxonomy term', expose it, and use the 'is none of' operator

I made that example using the 'dropdown' option, you may find the 'autocomplete' option more suitable to your needs.  I recommend trying both to see which fits best and allowing multiple values so that people who are allergic to nuts AND gluten can still use it.


by default drupal cache pages for anonymous user, and it is usual that visiting page bye anonymous user be faster than login users,also in admin page we have more load that front-end page
The is a property of durpal. admin pages have more forms and more proccess.