How do I programmatically update the allowed values of a list field? I have created a field_time_zone field for the Article content type.
I want to set the allowed values for that field to the values returned from system_time_zones().
For this, I implemented hook_form_alter() using the following code.
$zones = system_time_zones();
$entityManager = \Drupal::service('entity_field.manager');
$fields = $entityManager->getFieldStorageDefinitions('node', 'local_market');
$options = options_allowed_values($fields['field_time_zone']);

if(empty($options)) {
$options =  $zones;
$form['field_time_zone']['widget']['#options'] = $options;
}

The code adds the desired values, but the node cannot be saved, as it throws the following error.

The value you selected is not a valid choice.

How can I set the allowed values for a text (list) field?

You can't do this in a form alter hook, because the entity field validation will fail.

You have to add a function to the field settings. This is not in the field UI, so you have to export the configuration and change the field in field.storage.node.field_time_zone.yml:

type: list_string
settings:
  allowed_values: {  }
  allowed_values_function: 'mymodule_allowed_values_function'

Reimport the configuration. Then you can implement this function in mymodule.module to set the options dynamically:

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\field\Entity\FieldStorageConfig;

  function mymodule_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable) {
    $options = [
      ...
    ];
    return $options;
  }

See https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

For the question added later:

How can I set allowed value options to a field of type text(list) and save it accordingly?

The question originally was what to do with the code which doesn't work in form alter, where you can place it instead.

If you mean with this question you have a static allowed value list, then you can copy and paste the list in the field settings UI and save it:

And now it is stored in the mentioned yaml file of the exported configuration here:

  allowed_values: {  }

Thanks, @Gun5m0k3.
This works great. Here's a slightly adapted, more generic version.

In your form_alter:

// Define your options.
$my_options = ['foo' => 'foo', 'bar' => 'bar'];

// Add the options to the field widget.
$form['field_my_field']['widget']['#options'] = array_merge(
  $form['field_my_field']['widget']['#options'],
  $my_options
);

// Ensure that the new options are also added to the allowed_values list
$fieldStorage = \Drupal\field\Entity\FieldStorageConfig::loadByName('node', 'field_my_field');
$fieldStorage->setSetting('allowed_values', $my_options);
$fieldStorage->save();

Is there a good reason why setting fieldStorage within a form_alter is a bad idea? It seems to work perfectly, so I wonder why this isn't the go-to solution as it's the easiest and most straightforward to implement.

J.


Use $base_url in a computed field? Using $base_url to build a link in a computed field, I get this error:

  Notice: Undefined variable: base_url in eval() (line 1 of F:\wamp\www\mysite\sites\all\modules\computed_field\computed_field.module(468) : eval()'d code).

Is it a way to get the site base URL in a computed field?

This is a global scope variable and you can access it by using $GLOBALS['base_url'] instead or calling the core base_path() function to pull it into your computed field definition.

Before using $base_url, You need to declare it just like below

global $base_url;

After declaring you can use
$base_url in your code.


Add Language Switcher on admin toolbar What is the correct way for adding Language Switcher (Dropdown) or links on the admin toolbar menu from my custom module or from a contributed module?

Well, I got something up and running via hook_toolbar. Only thing left is, that you can't click directly on the "Language: EN" string in the toolbar. You have to click slightly next to it. Maybe you can fix this.

Apart from that, please also have a look at the Devel module and their implementation of hook_toolbar where they have an extra src/ToolbarHandler.php class for everything. You better should rebuild the code below into a dedicated handler.

use Drupal\Core\Url;
use Drupal\Core\Link;

/**
 * Implements hook_toolbar().
 */
function MYMODULE_toolbar() {

  // Get languages, get current route.
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $languages = \Drupal::languageManager()->getLanguages();
  $route = \Drupal::service('path.matcher')
    ->isFrontPage() ? '<front>' : '<current>';

  // Get links.
  $links = [];
  foreach ($languages as $language) {
    $url = new Url($route, [], ['language' => $language]);
    $links[] = [
      '#markup' => Link::fromTextAndUrl($language->getName(), $url)
        ->toString(),
    ];
  }

  // Set cache.
  $items['admin_toolbar_langswitch'] = [
    '#cache' => [
      'contexts' => [
        'languages:language_interface',
        'url',
      ],
    ],
  ];

  // Build toolbar item and tray.
  $items['admin_toolbar_langswitch'] += [
    '#type'   => 'toolbar_item',
    '#weight' => 999,
    'tab'     => [
      '#type'       => 'html_tag',
      '#tag'        => 'div',
      '#value'      => '' . t('Language') . ': ' . strtoupper($current_language) . '',
      '#attributes' => [
        'class' => ['toolbar-item-admin-toolbar-langswitch'],
        'title' => t('Admin Toolbar Langswitch'),
      ],
    ],
    'tray'    => [
      '#heading' => t('Admin Toolbar Langswitch'),
      'content'  => [
        '#theme'      => 'item_list',
        '#items'      => $links,
        '#attributes' => [
          'class' => ['toolbar-menu'],
        ],
      ],
    ],
  ];

  return $items;
}

The link in the reply berramou posted doesn't mention the contrib module toolbar_menu, which makes adding stuff in the toolbar more convenient than what is mentioned in the link.


Hide specific sections on admin configuration page I wondering how I may hide some sections on the administration configuration page? I would like to hide some sections entirely for instance the media section and then only remove certain items for others, under the system section I only like to remove the cron item.

I tried to alter the admin/config page using hook_admin_paths_alter() and hook_preprocess_page() but without any luck. Would be nice if some one could point me in the right direction on how to achive this.

function MODULE_admin_paths_alter(&$paths) {
   // hide some paths
   $paths['admin/config/system/cron'] = FALSE;
}

function MODULE_preprocess_page(&$variables) {
  if(path_is_admin(current_path())) {
    // I don't know how to modify the markup of the page
    // tried to add a template called page--admin--config.tpl.php but
    // without any luck
  }
}

In the end I used @Captain Pants solution:

function pe_admin_permission() {
  return array(
    'access extended config' => array(
        'title' => t('Access Extended Configurations'),
        'description' => t('Gives a user access to extended configuration pages.'),
        'restrict access' => TRUE,
    ),
  );
}

function pe_admin_menu_alter(&$items) {
  // add all items you would like to hide here
  // if you hide all items in a specific section the entire block
  // will be removed
  $sections = array(
    'admin/config/system/cron',
    'admin/config/system/actions',
    'admin/config/system/mimemail',
    'admin/config/system/mailsystem',
    'admin/config/date/date_popup',
  );

  // loop through each item you would like to hide
  foreach($sections as $section) {
    $items[$section]['access callback'] = 'user_access';
    $items[$section]['access arguments'] = array('access extended config');
  }
}

You have stated that it would be "nice" to have these paths inaccessible. If a user is not supposed to have access to this paths then you should go above and beyond just "hiding links so nobody can see". Here is the solution to both remove those links from the config page AND having those links inaccessible if one were to type in the url in their address bar.

You will need to make a module with the following code. Note: I'm only doing this for the cron config page.

/**
 * Implements hook_permission().
 */
function my_module_permission() {

  return array(
    'access cron config' => array(
      'title' => t('Access Cron Config'),
      'description' => t('Gives a user access to the cron configuration page.'),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {

  $items['admin/config/system/cron']['access callback'] = 'user_access';
  $items['admin/config/system/cron']['access arguments'] = array('access cron config');
}

This will give you the "Access Cron Config" permission on the permissions page and there you can choose which role has the cron page appear for them.

Please research more on hook_permission and hook_menu_alter for clarification on how to do this for the media pages.

you could use some css to hide the sections for UX, and then use Rules or a redirect module on the paths themselves to keep people from directly entering the url.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module

You could use hook_menu_alter() instead of Rules in a custom module to keep it simple.


Memory Size issue is coming while we have increased a lots of Memory Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 71 bytes) in /home/public_html/includes/theme.inc on line 98

1073741824 bytes = 1GB, so that should be more than enough. I have my development machine set to memory_limit = 256M, which is already pretty much, and I never run into exhausted memory problems.

Your error is probably caused by a mistake or some very inefficient logic in your code. There are a couple of things you can do to find the problem, like:

Switch to a standard theme, to narrow down if the theme is causing the problem.
Disable modules you added recently, one by one, to see which module is causing the problem.
Search for loops in your code that may keep running indefinitely.
Use a step debugger (like Xdebug) to find the point in code where the problem is caused. (Xdebug takes some setting up, but installing it is well worth your time.)
Use a profiler (like XHprof) to see where your memory is going. (Installing and learning XHprof takes time, but if the other methods don't work for you, it can probably answer your question.)

go to settins.php and changes

  memory_limit = "-1"


Alter views fields using preprocess function before render? How do I edit a views field using preprocess before it is rendered to the screen?
Let's say the field originally outputs something like this:

Note title

now I want to change that adding the number of comments in that node

Node title (4 comments, 1 new)

I know I can achieve this with joining two fields together or altering the template (tpl) files for that particular field but I'd like to learn how to use preprocess function in order to achieve this.

Drupal 7

Either you have to use hook_views_pre_render() or create appropriate TPL file (e.g. views-view-fields--MYVIEW.tpl.php) in your template dir (check Theme:Information in view edit page for more details).

You may also use preprocess theme function to print a single record from a row, with fields which is template_preprocess_views_view_fields().

Related:

_preprocess_views_view__ specify view name
Drupal 7 preprocess_views not working
Specific preprocess functions for theme hook suggestions are not invoked

There is help on Using default views in your module.

I also found this how-to helpful: Theming a view from within your module.


How to refresh new migrations in Drupal 8 migration module? When writing Drupal 8 migrate processes I only can refresh new migration processes if I reinstall the custom migration module. drush cr doesn't work.

Explanation:

I have one module, ie: cm_migrations, which have 2 migrations:

cm_users
cm_tags

With drush ms I see:

Group: beer     Status  Total  Imported  Unprocessed  Last imported
 cm_users        Idle    3      3         0            2016-02-09 16:56:25
 cm_tags         Idle    4      0         4

I write a new migrate process:

cm_beers

I execute drush cr; drush ms and I see the same table as previous.

Only when I uninstall and install cm_migrations I can see the three migration processes:

Group: beer     Status  Total  Imported  Unprocessed  Last imported
 cm_users        Idle    3      3         0            2016-02-09 16:56:25
 cm_tags         Idle    4      0         4
 cm_beers        Idle    4      0         4

Any clue about  how can I refresh the migration processes without reinstall the module?

Thanks

I found this worked for me

  drush config-import --partial --source=modules/custom/migrate_module/config/install/

In the answer by FLY above, drush cdi <module_name> should now be drush cde <module_name>.


Add contextual link to panels "custom content" pane? I am wondering if there is a way to add a contextual link to a "custom content" pane? For example my "block" panes have the block contextual link that allow for easy edit. But is there a way to do this for regular panes?

I am trying to find a way to make Panel's more accessible to the "non technical user". Having to click Panel Content, then find the gear, then edit that. Is a little too much work that can easily get lost.

Try FAPE, Field API Pane Editor. It is a separate module from ctools.

It does make it much easier for non-technical users to edit a field or a single pane of a page.


Drush 8.0.3 cannot update custom module I have a few custom modules that updates are being served from a D6 site with the Feature Server (fserver) module. Before updating drush, the drush up command on a site would see there were updates for them just fine. Now I get:
$ drush up uni_blocks_antares
Update information last refreshed: Mon, 03/07/2016 - 09:13
Name                Installed Version  Proposed version  Message
uni_blocks_antares  Unknown            Unknown           Specified project not
                                                         found

No code updates available.                                           [ok]

But when I check that module's info it exists.
$ drush pmi uni_blocks_antares
Extension        :  uni_blocks_antares
Project          :  uni_blocks_antares
Type             :  module
Title            :  UNI Blocks Antares
Description      :  This module pulls in the feed of Toolbar and Footer links
                    from the UNI Features website and creates blocks
                    containing those links.
Version          :  7.x-2.7
Package          :  UNI Custom Modules
Core             :  7.x
PHP              :  5.2.4
Status           :  enabled
Path             :  sites/all/modules/custom/uni_blocks_antares
Schema version   :  module has no schema
Files            :  none
Requires         :  none
Required by      :  none
Permissions      :  none
Configure        :  admin/config/content/uni-blocks

I found that updating through the web interface of the site will see an update(version 2.8) and update the module.
How do I get drush up to work again for it?

What I ended up doing was updating drush to 8.0.5 and that solved it.


How to retrieve last MySQL INSERT ID from db_merge() I am using db_merge for inserting or updating new records in my table.
I want to get the last inserted record id from this table, Thank you.

While there is RETURN_INSERT_ID which can be used with db_query(), I could not find a way to use with db_merge().

<?php
  $query = "INSERT INTO {table_name} (col1, col2) VALUES (:arg1, :arg2)";
  $args = array(':arg1' => $val1, ':arg2' => $val2);
  $last_id = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
?

I think you will have to retrieve the last ID with another query, but you would need to check with MergeQuery::STATUS_INSERT.

$status = db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute()

if( $status == MergeQuery::STATUS_INSERT ) {
      $last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();
}

You can use this.

      $node = db_select('table_name', 'f')
      ->fields('f', array('field_you_want'))
      ->condition('field', 'condition', 'expression')
      ->orderBy('id', 'DESC')
      ->range(0,1);
      ->execute()
      ->fetchAll();


Custom js added with drupal_add_js doesn't actually get added if I enable "Aggregate JavaScript files" or "Cache blocks" The site is the most stock, only Drupal 7 core is installed.
included my theme, where the page.tpl and html.tpl theme files are copied from core
I created a Yandex.Maps module, this is a block where js is added.
<?php
  function yamap_block_info(): array {
    $blocks['yamap'] = [
      'info'  => 'Block Yandex.Map',
      'cache' => DRUPAL_CACHE_PER_ROLE,
    ];
    return $blocks;
  }

  function yamap_theme(): array {
    return [
      'main-yamap' => [
        'template' => 'yamap-block',
      ],
    ];
  }

  function yamap_block_view($delta = ''): array {
    if ($delta == 'yamap') {
      $module_path = drupal_get_path('module', 'yamap');
      drupal_add_js($module_path . '/src/js/yamap.js', ['scope' => 'footer', 'weight' => 40]);
      drupal_add_css($module_path . '/src/css/yamap.css');

      return [
        'content' => theme('main-yamap'),
      ];
    }
  }
?>

When I enable cache and aggregation, js falls off .. there are no errors on the page and in the console.
Drupal.settings.my_data does not exist too. But, if I turn off the block cache or aggregation, then everything is ok

Is the site in D7 or D8/9?
Because in 8+ you should use  #attached instead of drupal_add_js/css


Features - Should I go for big or numerous? I have worked on a few Drupal projects that used features.  I am usually perplexed by the way the way functionality is grouped.  I'm guessing that most of them were created as needed and by different developers that did not want to meddle with other people's features.  The outcome is usually a mess of different naming and grouping schemes.  Currently, I have the opportunity to create a site from scratch, and I want to start using a good methodology for creating my feature groups.  I am tending towards making a gigantic feature that contains everything, and only rebuilding one feature every time an update is needed.  What is good/bad about doing this.  Also, I feel more responsible while considering building several different features for each bit of functionality.  However, I am not sure how granular to go, or if this is begging for conflicts later.  How should I be approaching this issue?

It's all up to you. There are pros and cons to both and it depends on your use case.

Generally one would tend toward decoupled functionality with granular features instead of a giant feature. Especially if you wanted to potentially use these features on other sites.

Some information to help you out.

One big feature Pros:

It's quick and easy. If you're just using features to track database changes in code and
don't care about re usability, you can just stick everything in one
big feature.

One big feature Cons:

If you make one big feature, you can't re use it at all on another
site unless that site is almost exactly the same.

Decoupled features Pros:

You can re use features on other sites.
Your features are much more manageable, even it if it takes a bit
longer.
You can keep custom code which is directly related to the feature in
the features module, so you're keeping the feature + custom code in
one nice package.
This model fits in well with programming in general, taking big
problems, breaking them down, abstracting them, using dependencies,
etc. It will definitely improve your programming practising
separating your code logically like this.
Helps the way you think about Drupal components and how they mess
together.

Decoupled features Cons:

Overhead of organizing features structure. This will get easier as
time goes on and you get better.
Can be very hard to decide where to decouple, especially for newbies.

How should I be approaching this issue?

Take a holiday
Come back when Drupal 8 is released
Use that.

;)

On a more serious note, I'd spend some more time learning core Drupal APIs and do as much as you can from an install profile using drush make and the smallest amount of contrib modules as you possibly can.


How do I get the current path and add a condition in page.html.twig? I have the view page called "location/all" which contain all the map details.

I changed some CSS styles.

{% if 'location/all' in url %}

{% else %}

{% endif %}

I tried this code to check the condition, but every time it executes the else part.

Try this

{% if 'location/all' in url('<current>')|render|render %}

Alternative solution would be to add the following to your THEMENAME.theme

function THEMENAME_preprocess_page(&$vars) {
  $vars['path'] = \Drupal::service('path.current')->getPath();
}

and use this in your page.html.twig

{% if 'location/all' in path %}

Try with this code

{% set current_url = url('') %}
{% if 'location/all' in current_url|render|render %}

{% else %}

{% endif %}


Multi step form with click and state logging in Drupal 7? I need to create two separate forms flows. Essentially the one case has 3 pages (intro, questions, thank you), while the other has 4 pages (intro, questions, questions, thank you). I want to be able to:

Log the states of each "step" as the user proceeds
Keep track of where the user clicks and in what sequence

I am thinking of doing the second part with Google Analytics, as I know it has ways to do this. However, I am not sure what is the best way to go with the multi step form process.

So far it sounds like I would have to create content types for each step and use rules to "guide" the user as he creates the different content types. However, this sounds like a nightmare when it comes to "back" and 'next" functions.

Can anyone please tell me what is the best way to implement a form like this, keeping in mind how important it is that the logging works perfectly.

I can't say that this is the best way, but you can achieve that using the Webform module.

You can create multi step form using Webform module. Add Page break type to form components to split the form.

In Advanced Form Settings you can manage the multi step form actions like 'Automatically save as draft between pages and when there are validation errors' options.

In you want to provide advanced navigation bar for multi step web from you can try the Webform steps module

  This module provides a navigation bar for multi-page webforms. The navigation bar is a set of buttons placed at the top of each webform page. The buttons allow free navigation between steps that have already been visited.

I've written a tutorial about how multi step forms in Drupal works. You can read the tutorial on http://brattland.no/blog/drupal/multistep-forms-in-drupal-7


What does URI mean in drush site alias? I want to create drush site aliases for my sites in order to use rsync. However, I'm not sure what URI means. Is it the (sub)domain I have assigned to my site, or the sites/ folder it is in? If it's the sites/ folder and I am using sites/default , does that make the URI "default"?

$aliases['demosite.drupal7.local'] = array (
  'uri' => 'demosite.drupal7.local',
  'root' => '/var/www/drupal7',
);

Update

I found my answer in drush/examples/example.aliases.drushrc.php.

  'uri': This should always be the same as the site's folder name in the 'sites' folder.

Okay, I wrote that line you're quoting above ("uri': This should always be the same as the site's folder name in the 'sites' folder."), but unfortunately that is an oversimplification that is not always correct, especially when using a Drupal 7 site.

This is what I say about "uri" in the Definitive Guide to Drupal 7:

  The URI used on the command line should be the same as when the site
  is being accessed from a web browser. It is also possible to use the
  name of the folder that contains the settings.php file for that URI
  (e.g. --uri=default).  This works, and is, in fact, equivalent to
  [back reference to an example that runs core-status using the cwd to
  select the Drupal site] in terms of the site URI that Drush will use
  when calling in to Drupal; you can confirm this by comparing the
  output of the "Site URI" line in [back reference to same listing] with
  this output.  Having a correct site URI is not always required, but
  some modules might need it if, for example, they are generating
  absolute URLs or making HTTP requests back to the same host; it's
  therefore advisable to set a correct URI whenever possible.

This quote is 100% correct for Drupal 7, but the situation is slightly more complicated with Drupal 6.  In D6, the value of the --uri option (and correspondingly, the URI used to access the site from a browser), will sometimes be written into the database.  For example, if your settings.php file is stored at sites/mysite.org/settings.php, and your URI (from the browser) is http://mysite.org, then you might in some circumstances find paths "sites/mysite.org/files/myuploadfile.png" in the database.  The URI from the browser is converted to the name of the folder containing settings.php before being used by Drupal (for some uses), whereas the --uri option passed to Drush is always used as-is.  Because of the fact that your site folders are written to the database, it's often handy to continue to use the sites folder "mysite.org" for your dev site "http://dev.mysite.org", and of course there's always the possibility that your sites folder is called 'default' (often a good idea on D6).  So, while --uri=dev.mysite.org and --uri=mysite.org and --uri=default may will all work (presuming a site http://dev.mysite.org which is a dev copy of http://mysite.org with its settings.php file in the default folder) to select the site for Drush, there are some edge cases where --uri=default is better in that the other options will not match what your modules are seeing when the same code.  On the flip side, there are also other edge cases where --uri=mysite.org is what you need to align your runtime variables with what your module will see with the browser (c.f. above dgd7 quote).  So the truth of the matter is that there is no value that is absolutely best for D6. The simplified advice you quoted above was used in the example file because things can really go wrong if you use --uri=mysite.org instead of --uri=default, AND a path is generated and written to the database, AND you migrate your database to another instance of the site, breaking the path.

For D6, the most pragmatic thing to do would be to name your sites folder 'sites/mysite.org' instead of 'sites/default' (and make sure that it is also 'sites/mysite.org' for http://dev.mysite.org).

I changed the advice in examples/example.aliases.drushrc.php as follows:

  'uri': In Drupal 7, the value of --uri should always be the same
  as  when the site is being accessed from a web browser (e.g.
  http://mysite.org, although the http:// is optional).  In Drupal 6,
  the value of --uri should  always be the same as the site's folder
  name in the 'sites' folder (e.g. default); it is best if the site
  folder name matches the URI from the browser, and is consistent on
  every instance of the same site (e.g. also use sites/mysite.org for
  http://dev.mysite.org).

Found my answer in drush/examples/example.aliases.drushrc.php : "uri': This should always be the same as the site's folder name in the 'sites' folder."


Alter menu item markup in Drupal 8 I am trying to play around with Drupal 8 menu. How I understand now menu is a service, so how to alter menu output in Drupal 8? Is there any documentation? Because googling show no useful results.

What I am trying to achieve is move active class from <a> element to parent <li> element, this should be possible to do in .twig template (I wouldn't like that) so how to get menu in Drupal 8 and alter it's attributes?

There is one central problem: the active class is not always added in PHP, but
for non-anonymous users its calculated using some javascript, see "active-link.js".
For anonymous users, its calculated in
\Drupal\system\Controller\SystemController::setLinkActiveClass

I have a complete example for twitter bootstrap, I use:

Note: this code is incomplete, maybe broken with beta update, but it's an example/introduction.

function nature_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Prevent dropdown functions from being added to management menu so it
    // does not affect the navbar module.
    if (($element['#original_link']['menu_name'] == 'management') && (module_exists('navbar'))) {
      $sub_menu = \Drupal::service('renderer')->renderRoot($element['#below']);
    }
    elseif ((!empty($element['#original_link']['depth'])) && ($element['#original_link']['depth'] == 1)) {
      // Add our own wrapper.
      unset($element['#below']['#theme_wrappers']);
      $sub_menu = '
' . \Drupal::service('renderer')->renderRoot($element['#below']) . '
';
      // Generate as standard dropdown.
      $element['#title'] .= ' ';
      $element['#attributes']['class'][] = 'dropdown';
      $element['#localized_options']['html'] = TRUE;

      // Set dropdown trigger element to # to prevent inadvertant page loading
      // when a submenu link is clicked.
      $element['#localized_options']['attributes']['data-target'] = '#';
      $element['#localized_options']['attributes']['class'][] = 'dropdown-toggle';
      $element['#localized_options']['attributes']['data-toggle'] = 'dropdown';
    }
  }
  // On primary navigation menu, class 'active' is not set on active menu item.
  // @see https://drupal.org/node/1896674
  if (($element['#href'] == '<front>' && drupal_is_front_page()) && (empty($element['#localized_options']['language']))) {
    $element['#attributes']['class'][] = 'active';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

After I have my view nammed "menu--main.html.twig" :

{#  https://api.drupal.org/api/drupal/core!modules!system!templates!menu.html.twig/8
    menu_name: The machine name of the menu.
    items: A nested list of menu items. Each menu item contains:
      attributes: HTML attributes for the menu item.
      below: The menu item child items.
      title: The menu link title.
      url: The menu link url, instance of \Drupal\Core\Url
      localized_options: Menu link localized options.
#}

      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">
      Toggle navigation

      </button>
      Site Name : {{ site_name }}

      {# All menu and submenu items #}

        {% for item in items %}
          {# Menu with submenu #}
          {% if item.below %}

              {{ item.title }}

                {# Menu -> Submenu #}
                {% for item in item.below %}
                  {% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
                {% endfor %}

          {# Menu without submenu #}
          {% else %}
            {# Menu - Link #}

{{ item.title }}

            {# Menu - Separator #}
            {% if loop.last == false %}

{% endif %}
          {% endif %}
        {% endfor %}

      <form class="navbar-form navbar-left" role="search">

          <input type="text" class="form-control" placeholder="Search">

        <button type="submit" class="btn btn-default">Submit</button>
      </form>

          Dropdown 3

Action

Another action

Something else here

Separated link

This view call "menu-infinite-child.html.twig" for unlimited infinite child (submenu) :

{# Submenu -> Submenu #}
{% if item.below %}

    {{ item.title }}

      {% for item in item.below %}
          {% include "@nature/snippet/menu-infinite-child.html.twig" with { 'item': item } %}
      {% endfor %}

{# Submenu without Submenu #}
{% else %}

{{ item.title }}

{% endif %}

Note: I use this configuration with bootstrap-submenu http://vsn4ik.github.io/bootstrap-submenu (MIT license).


Fill form on ajax callback Seems to be an extremely simple question. But I can't figure it out. In my module's form I need to load form values depend on the value of certain one and rebuild the form using those.

here is the part of the code (form builder):

$namevalue = isset($form_state['values']['name']) ? $form_state['values']['name'] : "";
$form['name'] = array(
    '#type' => 'textfield',
    '#default_value' => $namevalue
);
$form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#ajax' => array(
        'callback' => 'simplenews_mod_load_subscriptions',
    )
);

Here is the callback:

function simplenews_mod_load_subscriptions( $form, &$form_state){
  $form_state['values']['name'] = "loaded value"; // here will be a function which will get the value form DB
  return $form_state;
}

Nothing changes in the $form_state array.
I think I just don't get the basis of ajax in D7 itself... I'd be very appreciated if someone show my the simplest example of how to change a form field value using ajax.

Or alternatively: how do I rebuild form with new values using custom submit callback. Not on validation.

Thank you.

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

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

ARRAY!

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

You're pretty close...

$form_state['values']['name'] = "loaded value";
return $form_state();

Is wrong for a few reasons:

Messing with the submitted values ($form_state['values']) directly possibly isn't the best idea; if you need to do it that way, use form_set_value, but even better, stash it somewhere else in $form_state
$form_state is an array, and can't be invoked as a function. If you look in the logs, your AJAX requests will probably be returning a 500.
You need to return the element of the form that you want to replace rather than the state; $form_state is by reference so changes you make are persisted to it that way.

You're also missing the wrapper property for the ajax array in the form function, so the system won't be able to manipulate the DOM with the new data.

With those in mind, try something like this for the form function:

$namevalue = isset($form_state['namevalue']) ? $form_state['namevalue'] : "";
$form['name'] = array(
    '#type' => 'textfield',
    '#default_value' => $namevalue,
    '#prefix' => '
',
    '#suffix' => '
',
);
$form['load_settings'] = array(
    '#type' => 'button',
    '#value' => t('Load my settings'),
    '#ajax' => array(
        'callback' => 'simplenews_mod_load_subscriptions',
        'wrapper' => 'name-value-field',
    ),
    '#submit' => 'foo_submit_callback',
);

and this for the callback:

$form_state['namevalue'] = "loaded value"; // here will be a function which will get the value form DB
return $form['name'];

and a submit handler for your button to rebuild the form:

function foo_submit_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}


how to create image upload of difference dimensions I am creating a custom gallery. I require images that are the thumb nail and the big image size. I have custom content type. When i add the image field it allows me to enter the dimensions size. Is there a way for drupal to create 2 images. ie thumb and big image

You can either create two image fields, one for the media image and another one for the thumb, or you could just have one and use different Image Styles ( admin/config/media/image-styles in Drupal 7 ) for both the full and thumbnail. You could even add Image Javascript Crop for more fine-grained control of the thumbnail.

ImageCache is what you are looking for. Here is a quote about it (from the module's project page):

  ...  allows you to setup presets for image processing. If an ImageCache derivative doesn't exist the web server's rewrite rules will pass the request to Drupal which in turn hands it off to ImageCache to dynamically generate the file.


Group search results by content type and limit count I am trying to group search results by its content type. Also, I want to show not more than 4 results per content type.

For an assumption, it should look like this:
Content type1-
  Result1
  Result2
  Result3
  Result4
Content type2-
  Result5
  Result6
...

I am able to achieve this using TEMPLATE_preprocess_search_results().

function custom_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  $resultTypes = array();

  // Divide results
  foreach ($variables['results'] as $result) {
    $resultTypes[$result['bundle']][] = $result;
  }

  // Create fieldsets
  foreach ($resultTypes as $resultType => $resultTypeResults) {
    $value = '';
    $i = 0;

    foreach ($resultTypeResults as $result) {
      $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
      $i++;
      if ($i == 4) {
        $value .= l(t('Show more'), current_path(), array('query' => array()));
        break;
      }
    }

  $variables['search_results'] .= theme('fieldset', array('element' => array('#title' => $resultType, '#children' => $value));
  }
}

But this is not an optimal method, since I trimmed down the results per content type (but actually they exist). Say if Content type1 has 10 actual results and Solr's maximum results per page is set to 10, then I will end up showing first 4 results of only Content type1.

Please suggest an ideal method to list 'n' matched results of every content type.

Thanks!

You can increase the page limit by apache solr hook

function custom_apachesolr_query_alter($query) {
  if(strpos($_SERVER['REQUEST_URI'],'/bundle/') == false)
    {
  $query->replaceParam('rows', '400'); // Note that high value increases response time
  }
}


How do I use React components? I'm going to use React with D8 and perform so-called Progressive decoupling, i.e. use React Components on existing Drupal pages.

There are several articles on this topic but the information is not complete. It would be great to summarize it and define the best method of implementing React.

I've chosen this guide to start with and created a React App inside my custom module folder. I've also decided to use JSON API instead of RESTful Services, according to the recommendations.

After that author recommends to use Paragraph module to implement separate paragraphs which will be replaced by React components.

It is not clear to me what structure should my custom module have? Do I need a router, controller, .module file or maybe a plugin? Where should I put hook_preprocess_paragraph__HOOK function?

My idea is simple - to use different paragraphs for different React components and insert them into an existing layout.

Any best practices?

The 'React block'
module aims to add some more structure around React components and Redux state management in Drupal.

React blocks are defined by adding a simple YML file to your exising React component. This allows front end devlopers to create and manage React components as they normally would, and by including this YML file they can make the component available inside Drupal.

You can use https://drupalconsole.com/home which can generate module files for you.
What you need for this example is an info and a module file which can be created using the drupal gm command from Drupal console.
This guide https://www.drupal.org/docs/8/creating-custom-modules is also a good start to understand the structure of modules.
Also, you'll need to define libraries for your module as per this guide https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module


How can I change a field's widget type on its node edit page? I have a node type that uses Fuploader image field widget. When a user creates new a node of this type, I want them to be able to use the fuploader widget to upload images. When the user edits that node at some point, I want to switch to the normal imagefield widget. How can I accomplish this?

Login in as super admin:

content management ->content types -> edit [your content type]->managefields

click on configure of that field and there you will see second button which named "Change basic Information"

Click on this button and will get the way to edit widget type.


Backup and Migrate exclusion recommendations? When doing database backup using Backup and Migrate, what is the reasonable table exclusion strategy?

My first guess was:

Exclude the following tables altogether - leave that listbox with no selection
Exclude the data from the following tables - select all tables that include "cache" word, such as cache_block or ctools_css_cache.

Any comments, any considerations, any recommendations?

I have following tables to exclude data (not to exclude the table altogether):

all cache_* tables
ctools_views_cache
ctools_object_cache
flood
history
queue
semaphore
watchdog
search_index

Usually search_index saves a lot of database size.

As discussed by Charlie S, Artur and MPD above, the recommended settings are good but you need to watch for additional cache tables from added modules while accidental clicks can, a) lead to needless extra sized or huge mysql files that prevent full fileset/data backups (especially on shared servers); or b) totally useless backups; or c) backups that seem good on restore but are actually total disaster worse than useless because one of the many tables or missing data from a table is missing but not evident until a later time.

That being said, Drupal default Seven theme or other layout/style/css for BaM profiles page is decent and usable, BUT AWKWARD and this can lead to mis-clicks (been there 20 times) or time wasted scrolling up and down, up and down, trying to ensure there is no mis-click. The developers are kind enough to offer toggle between select box and check box but still scrolls up and down in the default theme UI may lead to issues from human error.

To improve the backup Migrate UI when adding or making a profile I use Context module based on path admin/config/system/backup_migrate/settings/profile/add and admin/config/system/backup_migrate/settings/profile/edit/*to get rid of theme sidebars and CSS Injector to  "exclude tables" and "exclude data" SIDE BY SIDE with css for HEIGHT as tall as possible and FLOAT right. Side by side human readability are therefore reliability of backup configurations are much easy that way.

The real point in respect to "exclusion table strategy" is that not all BaM Profiles are full backups, and aside cache table exclusion, when creating profiles for table sets for certain purposes, say nodes and fields, just field sets, locations and maps, rules and flags, filters and fonts, etc etc a BETTER INTERFACE for a GOOD SYSTEM means better protection.


Adding Divs in Blocks I've created a custom block with Div and P tags in which some have id and class attributes. I've tried use FULL & Filtered html formats for the block body however the id and classes don't show up once I've added the block.

In admin/structure/types/manage/your_content_type/display  (drupal 7 path) make sure field Body has format "Default" selected. If you have any other format those will remove the div ids and classes from the body.

Please try change to PHP code which this option appear when you enable php filter in Modules page.


Remove the strict warnings from being shown I have a site using Drupal 6; after upgrading PHP to 5.4 , some strict warning appear.

I set error_reporoting in settings.php with the following code, but I still see the E_STRICT warnings.

error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_WARNING);
ini_set('display_errors', TRUE);

Why do I still see them? What can I do to avoid seeing them?

From the link :

  If you're going to hack core, a much better solution is to properly
  fix the error handler. Add this line to the top of the
  drupal_error_handler function in includes/common.inc:

  if ($errno == E_STRICT) { return; }

Watch this youtube video this is axactly what you want its easy and helpfull and don't forget to change resolution to 460 before watching https://www.youtube.com/watch?v=i5Hq6t8Z6Fo


db_select condition with subquery causes PDOexception I want to build a relative simple select query with a subquery in its condition. What I want to achieve is to get the list of users updated after a given timestamp.

The working SQL-Query which I want to build as dynamic query is:

SELECT uid
FROM `users`
WHERE `vid` > (
  SELECT vid
  FROM `user_revision`
  WHERE `timestamp` > 1379494886
  ORDER BY `timestamp` ASC
  LIMIT 1
);

I've written the following code to build above query with Drupal's Database API:

$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC')
  ->range(0, 1);

$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.vid', $subquery, '>');

$result = $query->execute()->fetchAssoc();

But, I'm getting the following PDOexception error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in
      your SQL syntax; check the manual that corresponds to your MySQL server version for the right
      syntax to use near 'SELECT ur.vid AS vid FROM user_revision ur WHERE (ur.timestamp >
      137949488' at line 1: SELECT u.uid AS uid FROM {users} u WHERE (u.vid > SELECT ur.vid AS vid
      FROM {user_revision} ur WHERE (ur.timestamp > 1379494886) ORDER BY ur.timestamp ASC LIMIT 1
      OFFSET 0) ; Array ( ) in MYMODULE_page_callback() (line 22 of
      /path/to/the/module/includes/page_callback_file.inc).

What am I doing wrong building the subquery?

Thanks to @Clive's comment, I checked the documentation about the subqueries on https://drupal.org/node/310086 and I noticed the note about:

  Note: Currently it is only possible to use subselect conditions with the IN operator because with the other operators the sub-query is not wrapped in parentheses and so results in a syntax error. See #1267508: Subselects don't work in DBTNG conditions, except when used as value for IN.

I've changed my code to use IN instead of > and it worked like a charm. Here's the working code for future reference if someone falls into the same situation:

$subquery = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC');

$query = db_select('users', 'u')
  ->fields('u', array('uid', 'vid'))
  ->condition('u.vid', $subquery, 'IN');

$result = $query->execute()->fetchAll();

You could separate your subquery into another query to return just the value, see below:

$vid = db_select('user_revision', 'ur')
  ->fields('ur', array('vid'))
  ->where('ur.timestamp > 1379494886')
  ->orderBy('ur.timestamp', 'ASC')
  ->range(0, 1)
  ->execute()
  ->fetchField();

$query = db_select('users', 'u')
  ->fields('u', array('uid'))
  ->condition('u.vid', $vid, '>');

$result = $query->execute()->fetchAssoc();


Change workbench_moderation_state from select to radio I have workbench installed, and want to change the moderation status dropdown in the add node form to a radio.
But I don't get it. I have a custom module with a hook_form_alter hook which prints the $form array via

  dsm($form)

This does NOT print any workbench_moderation_state variable.
If I print it via print_r($form), I get a

 [...]
 [workbench_moderation_state_new] => Array (
   [#title] => Moderation status
   [#type] => select
   [#options] => Array (
     [needs_review] => Current: Needs Review
     [draft] => Draft
     [published] => Published
   )
   [#default_value] => needs_review
   [#description] => Moderationsstatus für diesen Inhalt setzen.
   [#access] => 1
 )

So it has to be there.

Why is the workbench_moderation_state_new Array not displayed in krumo via  dsm(), but printed via print_r()
(more important) Why the f**k does a simple

  $form['workbench_moderation_state_new']['#type'] = 'radio';

  not change the select into a radio, but introduce a new empty radio button in the form? I tried to follow the Drupal form API.

Argh. As almost always, I found the answer myself 5 minutes after posting here. Cost me 3 hours of searching and try-and-error before. workbench_moderation_state_new is a sub-array of options.

So a $form['options']['workbench_moderation_state_new']['#type'] = 'radios'; does the trick. Mind 'radios' instead of 'radio' as well. For anyone interested.
Problem solved.

$form['options']['workbench_moderation_state_new']['#type'] = 'radios'; does the trick.
I just forgot the ['options'] array.


form_set_error message delayed one page refresh I'm making a custom validation in a form I'm making but my error message is always delayed by one page refresh.

$form['submit']['#validate'][] = 'asap_sollicitation_form_validate';

function asap_sollicitation_form_validate($form, &$form_state)
{
    if(strlen($form_state['values']['pass']) < 6){
        form_set_error('pass', t('Must be longer than 6'));
    }
}

It successfully marks the field in red but the message is delayed. If I use only drupal_set_messsage without the form_set_error I do get a message displayed in time.
I render my form in a node template:

$arr = drupal_get_form('asap_sollicitation_form');
print drupal_render($arr);

How can I get my message to display after form submit?

I had the same, here is the solution and explanation:
The key of this problem is the drupal_get_form('FOO') is called in theme layer. For example _preprocess_WHATEVER or directly in BAR.tpl.php

The messages are prepared in _process_page()  After that it's unchangeable in deeper theme functions, like FOO_preprocess_node. (That's not exactly true, but it's out of scope of this topic.)

I bet, you prepared a variable by drupal_get_form('FOO') in _preprocess_node, maybe later.

You should use hook_entity_view_alter or hook_node_view_alter, maybe hook_page_alter if necessary, anything else than theme hooks.

Just for the record: The last time you are able to set a message by drupal_set_message() is _preprocess_page

If drupal_set_message() is working for you then you should use it. You can pass a second parameter to the function to control which type of message drupal will display.

  string $type: (optional) The message's type. Defaults to 'status'.
  These values are supported:

  'status'

  'warning'

  'error'

Also, form_set_error() calls drupal_set_message() with a $type = 'error' so it may be that there is something else causing 'error' type messages to be suppressed.


Use entity reference to target revisions of an an entity I'm building a custom entity document which supports revisions. Revisions are seen as versions of the document (v1.1, v1.2, ...), the title field is revisionable as well.
Then there is a custom entity customer, which needs to accept documents. On creation of a customer, I need to point out which revision of the document is suitable for this customer.
I have an entity reference field on the customer to target a document. However, I'm not achieving to target revisions of a document.
I tried entity reference display in views (with a view that supports revisions) but I'm not able to select it in the field settings (no eligible view found). Probably because I can only select 'Document' as target type and not 'Document revisions'.
I tried entity reference revisions module but gave me the same results. This module just keeps track of changes in parent vs child revisions (I guess).

I would expect document revisions being available in the settings above!

Any suggestions on how to do this properly, am I missing something? I want to make use of core as much as possible for this one.
Update: I ended up creating a custom field plugin to get the required solution.

Revisions are stored in a separate db table from content. Views module makes you choose the base table for the query to the database when you're creating a new View (it's commonly called Views type: Content, User, Media, Taxonomy terms).
The easiest way to allow an Entity Reference Field to choose a particular Revision of a Content item is to build the list of Content Revisions items, and not a list of Content items.
Create a new Views entirely but this time choose Content revisions under Show, and not Content (you can't change that from within your existing Content type Views).
Your aim it to have a separate revision in each Views row, because when you're using that list within an ER Field each Views row becomes one checkbox/radio button to select when you're creating a new node.
Revisions can be grouped by their original content ID, Title or something else in common, but I'm not sure if the Entity Reference Views Display type supports that, I expect it doesn't and it won't affect it, you'll still get a plain list of all Revisions and you need to make sure yourself what to output and how to style it to make the options clear. There are probably ways on how to improve the ER Display output in Field widgets but that is out of scope of this question.

I haven't tries this, but usually when listing content referenced through ERs you need to add a Relationship to get any other info than an ID of the referenced entity. You'd need a Relationship to get that info. In your case if you start with Content Views type I expect you'd have to make sure to have each Revision is in a separate row (after you make them appear in results by adding a Relationship, and you'd probably need to list only the Revision info to make them appear in separate rows). I know it's possible to create the reverse ER Views through the forward list Views this way, but haven't tried it with Revisons, maybe the same logic applies.
Anyway, go with the Content Revisions Views type as explained above ;)


Programmatically get View Custom Text I created a view with a "Custom text" field and want to get this field programmatically in Drupal 8.

I have:

$view = Views::getView('my_view');
$view->execute();
foreach($view->result as $row){
    $node = Node::load($row->nid);
    // Get here the view custom field with label "An example view field".
}

The $row field doesn't have the fields, nor the $node.

A screenshot of the view:

I now have:

$customField = $view->field['nothing'];

customField is an instance of Drupal\views\Plugin\views\field\Custom.

dpm($customField->render($row));

This returns class Drupal\views\Render\ViewsRenderPipelineMarkup with protectecd string with the same markup: {{ title }} test.

Thanks,

You should have something like

//already loaded
$node = $row->_entity;

Best way to get properties easily is probably to inspect variables with xdebug

If it is some king of header/footer, you can get the rendered array this way :

$view = \Drupal\views\Views::getView('Your view');
$view->execute();
/* @var $area \Drupal\views\Plugin\views\area\Text */
$area = reset($view->header); // $view->header['area'] or something else
$rendered = $area->render(); // rendered array

Ok, then :

$view = \Drupal\views\Views::getView('YOUR VIEW');
$view->execute('YOUR DISPLAY ID OR DEFAULT');
$nothing = $view->getHandler('YOUR DISPLAY ID OR DEFAULT','field', 'nothing');
$text = $nothing['alter']['text'];

$view = \Drupal\views\Views::getView( 'view_name' );
  $view->execute();
  foreach ($view->result as $row) {
  kint($row->_entity->get( 'nid' )->getValue()[0]['value']);
  }


Exclude fields from a node-add form (but keep them on the node-edit form) by excluding (to save load time) not hiding? Drupal 7 The site I am building is for a parts database and parts are related to each other - eg a circuit board can have a bunch of screws and relays that are sub parts and the board itself can be a sub-part of a module.

When you are registering a circuit board (node-add) you don't need to associate it with parent parts or sub parts. But you may want to do that when you edit it (node-edit).

The parts are associated by entity reference fields and the entity select views take a bit of time to load. I want to save that load time for the node-add by excluding those fields from the node-add form completely (not just hiding them) but I want them to load as normal for the node-edit form.

Thanks very much and have a great Friday!

Okay I got it to work. On new nodes there is no NID on existing nodes there is. This code works.

function custom_form_alter(&$form, $form_state, $form_id) {
if($form_id == 'custom_node_form') {
    if (empty($form['nid']['#value'])) {
    unset($form['field_remove_this_field_name']);
    }

}

Unfortunately I still have a slow load time and I suspect that even though I'm unsetting the form fields that involve entity references (and therefore views queries to populate selection lists) that the queries are still getting run.

It's only really slow on the first form load after clearing caches. The second form load is much faster.

If anyone has any ideas to speed up the initial form load, I'd love to hear them.

It may be that I need to create a custom form from scratch using module code and only load the essential fields.


Content Type name not translated I created a custom Drupal 7 module that creates a custom content type. It looks like this:

$type = node_type_set_defaults(
array(
    'type' => 'featured',
    'name' => t('Featured'),
    'description' => t('The description of the featured item.'),
    'base' => 'node_content',
    'locked' => 0,
    'custom' => 1,
    'modified' => 1
)
);

node_type_save($type);

I have a nl.po translation file that contains the following entries:

msgid "Featured"
msgstr "In de kijker"

msgid "The description of the featured item."
msgstr "De beschrijving van het in de kijker item."

The description gets translated as I expect when switching between languages. The content type name does not get translated at all, only English is shown.

Any ways to fix this?

Thanks in advance.

I hope this like help you

How to Translate Content type name using i18n module?


Using AJAX in menu and menu tab links I have a few pages with sub pages as tabs. Each pages are in a custom menu. I'd like to convert the menu links to load each page using AJAX, is this possible?

I know how to load a page using a regular AJAX link, but not a menu, or menu tab link. One way is to replicate the menu links using AJAX and binding the events to the corresponding menu links, which works, but there must be a better way?

Assuming I understand your question correctly, it is possible. This is how I would do it (not sure how much this differs from the way you mentioned). Obviously you would need to change your page callback function, which you set for the tab in hook_menu(), to return a json object rather than a rendered page.

At the end of your page callback function you should add something like this:

// Return the rendered view in a JSON object. The object will contain a property
// named “contacts”, which containes the rendered view.  This will be sent to the
// browser and is accessable to javascript.
return drupal_json_output(array('contacts' => $view));
exit;

You would then need to include some javascript on the client-side to send an ajax request to the server using the URI/path you set for the tab in hook_menu.  This same client-side javascript would then process the returned data.

  currentMenuLink.click(function() {
      var updateContacts = function(data) {
        // The data parameter is a JSON object. Do something with the returned data here.
      };

      // Send ajax request.
      $.ajax({
        type: 'POST',
        url: this.href, // Which url should be handle the ajax request. This is the url defined in the  html tag
        error: function() {
          $('#namecards-get-contacts-by-nid-row-' + currentNid).show();
          $('#namecards-get-contacts-by-nid-cell-' + currentNid).html($('
An error has occurred while retrieving the list of contacts.  Please try again.  If the problem persists, please inform your website administrator.
'));
        },
        success: updateContacts, // The js function that will be called upon success request
        dataType: 'json', //define the type of data that is going to get back from the server
        data: 'js=1' //Pass a key/value pair
      });
      // return false so the navigation stops here and not continue to the page in the link.
      return false;
    }
  });

I use hook_menu_alter() for this:

function THEMENAME_menu_link(array $variables) {

  //mlid - menu link ID. I want AJAX only some menu link
  if ($variables['element']['#original_link']['mlid'] == 1177) {
    drupal_add_library('system', 'drupal.ajax');
    $element = $variables['element'];
    $output = l('YOUR_LINK', $element['#href'].'/nojs', array('attributes' => array('class' => array('use-ajax'))));
    return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";
  }

  // render other items dy default way
  return theme_menu_link($variables);
}


How to build a user authentication workflow with AngularJS using RESTful module? I'm building a single page app with AngularJS and Drupal as the backend. I'm using the RESTful module. However, I do not have much to go on to build a user authentication workflow.

There are several techniques to authenticate users with a SPA. For example, storing session information in a cookie or in a token. In order to keep a persistent authentication with a token, AngularJS stores the token in local storage. I've been reading that this causes security risks because other scripts are able to access local storage.

Also, RESTful comes with a token authentication module which stores tokens on the server.

The first question is which form of persistent authentication to use? Do I have to completely make the SPA headless Drupal? If the app is headless, using token authentication, do I have to completely remove all the out of box user authentication workflow, for example, resetting a user's password, from the app? Is there a hybrid solution? If the information is being consumed and altered by mobile apps and other non standard means, is using cookie authentication out of the question? If that is the case, on a desktop app, how do I prevent users from accessing user URIs? Basically, I have no clue what is going on and there isn't much information about secure solutions.

Do headless means no layout and block display at all ?
i believe u can leave CAS drupal module do the job ( and a connection menu )


Blank spaces opening RSS XML file - How to solve? All of the sudden, we are experiencing problems with our RSS feed which comes with the Drupal core 7.x . It is no longer valid due to two spaces before the opening XML tag. The following error is what I get in the feed validator:

  line 1, column 2: XML parsing error: <unknown>:1:2: XML or text declaration not at start of entity

So I am aware of other related posts on Stack Exchange and tried the things mentioned in:

Approach to removing extra space at beginning of RSS file?
xml sitemap module : XML declaration allowed only at the start of the document [closed]
RSS Feed does not validate using Views RSS module

These are the things we did do so far:

Checked all PHP-files on the website for containing blank spaces before the opening tags. There were a few, we fixed them all but no help.
Changed the default theme to another theme, making sure it is not theme related.
When I create a custom RSS feed with Views, the same two blank spaces show up before the XML opening tag.
I checked every page, block and view that has manually written PHP tags everywhere and deleted every space that could cause this.
All modules and Drupal core is updated to the most recent versions.
I checked on the Drupal forum for related issues in XML Sitemap, Metatag, RDF, Schema.org (modules we are using) with no success. I disabled every one of the above mentioned modules one by one, but with no success.
Eventually we exported the complete website, except the sites/default/files/ folder which contains no PHP files anyway, and imported it local. The blank spaces are gone in the local setup.

What makes it a bit difficult too, is that I have no idea when the RSS feed went broken. It can be between a week and a few months, making it difficult to filter out when I updated some contrib modules.

So we are quite desperate in finding this, especially since the problem doesn't exist in a local setup. We have a news website so having a working RSS feed is pretty important.

We must be overlooking something, but have no idea what it can be.

Some more troubleshooting ideas:

Do the spaces only appear on the RSS page, or also on other pages? That could tell you whether the problem is in a central place or a template/include-file that is only loaded for the RSS feed.
You can use var_dump(get_included_files()) (ideally in the template, just before the XML is generated) to see a list of all PHP files that have been included so far. This might help with investigating - look for closing PHP tags at the end of the files, print statements, etc.

Also, an idea for a dirty workaround (may cause other problems, but could be worth a try if it's urgent): ob_start() buffers all output, while ob_end_clean() deletes it. So if you put an ob_start() in the top of your index.php and an ob_end_clean() at the start of the RSS template, this might let you discard the spaces. (It shouldn't affect anything else, because the buffer is flushed automatically if it's still open when the script ends.)

The issue was a module which had two blank spaces AFTER the closing PHP-tags in its .module file. All the topics I've found on the internet only mentioned blank space before the opening PHP-tags, so if anyone else ever have this issue, also look in the closing tags


Filebrowser thumbnails "can not create img for private://" I am using Drupal 8.7.5 and PHP 7.3.7 running on Apache 2.4.6.

UPDATE: I'm trying to make available a library of images to the public. I chose the content type of 'Directory listing' to do this. In the Directory listing I have configured a private file path (i.e. located outside of Web root) to hold the images. Apparently I have done something right as it is working except for the thumbnails. I get constant 404 errors in my apache logs and the other errors through the web interface seen in the images below.

What have I missed in terms of getting the thumbnails working? Am I missing an binary or library to render the thumbnails? Did I not create or configure a path for the thumbnails?

Below are some of the steps I have done to configure the Directory listing.

UPDATE On the server I have installed Druapl 8 using composer and drush to $APACHE_CONTENT/drupal. The drush site-install then goes to $APACHE_CONTENT/drupal/web (drupal app_root) and have added a 'private' path as $APACHE_CONTENT/resources. This puts the 'private' path outside of the drupal site's DocumentRoot. The permissions and ownership for the 'private' path are 775 and apache.apache. Also, a .htaccess file was auto generated for the 'private' path. It contains the following:

# cat .htaccess
# Deny all requests from Apache 2.4+.
<IfModule mod_authz_core.c>
  Require all denied
</IfModule>

# Deny all requests from Apache 2.0-2.2.
<IfModule !mod_authz_core.c>
  Deny from all
</IfModule>

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

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

In drupal/sites/default/settings.php I have:

$settings['file_private_path'] = $app_root . '/../../resources';

Viewing the Configuration->Media->File system is see:

I've configured a private file path to use with content created via
Content->Add Content->Directory listing.

I have then used scp to copy files into the private path.

Through the web interface, I can browse through the content but I never see the thumbnails. I get errors above my content.

In the apache logs I see 404s for the thumbnails:

GET /system/files/styles/thumbnail/private/Images/JPG/Marshal_Hub.jpg?itok=QwQds55m HTTP/1.1" 404 11730

I have GD installed.

While I can browse all of the content in the 'private' paths, none of the thumbnails get generated.

What do I need to do to get the thumbnails working?

This is a workaround I used to solve the issue:

[https://www.drupal.org/project/private_files_download_permission]

I don't consider this 'magic' to be a fix. There is a lack of documentation and/or a bug in the filebrowser module.

How can one raise an issue with the developers?

PS: Also, now have another issue with the filebrowser module: sort order is not being honoured in Grid view!

It's my understanding that the 'private' directory can not be used to serve files. The whole point of this special directory is to provide a protected place for the files you choose to place in there. If the images are place in another directory under the 'sites/*/files' directory they should be accessible to be served.


Hide some part of node when the field_countdown timer is zero I create a field with field_countdown. Now I want hide some part of my node text when the timer is zero.

For this when I use this code:

{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    Show
{% else %}
    Hide
{% endif %}

Work but not currectly. And in first page send me an error.

  The website encountered an unexpected error. Please try again later.
  TypeError: DateTime::__construct() expects parameter 1 to be string,
  array given in DateTime->__construct() (line 519 of
  vendor\twig\twig\lib\Twig\Extension\Core.php).

In second way I create a field like my field_timer and just show secondes and after my timer show zero IF command work but in this way I add a field and it's not good.

How can I do this with other codes in Drupal 8 ?

You might use twig without method. It will print all configured content to be rendered without the selected fields/properties.

{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    {# Show #}
    {{ content }}
{% else %}
    {# Hide - print the content without the field_timer #}
    {{ content|without('field_timer') }}
{% endif %}

For some cacheability issues it is recommended to always print content.


View calc and multiple field collection lines I came here because I have a problem with view calc module and several lines in my field collection. So first the result of my view look like this :

All this fields are in the same content type, and I put sum calculation on each fields. But it's seems the value of the field is multiplied by the count of lines in my field collections. So for the first sum(Montant HT) the calcul done is :

8600 + 51600 + (3101.26 * 5) + 2962.99 + (42000 * 3)

For the column paid sum I don't know how the sum is calculated I doesn't understand.

I tried to use distinct but it didn't work, so how can I found the right sum for all my column ??

Thanks

Finally, I found a way to make it work. Although, maybe it's not a good solution but it worked.
Here is steps:

Find file views_calc_table.inc in views_calc module directory.
Change if ($query_alias == 'unknown') { to if ($query_alias ==
'unknown' || $field->field_info['type'] == 'field_collection') { in
line 238 under function add_aggregation_fields(&$view)

Remind，never hack core!


Programmatically activate users I have a custom module that allows administrator users to review users, and then approve their registration. I can't figure out how to programmatically trigger the 'approve' process.

Changing their role, or doing a regular user_save() with the new status doesn't seem to trigger rules associated with activating the user.

I'm sure there's a simple function for this, but I can't find it.

You have to rely on user_load to load the $user object, edit what's appropriate, in your case $user->status, then user_save the modified object.

You could also use db_query to update the users table directly if you know what you're doing.

As for triggering the rule, this post explains how to do it.

If you need to activate all users Programmatically via following methods.

$uids = db_query('SELECT uid FROM {users}')->fetchCol();
foreach (user_load_multiple($uids) as $account) {
  $account->status = 1;
  user_save($account);
}

This will invoke all other activities related to this action such as mail notification, other hook altering etc.

Entity API module:-

$users = entity_load('user');
 foreach ($users as $user) {
  if ($user->uid != 0) {
    $user->status = 1;
    entity_save('user', $user);
  }
}

Query update using db_update

db_update('users')
 ->fields(array('status' => 1))
 ->execute();

Note:- Reference link


Disable the /blog route I'm using Drupal 6.16. I would like to permanently disable the /blog path (and all its sub-paths, but not the Blog module.

Is this possible?

You can do this with hook_menu_alter() in a custom module or theme, for example using the following code.

function custom_module_menu_alter(&$items) {
  unset($items['blog']);
  unset($items['blog/%user_uid_optional']);
  unset($items['blog/%user/feed']);
  unset($items['blog/feed']);
  return $items;
}

Make sure to clear the cache.

REDIRECT ACCORDING TO THE GEOLOCATON

  function geo_redirect_init() {
  $geoPlugin_array = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );

   if ($geoPlugin_array['geoplugin_countryCode'] != "GB" && (!isset($_SESSION['non_uk_redirect']) || $_SESSION['non_uk_redirect'] === false)) {
     $_SESSION['non_uk_redirect'] = true;
     drupal_goto("/blog");
   }
  }


Load single value from multiple value image field in View I am trying to load a single value from a multiple value image field in View.
I am adding the field with a restriction to print only a single file. I am also filtering by delta(=0). Check the settings in the attachment.

However the view is loading all images attached to the field. How can I load only the 1st one?

Try to delete the delta field. You only need the content field and the restriction on the display values (like you did on the screenshot).

I think should be using agregation and unique option at query options inside advanced tab


Search API view - Displaying items that doesn't meet Facets criteria I have a search api view where I display houses with number of bedrooms in each of the house, and I'm using facet api to create filter so that for example if I would click on "2" it would only display houses that have only 2 bedrooms in it.

But I would also like to below this view (or as part of this view) display other results that doesn't meet the criteria (and that are filtered out by facets) and I'm really stuck with how this can be done.

In addition I only want it to happen with "Bedrooms" but not with "Bathrooms".

I hope someone can help I'm really stuck with this issue!

** small update 26.09.2015 **

I'm trying to achieve that now by combining two views together using views attachment and having "views negate" filter to work on values provided by exposed filter.. so far no luck.

And views attachments are being displayed UNDER pagination, instead of after the normal results which is not what I ideally would want to have.

After that I'm planning to change the normal exposed filter into BEF with links and style them as facets...

Might be wrong place, but my query is related to retrieving improper data. I am using facet to filter the result its working fine. But if I use solr slop to retrive data all the  record are proper and then try to filter the record using another facet Sector then the result displayed in location facet is improper. e.g

Initially search for England, it retrieves all data of England record include location, Sector Cont type data.Location details are displayed in location facet block. But when I do deep filter using Sector facet(sector records are within location searched I.e. England) I get records from Scotland location too.. Scotland location is listed in the location facet along with England. Not knowing what is going wrong afteer using Solr slop as without it all the data retrieved is proper.


Display node in multiple context I'm using Drupal 7, and this problem have been tormenting me these past few days :

let's say I'm using the basic content type Article, with basic view mode : full and teaser.

Now I'm creating a new content type Magazine, which reference multiple Article (with the module entity reference). On Magazine full view mode, I have set that every Article will be diplayed in teaser and linked to its content.

Easy isn't it ? Everything work fine. Noted that the red block in the sidebar are the same (with contexte module), and as the title.

Now I'm creating another new content type Book, which also reference multiple Article. On Book full view mode, Article are also displayed as teaser linked to  its content.
And now we have a problem when clicking on a Article from book: the sidebar and the title is from Magazine, and what I need is to display green block and title from Book.

What I get :

What I want :

Is there a way to achieve that ? By contrib or Custom ?

P.S. An article can be referenced in Book, or in Magazine, or both, or neither of them.

You can add query string or another argument to the link of article, for example:

node/[nid]/magazine or node/[nid]?ct=magazine
node/[nid]/book or node/[nid]?ct=book

After that you need to add visibility to the Book and Magazine block that appears in sidebar.

For Book block:

node/*/book

For Magazine block:

node/*/magazine

Hope it will help.

P.S. You can add argument or query string to the link of article through template_preprocess_node function by changing $vars['node_url'].

P.P.S. Just figured out that you can only use new argument, not query string.

Sorry all, I had completely forgotten about this un-responded question.

It's been a long time so I don't remember the details. After a deep dive in custom and contrib', I managed to get it done with view_mode_page and context

At first view_mode_page didn't seems to respond to my need, but after more thorough tests, it do the job pretty smoothly.


How to save/map uploaded image in term field of type image with storage location equals s3:// I'm having 1 field in a taxonomy = 'features' of type image. Image storage location is set to s3.

I have written a hook_form_alter for form_id = article (article is the content type)  where I have created an image field like:

$form['image_dir'] = [
    '#type'                 => 'managed_file',
    '#upload_location'      => 's3://s3-bucket',
    '#multiple'             => FALSE,
    '#description'          => t('Allowed extensions: gif png jpg jpeg'),
    '#upload_validators'    => [
      'file_validate_is_image'      => array(),
      'file_validate_extensions'    => array('gif png jpg jpeg'),
      'file_validate_size'          => array(25600000)
    ],

     ];

Now in my form submission, I'm trying to save/map this image into my term image field (field_vocab_image) . For this, I'm trying something like:

$term = Term::create([
    'name' => $term_name,
    'vid' => 'my_vocab_name',
    'field_vocab_image' => $img,
  ]);
  $inserted = $term->save();

where $img = $form_state->getvalues()['image_dir']; this image is coming from the custom field created in hook_form_alter.

Above code is successfully saving term name but when I go to edit term , image field is empty. Image is not getting mapped.

An Image type field should contain a file fid of an image file. The following should resolve your issue:

$img = $form_state->getValue('image_dir');

if (!empty($img['fids'])) {
  $img = reset($img['fids']);
}


Local server doesn't work, directly web on local server go to www I have a local host and website designed by drupal, I downloaded a website to local host but when I want to open local web directly go to www not to local, please can help me?

You probably have a full URL somewhere in your .htaccess file, in the root directory. Search for Rewrite directives.


HTML isn't rendering, HTML tags are being printed I added a view template views-view-fields--nieuws--page.html.twig to my theme.

The template is correct, when I edit it I see the results on my website.

{% for field in fields %}
  {{ field.separator }}
  {{ field.wrapper_prefix }}
    {{ field.label_html }}
    {{ field.content }}
  {{ field.wrapper_suffix }}
{% endfor %}

In page.html.twig I print the region like this:

{{ page.content }}

But my output has HTML tags in it, any idea how I can solve this?

EDIT: It appears my HTML is rendering at all through Twig

{% set hello = 'Hello' %}
{{ hello }}

outputs the  tags, too.

This is currently a known bug with the views-view-fields.html.twig template: https://www.drupal.org/node/2363423

You need to add |raw for print html  {{ field.content|raw }}  but you need to remove wrapper

{{ field.wrapper_prefix }} {{ field.wrapper_suffix }}


use a custom textgroup from t() I've defined my own textgroup using:

function foo_locale($op = 'groups') {
  switch ($op) {
    case 'groups':
      return array('foo' => t('foo strings'));
  }
}

The problem is that when I use t('bar') in a template, the entry generated in the database (e.g when viewing the template in /fr) is associated with the default textgroup. This doesn't allow me to use the foo textgroup I've previously defined, thus all my custom strings are mixed with the other "Built-in interface" ones.

How can I solve this?

t('String') always belongs to the "Built-in interface". If you have t() texts, then you don't need to create textgroups.

They are meant for strings that are not translated with that function, usually content/configuration. The I18n modules define lots of these groups for things like variables, menus, taxonomy terms and so on.

You can add strings to a custom text-group by first extracting them to a POT file. Then when you import them at /admin/config/regional/translate/import you can assign the strings to your text-group.

Or for user-defined strings you could use the i18n module.

NOTE: Text-groups will be removed in Drupal 8. See http://drupal.org/node/1188430


How to use t() function for a text with anchor links? I have a text that I must show in 5 languages. I am using t() for that. The text is:

  In case of any issues, please Contact Us for assistance.

I want the phrase "Contact Us" to be a link. So this is what I have done:

$text = t('In case of any issues, please ')."".t('Contact Us')."".t('for assistance');

I suspect that this might not be the correct way to do this as this will break the translation. I fear that the sentence will not be translated as a whole but in parts.

Am I right?

And if I am, what could be the correct way to do it?

You're absolutely correct; you should never concatenate strings with t(), the whole point is that it uses placeholders so you don't have to. Specifically:

// DO NOT DO THESE THINGS
$BAD_EXTERNAL_LINK = t('Look at Drupal documentation at !handbook.', array('!handbook' => ''. t('the Drupal Handbooks') .''));

$ANOTHER_BAD_EXTERNAL_LINK = t('Look at Drupal documentation at the Drupal Handbooks.');

$BAD_INTERNAL_LINK = t('To get an overview of your administration options, go to !administer in the main menu.', array('!administer' => l(t('the Administer screen'), 'admin'));

Instead of those you should use the following:

// Do this instead.
$external_link = t('Look at Drupal documentation at the Drupal Handbooks.', array('@drupal-handbook' => 'http://drupal.org/handbooks'));

$internal_link = t('To get an overview of your administration options, go to the Administer screen in the main menu.', array('@administer-page' => url('admin')));

See Dynamic or static links and HTML in translatable strings for full details.

This solution is work for you.

drupal_set_message(t('Payment Method Added Successfully -  '.l('add anchor link')),'status');


Programmatically place blocks? I'm using Drupal 7.  Right now, I have a main-menu navigation and Language switcher that exists in my website header.  I placed them there by going to the CMS>Structure>Blocks and hten dragging the blocks into the header region.

How do I programmatically situate these block in the header?

To alter the region where blocks defined by other modules are placed, you can implement hook_block_info_alter(), which receives the following arguments:

$blocks (passed by reference): the array containing the block definitions, keyed by module, and delta
$theme: the theme for which the blocks are being defined
$code_blocks: the blocks as defined from the hook_block_info() implementations, before their values are overridden by the values obtained from the database

This isn't the best form, but you can manually place content into the page array like this...

function mymodule_page_alter(&$page) {
  $my_content = _mymodule_render_mycontent();
  $page['my_region']['my_special_insert']['content']['#markup'] = $my_content;
}

Though you should stick to using Context or just core blocks.
Making new plugins isn't as bad as it seems. Just name files correctly, setup a trigger and a test. example.


How to switch existing file field from public to private? I have a Drupal 7 website with an existing file field set to store files in the public folder (i.e. sites/default/files).

I need to switch this one field so that it stores files in the private folder. Because the field has already been set to public and there are a number of existing files in place - the option to change the settings to private is not available in the user interface. I was wondering if anyone has a way to make this change manually in the database.

I know this was asked a while ago, but posting this in case anyone else needs it:

https://gist.github.com/thsutton/6878688

This gist takes the steps from this comment on d.o. and makes it into a simple script: https://drupal.org/node/1806220#comment-6960906

Here's the steps from the linked comment:

backup your site and db
copy the table for your field (and the revisions table for the field) to make a backup (in my case i copied: field_data_field_attachments to field_data_field_attachments_bk)
empty table field_data_field_attachments
go to drupal and the option to change the file system should be available, so change it
copy all data from field_data_field_attachments_bk back to field_data_field_attachments
go to drupal, select your content type, select your file field, in file path settings select retroactive update
click save and it will move all your files to the right place in file system and update your db to the new path

I ran through the script and field updates on several fields myself recently and it just works.

In the Home » Administration » Configuration » Media path you should set your private file path to sites/default/private.
This will automatically give you an option for public or private files while editing fields settings.

Then you can check in field settings and select private file .


Show all content related to child taxonomy terms in parent I don't think I could explain it any better here then I have in the title.

Basically if I have a taxonomy term call Parent and it has sub terms called Child 1 and Child 2. I'd like to be able to see any content related to Parent's sub terms (Child 1 & Child 2) appear on the Parent taxonomy page.

Thanks in advanced!

Looking around I have found the solution that helps me. It's a module called Hierarchical Select.

Use Hierarchical Select module and in manage display filed setting for that.

  This module defines the "hierarchical_select" form element, which is a
  greatly enhanced way for letting the user select items in a hierarchy.


Get path alias from NID (or node object) I have a node object, and I am trying to use it to get a given path in Drupal 8.

There was drupal_lookup_path() in Drupal 7 but I'm not seeing any equivalent or documentation for Drupal 8.

What's the new "Drupal" way to get a path from a node object?

Would it be something simple like $node->get('path')?

This seems like a simple question, but I'm just absolutely not finding any documentation on it.

Notice I do not want the path alias for the current path; I want the path alias for an arbitrary node, given a node object or a node ID.

To get the path for a node id use AliasManager::getAliasByPath:
Drupal 8
$alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid);

As per the new change record in Drupal 8.8.0 and above path.alias_manager is deprecated and path_alias.manager is introduced.
New syntax is as follows :
$url_alias = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid, $langcode);

I was hoping for a more "Drupalesque" solution, but here's what I made myself to do the job:

  function getPathFromNID($nid) {
    $db = \Drupal::database();

    $data = $db
        ->select('url_alias', 'u')
        ->fields('u', ['alias'])
        ->condition('source', '/node/' . $nid)
        ->execute()
        ->fetchField();
    return $data;
  }


Information added by Drupal.org on Distribution Hi am trying to make a Drupal 8 Distribution, all is well, but when I download it from drupal.org I get on all modules this information.

I would like that all contrib modules to have their default information. What do I need to setup in order to remove the profile package from contrib modules?

In the image below Drupal.org comment out the module information and added profile information. I do not want to add the profile information on to the contrib modules.

# core: '8.x'
# Information added by Drupal.org packaging script on 2017-08-15
# version: '8.x-1.0'
# core: '8.x'
# project: 'ace_editor'
# datestamp: 1502816349

# Information added by Drupal.org packaging script on 2018-01-18
version: '8.x-1.x-dev'
core: '8.x'
project: 'myprofile'
datestamp: 1516303995

So it's not confusing I don't want to remove the information from Drupal.org. Somehow Drupal.org is packaging the modules as part of the profile, and the result is the image below

I want to be able to see it normally like the image below

Whoever is getting the same error it is probably you got some patches and themes that are not from Drupal.org

The 2 links below helped me see what my problem was:

https://www.drupal.org/docs/develop/packaging-a-distribution/how-to-package-a-distribution-on-drupalorg

https://www.drupal.org/docs/develop/packaging-a-distribution/drupalorg-distribution-packaging-requirements


Fillable Fields in a View I want to submit several items with Views Bulk Operations - is there a module or method to add fillable fields to a view?

I think you need editablefield module. once this module is enable you can set any fields editable in your view. So when you visit your view page or block you can edit the field value there itself..
Nice Ajax is implemented in here, so it works very nice.. You can set it like double click to edit..

NOTE - I am not able to link the module with original URL at drupal.org so you can search for it in google with same name.


Disable displaying user picture in page--user.tpl.php I don't want to display the user picture on the user account page. It is not a field, so I can't simply hide it in display settings. How can I disable it in Drupal 7?

If you don't want it at all in the user registration you can navigate to : admin/config/people/accounts/settings and uncheck "Enable user pictures" on that page.

If you dont want it only on the user profile page you can add this snippet to template.php in your theme folder

function THEME-NAME_preprocess_page(&$variables){
  if (arg(0)=="user" || arg(0)=="users" ){
    unset ($variables['page']['content']['system_main']['user_picture']);
  }
}

If you want to disable the avatar picture in Drupal 7 for any roles in edit case, then you need to change this:

function hook_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "user_profile_form") {
    if(in_array ( {role_id}, array_keys ( $user->roles ) )) {
      $form ['picture']['#access'] = '0';
    }
}

This is working for my case.


With states, how to uncheck a disabled checkbox, but not check it when it becames enabled? I have a Form API checkbox that can be enabled and disabled by another ("parent") one:

$form['my_checkbox']['#states'] = array(
  'enabled' => array(
    ':input[identifier="parent"]' => array('checked' => TRUE),
  ),
);

Works like a charm, but now I want it to get cleared if it is dizabled. So I made my code look like this:

$form['my_checkbox']['#states'] = array(
  'enabled' => array(
    '[:input[identifier="parent"]' => array('checked' => TRUE),
  ),
  'unchecked' => array(
    ':input[identifier="self"]' => array('disabled' => TRUE),
  ),
);

Sadly, this also automatically checks that checkbox when it becomes enabled, and that's not what I want - I want to give my user an option, but not suggest him to check that field at all.

Can this "one way" action be achieved with '#states'? If so, how? Or is it always two way deal, and there is no option to uncheck on disabling without checking on enabling?

Note: I tried to use both disabled and enabled of self, and checked & unchecked of parent, with the same results.

I know I can achieve it with behavior, that's how I have it done now, but states api is there to avoid behavior's complexity and my use case seems pretty simple.

Turns out that with current implementation of states it is not possible. When condition gets true, state is applied, and when it gets false, state gets removed. No way around it so far, not without hacking core, so it's more feasible to write custom behaviors instead.

it's possible create states with unchecked.

See https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_process_states/7

[]'s


Add followers' list at the end of discussion I want to add following functionalities in Drupal 7.

Any forum-user can have followers, So I want to show followers list on forum-user's profile page. (Like this)
Those followers should be automatically subscribed to all the posts by that author.

I'm using Advanced Forum module. How to do this using Views module or any other possible way?

You can do this using Flag module.

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.

Creating Following & Followers

@NishantP's link helped me to understand a bit, but this post solved the issue perfectly. Its Author has elaborated nicely.

Modules used : Views, Flag, CTools


How to: Multilingual site with one front page that makes user choose a language first I want to have a front page like www.mysite.com/frontpage that shows up for every new visitor and helps him select a language and then move on to whatever language homepage the user selected.

You can create a custom block to display the language enable into site and a link to respective page of particular language.

To display the custom block in home page, you can use panels, create different template for the home page (page--front.tpl.php).

Read https://drupal.org/documentation/multilingual

Install https://drupal.org/documentation/multilingual

One configured your site will have /es and /en,  for example. Simply add now a front end ui linking to each one and that's it :-)


Redirect to login page if login fails from a login block? I have a login form block, when a user fail to login to the site I want to redirect him to the user/login page with the usual error message

You can do this by form_alter

function MODULE_NAME_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_block':
      $form['#validate'][] = 'my_custom_login_val';
      break;
    default:
      break;
  }
}

function my_custom_login_val($form, &$form_state) {
  $form = form_get_error($form['name']) . form_get_error($form['pass']);
  if($form != '') {
    $_GET['destination'] = 'user/login';
    drupal_goto('user/login');
  }
}

If you need like after the correct login redirect to a page use Login Destination

Got this to work in drupal 7, looks like you need to define both

$_GET['destination'] = 'user';

AND

$GLOBALS['destination'] = 'user';

$_GET['destination'] = 'user';
$GLOBALS['destination'] = 'user';
drupal_goto('user');


Getting a list/array of all organic groups a user is part of I have been searching online for awhile and so far I have been unable to find any og functions that will give me an array or list of all groups a user is a member of.  Does such a function exist?  If not, is there a sql query I could run that would give me this?

Assuming you are using Drupal 7 and latest OG you can use og_get_groups_by_user().

  Get the group IDs of all the groups a user is an approved member of.

The user groups can also obtained by loading the user.
For ex:
 $test_user = user_load(2);
   $groups = $test_user['og_user_node']; // returns all group ids of a user


Does commerce send an order notification email to site admin (site email) out of the box? Does commerce send an order notification email to site admin (site email) out of the box?

If not how do I do this?

It doesn't look like it does, no. There is, however, a rule set up to send the order notification to the user. It's called "Send an order notification e-mail".

You can easily clone this rule, but instead of sending the email to the owner of the order, send it to the admin's email address.

The admin user isn't available as a data selector for this rule, so you'll either have to expose it yourself somehow (not sure exactly how you'd do that without custom coding off the top of my head), or simply switch to 'direct input mode' and put the email address in manually.

You could "Clone" It's called "Send an order notification e-mail" and edit Data selector to site:mail (or switch to the direct mode to fill your e-mail address).