How to set up salt hash while installing Drupal 7? I am no expert in salt hash but while I was installing Acquia Dev, I noticed a variable $drupal_hash_salt, filled with a randomly generated string, in settings.php of newly installed Drupal 7 and a file called .hashlist under root drupal installation folder. Can someone help me understand the salting concepts in Drupal 7?

When I tried to import a new version of Drupal 7 site, I could not see any random string in that same variable and also no .hashlist file. I may be doing something wrong here. I tried googling around to see if I could find something useful but no luck.

So I have 3 questions

How to do salt hashing in Drupal 7 during/before installation process?
What kinds of data are being hashed (other than password)?
How can I extend this salting concept further?

Thanks a lot in advance.

I talk a bit about the new salts in my article on Improvements to Security in Drupal 7 which may help answer these questions.

Depending on when you need the salt you might be able to use drupal_get_hash_salt or you may be able to leverage the code it uses to create your hash.

Can you expand on "extend this salting concept" ?  What kind of extension do you want to do?

Salting is a standard part of hashing. You can read about salting on the php hashing pages. Changing your salt after the site is live may cause some problems in specific areas. My guess is that it depends on which modules you have installed and which features you are using. The one-time-login links are likely to stop working, but I'm not sure of other specific functionality that would stop.


How can I keep the files uploaded by filefield module even though users delete them on node edit form? On my site users can upload photos by using CCK image field.  However I would like to keep the  images uploaded by users on the server even though users delete them on node edit form.

I'm not sure if this is possible or not..  Or backing up the images frequently is the only way?

I used a module called Filefield Sources together with IMCE. And on the file field's configuration page, I enabled the "IMCE Browser" option for additional sources.

I did a few tests and any files attached to a node using the "IMCE Browser" method doesn't get deleted when the file is removed from a node on node edit screen. But files added through the normal "Upload" method do get deleted, so I think you should upload files using the IMCE Browser too as it has a file uploader as well.

I'm not sure how to remove or hide the actual default "Upload" method on the file field though.


hook_inline_entity_form_table_fields_alter add custom field Need some help with Inline Entity Form hook function hook_inline_entity_form_table_fields_alter.

I'm trying to add columns to the table that is visible when editing a specific node. I have been able to add fields and got the content to print too, but I need to add a checkbox. I've unfortunate not been able to find how to add other custom fields, so I wonder if someone has used this function before?

I guess it would be possible to add a "checkbox" fields to the content type itself, but in this case its more like a function rather than a value that I want to save.

Best,
Fever

Add the checkbox field to the referenced entity. Also, as an alternative you could use ief_table_view_mode module instead of hook_inline_entity_form_table_fields_alter and then set the fields that should be displayed in the table on the referenced entity in the Entity form table view mode.


Drupal Submenu on left sidebar I have added primary links and enable as expaned . Which is working fine for me

> About
>  - test1
>  - test2
>  - test3

Now i want when i click on about or nay test1, test2, test3 page

I want a block on left sidebar containing  sub menu items

test1
test2
test3

Anybody have an idea how to do this

I am using Bootstrap 3 sub theme

Thanks

You can use Menu Block Module. It will display your menu as a block.

1) Create a new menu block.

2) Select parent menu as a "About".

3) Select its region and page visibility to about page url (and inner pages urls too if you want to display it on inner pages.)

4)Click on save.


How to load an OpenLayers view into the content area with an AJAX link? I have a link in the side bar that links to a OL view.

I would like to Ajaxify it so the view is loaded into the content area without a page re-load.

I am using the Ajax link example in the Example module and saving the $output at ajax_link_response() with this code:

<?php
...
function ajax_link_response($type = 'ajax') {
  ...
  $view = views_get_view('view-name');
  $view->set_display('display-name');
  $view->exposed_input['myfilter'] = 'filter-value';
  $view->pre_execute();

  // $output = t("This is some content delivered via AJAX");

  $output = $view->render();
  ...

This solution works fine for non OL views but fails to load a OL view into the wrapper div. What am I missing?

Gist files:

ajax_example.module
ajax_example.misc.inc

NOTE FROM THE QUESTION'S AUTHOR:
This solution works for non OpenLayers views. It fails to build up the wrapper when the view is an OpenLayers though.

So the question remains to be answered.

You have to create a div wrapper where you are supposed to show the
ajaxified view content. You have to add the div wrapper in the
template file (MYTEMPLATE.tpl.php)
Create a module that will register the ajax link in hook_menu().
In the callback of the menu item you have to render the view content
using ajax_commands.

Sample code:

function MYMODULE_init() {
  // Add the Drupal AJAX library.
  // You can optionally provide a check to add AJAX library only on certain pages.
  drupal_add_library('system', 'drupal.ajax');
}

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

  $items['ajax-link/nojs'] = array(
    'title' => 'TITLE',
    'description' => 'DESCRIPTION',
    'page callback' => 'MYMODULE_ajax_link_callback',
    'page arguments' => array(1),
    'access callback' => PERMISSION,
    'type' => MENU_CALLBACK,
  );

  $items['ajax-link/ajax'] = array(
    'delivery callback' => 'ajax_deliver',
  ) + $items['ajax-link/nojs'];
}

function MYMODULE_ajax_link_callback($ajax) {
  // Check whether this is AJAX callback.
  $is_ajax = $ajax === 'ajax';

  if ($is_ajax) {
    // Your code to obtain view content in HTML format and store it in some variable say $ajax_content.

    $commands = array();

    $commands[] = ajax_command_replace('div.WRAPPER-YOU-ADDED-PREVIOUSLY', $ajax_content);

    return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );

  }
  else {
    drupal_set_message('Content added');
    drupal_goto();
  }
}


How to change node save button text? I found a discussion with some methods for d6 here http://drupal.org/node/344802
on how to change the node "Save" button text to sg else.

Any tips for d7? I would prefer to use form api.

you could use string overrides module or use hook:

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'name_of_form') {
    $form['actions']['submit']['#value'] = 'Your button text';
  }
}


Is there module that will add a drop down widget that auto-populates with a list of the site users? Looking to have a "field widget" that creates a drop down populated with the site's users.  I'm not sure "field widget" is the right term.  I just mean a widget that's used in a field.

Does anyone know of such a module?

You're looking for the References  module

  This project provides D7 versions of the 'node_reference' and 'user_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts. See http://drupal.org/node/533222 for details.

Similar module is Entity Reference

  Provides a field type that can reference arbitrary entities:

You can add a new field for user list by selecting User Reference as a field type and select list as Widget Type in your content type.

Here is the screenshot for that


Install a custom empty module break my custom style On Drupal 8, I have a style and a empty module :

/modules/kyna/nature/

/modules/kyna/nature/nature.info.yml

name: 'Nature Theme Structure and configuration'
type: module
description: 'Example Module description'
package: Kyna
version: VERSION
core: 8.x

When my module is installed and the cache clear, my custom theme is broken:

Why my custom and empty module break my custom theme please ?
Without the addon all is OK:

Thanks.

Is your custom theme called nature?

That's not allowed, you can't have modules and themes with the same name.


Programmatically set URL Alias when creating node in form plugin I'm currently importing data from a database to create nodes based on them. My node save code looks like this

$node = \Drupal\node\Entity\Node::create([
        'type'                 => 'issue',
        'title'                => $title,
        'body'                 => $body,
        'field_issue_category' => $term,
        'field_issue_type'     => 'publication',
        'field_pub_id'         => [
            'target_id'           => $publication_id,
        ],
        'field_issue_group' => $group_id,
        'field_date'        => $date,
    ]);
$node->save();

I also want to create a url alias based on the title of this node, which I create like this,

$nid       = $node->id();
$title     = preg_replace("/[\s_]/", "-", $title);
$path      = \Drupal::service('path.alias_storage')->save('/node/'.$nid, '/mypath/'.$title);

This successfully create a url alias that shows up in the URL aliases list in the URL alias config. However it doesn't show up in the URL alias field on the node edit page.

This creates a problem. One, the user can't see what the actual alias is.
Also I have a block plugin that puts every node of that type in a list on a page. It also displays the url to that node. I'd like the url displayed to be the alias like '/mypath/title' but Drupal only seems to know about the '/node/nid' path.

Is there a proper way to programmatically set a nodes url alias so that it still appears in the url alias field?

The node widget currently only shows aliases that have the same langcode as the node. https://www.drupal.org/node/2511968 will change that and also display aliases without a specific language.

But if the alias also doesn't work on the site then that sounds like something else also isn't correct yet. Does it work in that block if you create an alias manually in the UI? If so, compare the two records in the url_alias table, do you see a difference?

You can create an alias as part of saving the node, there is a path pseudo/computed field. Try adding this to your array:

'path' => [
  'alias' => '/mypath/' . $title,
  'pathauto' => PathautoState::SKIP,
]

That should create the alias correctly as well.

And last, if your alias is so predictable, you should look at Pathauto. That allows you to set up rules for creating aliases. Among other things, it has a ton of logic to deal with special characters and duplicates, your code will have a problem if you have two nodes with the same title, for example.


How to hide an exposed filter block if the view results are empty? I have an exposed filter block on the sidebar on my page. I want to hide the exposed filter block if the result of the view is empty. What is the best was to do it ?
Right now i am having some Jquery code in a no result behaviour textfield wich hides some block elements. But i dont like this solution. I prefer if the code is clean and the html code is completely removed.

@pierre's answer is a good one, however $view->total_rows is not always populated.

So you could do something like this instead, which will work no matter what:

function MODULE_views_pre_render(&$view) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if (empty($view->result) && empty($view->getExposedInput())) {
      $view->exposed_widgets = NULL;
    }
  }
}


How to change core's default services Dependency Injection is added to core, but there's no documentation to tell how developer can alter the default services. For example, I would like to change cache.bootstrap class to APC Caching.

You can look at LanguageTestServiceProvider to see how alterations are made. Or I can offer my class:

<?php
namespace Drupal\mongodb;

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

/**
 * MongoDB service provider. Registers Mongo-related services.
 */
class MongodbServiceProvider implements ServiceProviderInterface, ServiceModifierInterface {

  /**
   * {@inheritdoc}
   */
  public function register(ContainerBuilder $container) {
  }

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    foreach ($container->findTaggedServiceIds('mongodb.override') as $id => $attribute) {
      $container->setDefinition(substr($id, 8), $container->getDefinition($id));
    }
  }

}

Basically, in alter you need to use the getDefinition method, do something with the definition and then use the setDefinition method to put it back.

and then here's the relevant parts of mongodb.services.yml:

services:
  mongodb.flood:
    class: Drupal\mongodb\Flood\MongoDBBackend
    arguments: ['@mongo', '@request']
    tags:
      - { name: mongodb.override }


How to display items in Rules data selector in alphabetical order Because of my sites having a lot of fields, it takes me a lot of time to select fields in the Rules data selector, because they are sorted by date created.
What should I do to make them sorted alphabetically?

This is not an answer in any way, but

on around line 150 of rules.autocomplete.js, there is this code..

  Drupal.rules.autocomplete.prototype.success = function(data, request, response) {
    var list = new Array();
    jQuery.each(data, function(index, value) {
      list.push( {
        label: value,
        value: index
      });
    });

    this.cache[request.term] = list;
    response(list);
  };

That could possibly be where you need to add some code to rearrange the list. It might be there or it might be elsewhere.. It's a huge module.

If you manage it, create a patch for yourself that can be applied each time the module is updated.


Disable opcache.use_cwd for Drupal In PHP Opcache there is an option opcache.use_cwd. Disabling it improves performance, but in documentation mentioned that this may break existing applications:

  If enabled, OPcache appends the current working directory to the
  script key, thereby eliminating possible collisions between files with
  the same base name. Disabling this directive improves performance, but
  may break existing applications.

I would like know will Drupal break by disabling opcache.use_cwd? I know Drupal has a lot of files with same base name.

It really depends on your server and Drupal sites setup.

opcache.use_cwd=0 can ONLY be used if you can ensure that there is no duplicate filenames in the PHP files that the server PHP engine may run.

Note that PHP files are not only those with .php extension, but any of them that begin with the php symbol, like .module, .inc, .install, .tpl.php and so on (whatever extension could be used really).

There are a lot of Drupal setups where these duplicate filenames exists, so opcache.use_cwd=0 must not be used, like:

Overriden core tpl files from your custom theme or sub-theme.
Multisite configurations, or multiple drupal installations running in the same PHP engine.

Note that in a single PHP engine, OpCache (if active) is shared between ALL the PHP files that are running on it, so name collisions will happen if any filename is duplicated, if the subdirectory info is not appended.


Add values to a list (text) field that stores already content I want to add additional values to a list field, that stores already content.

In the field configuration i get of course:

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

Is it acceptable to ignore this message, add my values via the textfield without touching the current ones and save the field?

Yes, that message is very unfortunate. Ignore it.

Adding options is perfectly fine. Removing unused options is fine too. If you try to remove options that are still used, it will prevent you from doing so.


Create media from blob I am receiving a payload with blob files.

I would like to store them as files and create a media entity.

Here's the code I have to create the Media object

 if (!empty($payload['blobFile'])) {
  $name = str_replace(' ', '_', $payload['fileName']);
  $file = file_save_data($payload['blobFile'], 'public://' . $name, FILE_EXISTS_REPLACE);
  $content['field_media_file'] = ['target_id' => $file->id()];
}
$this->entityTypeManager->getStorage(....

It successfully creates the media content and attach a file to it.

Unfortunately the file is still blob I don't see a pdf or similar.

A file that comes in from a browser's Web API as a Blob is probably base64-encoded. PHP will not decode files in the POST or GET parameters. It is up to the PHP application to decode the file before saving.

if (!empty($payload['blobFile'])) {
  $name = str_replace(' ', '_', $payload['fileName']);
  $file = file_save_data(base64_decode($payload['blobFile']), 'public://' . $name, FILE_EXISTS_REPLACE);
  $content['field_media_file'] = ['target_id' => $file->id()];
}

It might also be useful to check if the binary is actually a PDF before saving, but that could be done in different ways based on opinion (loading via a PDF library, checking file headers, virus/malware scan).


Form Default Values missing on theming form Long story short when doing some basic theming on a drupal form the default / previously saved values refuse to display within the form fields (works without theming of course).  In the code exerpt below we are simply taking some for fields and sticking them into a drupal table to better organize the overall page.  This is within the hook_form_alter() framework.

$form['top'] = array(
  '#theme' => 'table',
  '#header' => array(array('data' => $form['#node']->title, 'style' => 'text-align: center; font-size: 1.6em; color:#333399; margin:1em 0; background: transparent; border: 1px solid #FFF; border-bottom: 3px solid #CCCCCC;', 'colspan' => 2,),),
  '#rows' => array(array(drupal_render($form['title']), drupal_render($form['field_order_id']),),),
  '#weight' => -8,
);

The form correctly outputs the form items and submits correctly, all that is missing is the default / previously saved values.  Nothing around the internet seems to have a workable solution either.

See examples for developers. You should not theme form in form alter hook. Do it in hook_theme(). In a module it looks like that:

function yourmodule_theme() {
  return array(
    'yourmodule_form' => array(
      'render element' => 'form',
      'file' => 'forms/yourmodule_form.inc',
    ),
  );
}

If you move elements around in form_alter(), they became different fields. If #tree is set to false (default), it does not interfere with submit, but it may interfere with defaults and validation.


Redirection after adding new groups and gnodes using group module I am using Group module and Drupal 8.

After adding a new group, the page will be redirected to the corresponding group page(ie. /group/5) but I want to change it to be the group edit page (ie. /group/5/edit)
After relating/creating an entity in group, the page will be redirected to the gnode page (ie. /group/5/content/116) but I want to change it to be the group content page (ie. /group/5/content)

I have read this issue but I want to solve this problem using either installing modules or creating a custom module.

I am new to Drupal and programming so it is great to have some clear and complete elaboration.

Thanks!

If The issue you posted about promises to solve your problem then your best bet would be to test the patch (always on a test server) and help this issue forward so others can take advantage of that in the future, because this is how drupal progresses mostly.

Just download the latest .patch that you find in the group modules directory
and open up up a command window (in windows) or shell in linux based systems and apply the patch

in a linux based system you could run the following commands, assuming group is in modules/contrib/group and using latest patch as an example

cd modules/contrib/group
wget https://www.drupal.org/files/issues/2817109-by-rachel_norfolk-ericras-How-to-redir.patch
git apply -v 2817109-by-rachel_norfolk-ericras-How-to-redir.patch

If the patch does not report any errors you will probably get a configuration field to do what you are asking and it would be great to post in the thread how the patch went for you.

More on patches here

If you want something different you should create your own module and implement a hook_form_alter to set setRedirect for both of the forms that you mention similar to what rachel_norfolk does in comment #3


Show / Hide login menu item not connected to node I have a login menu item that links to the login page of my website. I want to have the menu item disappearing when someone is logged in and an a sign out button appearing in its place.

Since the menu item is not connected to a node, i cannot alter it's visibility based on node access rights. I found Menu Item Visibility module but it is beta and it does not seem to be maintained. Is there a way to do this via Drupal?

If I have to make a custom module or js can you give me a link of a tutorial on how to do this?

For login add a menu item into main menu named as Login and path should be user/login.

For logout add a menu item into main menu named as logout and path should be user/logout

Now when user will be login then login menu will replaced by logout automatically. And when he/she will be logout then a login menu will appear again.


Drush cron - how to provide the actual task Based on this documentation the drush cron can be set up as

10 * * * * /usr/bin/env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
COLUMNS=72 /usr/local/drush/drush --root=/path/to/your/drupalroot
--uri=your.drupalsite.org --quiet cron

Where is the actual task being set here? I would like to invoke a certain url on each cron run. How do I provide that url to be ran in this cron or invoke a function using this drush cron.
Thanks.

From the Drupal perspective, you just need to implement hook_cron():

function MYMODULE_cron() {
  drupal_http_request('http://foo.bar');
}

That will be invoked on all normal cron runs (there are situations when it won't, e.g. if you have a cron management module installed that limits core cron operations).

But it might make more sense just to wget/curl that URL on a separate single-line cron job. Depends on your use case, but either will probably be fine.


Change the disabled status of a form element via Ajax I have a form built with the Form API. I have a field which is, at first, disabled. I want to change the status of that field to enabled when the user selects another contiguous field.

I have a working example of changing the callback URL of Ajax complete of that field, so the form is making a kind of OnChange and working well, but for some reason I am not able to change the disabled status.

Code. Here the 2 elements, first brand and next the model, which is disabled at the beginning.

 $form['brand'] = array(
'#type' => 'select',
'#title' => t('Brand'),
'#options' => $brands,
'#default_value' => $brand,
'#ajax' => array(
    'callback' => 'hook_models_update',
    'wrapper' => 'models_wrapper',
    'progress' => array(
        'message' => '',
        'type' => 'throbber',
    ),
),
);

 $form['model'] = array(
    '#type' => 'textfield',
    '#title' => t('Model'),
  //    '#description' => 'Please note available models change based on the brand selected.',
'#required' => FALSE,
'#autocomplete_path' => 'providers/autocomplete/' . $brand,
'#attributes' => array("placeholder" => t('Model')),
'#prefix' => '
',
'#suffix' => '
',
'#disabled' => TRUE,
);

Now the code for the "onChange" behaviour, which is a "throbber" called hook_models_update:

function hook_models_update($form, &$form_state) {
    unset($form_state['input']['model'], $form_state['values']['model']);
    $brand = $form_state['values']['brand'];
    $form['model']['#autocomplete_path'] = 'providers/autocomplete/' . $brand;
     $form['model']['#enabled'] = TRUE;
    // $form['model']["#disabled'] = FALSE
    return form_builder($form['#id'], $form['model'], $form_state);
} // function

I have tried with #enabled = TRUE and with #disabled = FALSE, with no successs.

I found the solution here:

Enable DropDown using Ajax Call

The code finally gets this:

     function hook_models_update($form, &$form_state) {
         unset($form_state['input']['model'], $form_state['values']['model']);
         $brand = $form_state['values']['brand'];
         $form['model']['#autocomplete_path'] = 'providers/autocomplete/' . $brand;
         unset($form['model']["#attributes"]['disabled']);
         $form['model']['#disabled'] = FALSE;
         return form_builder($form['#id'], $form['model'], $form_state);
} // function

The trick lies in these two lines:

     unset($form['model']["#attributes"]['disabled']);
     $form['model']['#disabled'] = FALSE;

Apparently, there has to be an unset and not of #disabled, but #attributes - disabled. Why this is so convoluted is beyong my comprehension.


How can I alter the list of available layouts in the Panels IPE? I'm trying to hide or remove several layouts from the layout selectors, so that users can only select from an approved list. I can do this successfully with hook_form_alter() code, but the Panels IPE isn't using a form for its layout selection tray. It seems the best method would be to use LayoutPluginManagerInterface somehow, so that any function that displays a list of available layouts will have the same list available, but so far I haven't figured it out. Is there a way to do this?

I've been trying to curate the Panels IPE more to my liking, and so far, it seems like overriding the controller is a decent way to go.

Say you're wanting to do this in my_example module:

Inside your custom module, create src/Controller/CustomPanelsIPEController.php. We want to extend from panels_ipe/src/Controller/PanelsIPEPageController.php into this file, and change the namespace declaration and change the class name to match:

<?php

namespace Drupal\my_module\Controller;

use Drupal\panels_ipe\Controller\PanelsIPEPageController;

/**
 * Contains all JSON endpoints required for Panels IPE + Page Manager.
 */
class MyModuleIPEController extends PanelsIPEPageController {
...

Now, we need to have our routing subscriber tune in to panels IPE being called, and re-route it to our new method. Create src/Routing/MyExampleRoutingSubscriber.php, and add the following:

namespace Drupal\my_example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class MyExampleRoutingSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('panels_ipe.block_plugins')) {
      $route->setDefault('_controller', '\Drupal\my_example\Controller\MyModuleIPEController:getBlockPlugins');
    }
  }
}

So now what will happen is our Panels IPE is now calling our method.

So now, we can do some more precise altering. For a simple example, when it comes to creating blocks, let's say we wanted to only give users a single module called 'awesome_blocks' for their choices when creating content.

public function getBlockPluginsData($panels_storage_type, $panels_storage_id) {
   $panels_display = $this->loadPanelsDisplay($panels_storage_type,
   $panels_storage_id);

   // Get block plugin definitions from the server.
   $definitions = $this->blockManager->getDefinitionsForContexts($panels_display->getContexts());

   // Assemble our relevant data.
   $blocks = [];
   foreach ($definitions as $plugin_id => $definition) {
     if ($definition['provider'] == "awesome_blocks") { // Added this logic
     ...

In this simple example, I've altered the logic to ONLY show blocks from the awesome_blocks module. Now of curse, I was altering the blocks, and you were asking about the layouts. The layouts can be altered the same way! Inside of the getLayoutsData() function that is in this same class, you could implement custom logic. To alter the layouts in the same way, we could add another function inside our custom Routing controller, inside the alterRoutes() method:

    if ($route = $collection->get('panels_ipe.layouts')) {
        $route->setDefault('_controller', '\Drupal\my_example\Controller\MyModuleIPEController:getLayouts');
    }

Now, just implement custom logic in the getLayouts method:

public function getLayoutsData($panels_storage_type, $panels_storage_id) {
    $panels_display = $this->loadPanelsDisplay($panels_storage_type, $panels_storage_id);

    // Get the current layout.
    $current_layout_id = $panels_display->getLayout()->getPluginId();

    // Get a list of all available layouts.
    $layouts = $this->layoutPluginManager->getDefinitions();
    $base_path = base_path();
    $data = [];
    foreach ($layouts as $id => $layout) {
        if ($layout['provider'] == 'my_layout_module') { // Added logic check here
        ...
        }

Hope this helps!


Custom node add/edit form - How to leave value of undisplayed field as set? I have a person node. There are some internal fields only the admin can change (e.g. Internal person code). Some other fields users with certain roles can change (e.g. first name...).

I have built a custom page using panels for this; I added the desired fields for normal users to the panel and Then I added a selection rule to the variant, enabling the variant for the normal users.

When a normal user opens the form and saves it, the internal fields, which only should be edited by the admin are set to NULL, because they were not submitted of course.

Is there any setting I missed? I don't want to add all the internal fields.

Thanks.

After some research I found out, that it is very important to have the full node form be added to the panel to get all fields (like publishing option, date created...), so the submit routine gets data for all node fields.

You can show/hide fields for certain roles using the Field Level Permission Module for the standard Drupal roles. But I like to use the OG roles to define the permissions. There is already an OG function for this under admin/config/group/permissions.

I did it this way:

Activate the node/%/edit page under pages
Create a variant for editing node of a certain type
Add all required fields, which should be shown to the normal user to the form and layout it
Add the submit buttons to the form
Add General Form to the panel, so that all fields, which are not build before are added to the form (like publishing status, author, date created...)
Goto admin/config/group/permissions and set the edit rights for the fields, the normal user should not see. The fields then are not on the node form anymore, but the values remain in the database.

I hope that helps someone else.


Content Type Segmentation I need to know if there is a way to create a content type and within the content type to create a field which this field should be segment.

For Example :

at the beginning i will have an image,  this will be the default image.
and in case i will choose an option like to display only for authenticated user another image field will be opened , and in the display all unauthenticated users will see the default image and authenticated users will see the second image.

Is there something like this ?

Thanks

You can create a template for that specific content type like

node--yourcontenttype.tpl.php

and inside you can check for the user roles like so

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // print one image
} else {
  //print the other one
}


How to substitute a value of an exposed filter for views? I have a view with an exposed filter with taxonomy tree. Each term can be selected or unselected. If some parent term is selected but every of its child terms isn't selected then all the children terms also should be added to view filter.

But if I select one children term after it, the view should be filtered only by this children term (not by all children terms).

I decided to solve this problem trying to add children terms in the view parameters. By my idea, the view should use this parameters for its execution.

But, unfortunately, I can't understand where to add these params. I tried to use different view hooks, having tried to add them in vars $view->exposed_data, $view->exposed_raw_input, $view->exposed_input. No result.

I also tried to add them in the submit function of the exposed filters form. No positive result also.

Could you clarify me, where can I add new params into the view ?

For example, a user selected term1. In this case term2 and term3 should be added to the view parameters programmatically. And after it, views should use parameters term1, term2 and term3.

I hope, I've described the problem clearly

I solved a similar issue using hook_views_pre_render(&$views).


Content authoring and CKEditor In my drupal 7 site under Configuration » Content authoring

The following are available:
Filtered HTML
Full Html
Plain text
PHP code

However, under Content authoring » CKEditor

Only the following profiles are available:
Advanced - Filtered HTML
Full - Full HTML

Plain text and the PHP one are missing. Is this normal? Why would this be the case? I am happy to uninstall modules or redo whatever I need to in order for this to be as it should be.

Also, should Filtered HTML and Plain text input formats be editable in the Content authoring section?

I believe what you see is normal. In any case, having the WYSIWYG editor for Plain text would result in that the output would display the HTML source code. Using the WYSIWYG editor for PHP input format would probably reformat and destroy the PHP code.


Views: How to sort in Table format naturally Create view.
Select Format: Table.
Under the Table Settings toggle Sortable on.
Fields gets arranged/sorted unnaturally 1 2 3 4 40 5 50 51 6 60, etc. both ways ascending and descending.

The module Views Natural Sort does not solve the problem, it works only with fields under Sort criteria settings. And it's pretty broken in overall, the option to sort doesn't even appear in my Views.

We want to sort in normal natural way 1 2 3 4 5 6 7 8 9 10

Try to install Views_bootstrap module.

Then in views/Format select Bootstrap Table

  Don't forget the Settings


Add #ajax event to a custom composite element I have created a custom composite element for Webform (6.0) that has a date field and a select field. The idea is when a user picks a date, an API call is made that returns available time slots to make a booking.
I am familiar with how this is normally done in FormBase forms and inspecting form_state to inform build values, but I am stuck here.
class WebformTourAvailabilityComposite extends WebformCompositeBase {

  /**
   * {@inheritdoc}
   */
  public static function getCompositeElements(array $element) {
    $date_format_entity = DateFormat::load('html_date');
    $date_format = $date_format_entity->getPattern();

    $elements = [];

    $elements['tour_date'] = [
      '#type' => 'date',
      '#title' => t("Tour Date"),
      '#date_date_format' => $date_format,
      '#date_year_range' => '0:15',
      '#attributes' => [
        'min' => '[webform_submission:created:html_date]',
        'onkeydown' => 'return false'
      ],
      #'#datepicker' => TRUE,
      '#datepicker_button' => TRUE,
      '#date_label_position' => 'invisible',
      '#required' => TRUE,
      '#ajax' => [
        'callback' => 'mymodule_get_date_options',
        'wrapper' => 'available-times'
      ]
    ];

    $elements['tour_time'] = [
      '#type' => 'select',
      '#title' => t('Tour time'),
      '#prefix' => '
',
      '#suffix' => '
',
      #'#options' => [],
    ];

    return $elements;
  }

}

in mymodule.module:
function mymodule_webform_submission_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $selected = $form_state->getValues();

  if (isset($selected["select_appointment"]["tour_date"])) {
    $response = \Drupal::httpClient()->get('https://nestiolistings.com/api/v2/appointments/group/123/available-times');
    $options = json_decode($response->getBody()->getContents(), TRUE);
    #$form["elements"]["step_1"]["select_appointment"]["tour_time"]["#options"] = $options['data'];
    $form["elements"]["step_1"]["select_appointment"]["#webform_composite_elements"]["tour_time"]["#options"] = $options['data'];
  }
}

function mymodule_get_date_options(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  return $form;
}

Which method I should override or use in the Webform ecosystem, or if this needs to be a composite at all and I can do this some other way?

Turns out I was pretty close, an external module was causing interference while authenticated (was getting a post max size exceeded error when submitting the form) on the front end. Unrelated to Webform.
You can add ajax to composite elements and react to them in afterBuild like so (or in your own custom form elements, added to the composite):
class WebformTourAvailabilityComposite extends WebformCompositeBase {

  /**
   * {@inheritdoc}
   */
  public static function getCompositeElements(array $element) {
    $date_format_entity = DateFormat::load('html_date');
    $date_format = $date_format_entity->getPattern();

    $elements = [];

    $elements['tour_date'] = [
      '#type' => 'date',
      '#title' => t("Tour Date"),
      '#date_date_format' => $date_format,
      '#date_year_range' => '0:15',
      '#attributes' => [
        'min' => '[webform_submission:created:html_date]',
        'onkeydown' => 'return false'
      ],
      '#datepicker_button' => TRUE,
      '#date_label_position' => 'invisible',
      '#required' => TRUE,
      '#ajax' => [
        'callback' => ['\Drupal\mymodule\Element', 'refreshTimes'],
        'wrapper' => 'available-times'
      ],
      '#prefix' => '
',
    ];

    $elements['tour_time'] = [
      '#type' => 'select',
      '#title' => t('Tour time'),
      '#suffix' => '
',
      '#after_build' => [[get_called_class(), 'afterBuild']],
      '#validated' => TRUE,
    ];

    return $elements;
  }

  public static function refreshTimes($form, FormStateInterface $form_state) {
    return $form['elements']['tour_time'];
  }

  /**
   * Performs the after_build callback.
   */
  public static function afterBuild(array $element, FormStateInterface $form_state) {
    $client = \Drupal::service('mymodule.client');
    $selected = $form_state->getValues();

    if (isset($selected['tour_date']) && strlen($selected['tour_date'])) {
      $times = $client->getAvailableTourTimes($selected["tour_date"]);
      $element['#options'] = count($times) ? $times : ['' => '- Select -'];
      $element['#description'] = count($times) ? '' : 'There were no available times found for the date you selected. Please choose another date.';
    }

    return $element;
  }

}

Note that your form keys will vary depending on your form, what you name fields, etc. On afterBuild, in this case, if the date picker has a value submitted, it will call a remote API and replace the options in the select with values.


Non blocking drupal_http_request I am trying to integrate with a third party API using REST. I want to make a few calls to the API without waiting for the result to be back (The calls are action calls ie they perform some operation in the third party software and hence I don't need to wait in Drupal).

In short I want to make a non blocking http call in php. (similar to asynchronous call in java-script.)

Please let me know if this is possible.

Note : I know of httprl module. But it is not of much use as I do not want to make calls in parallel. I rather want to make a non-blocking call and then carry on with my Drupal specific actions.

No, that's not possible with drupal_http_request().

You'll need to use httprl, curl_multi, or something like that.


Is it possible to create a menu item and leverage path aliases? I am trying to create a menu item that loads a view mode that calls the callback function with the path alias.

$items['node/%/%'] = array(
  'page callback' => '_node_view_load',
  'page arguments' => array(1, 2),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK
 );

function _node_view_load($node_id, $view_mode = 'default') {
  return drupal_render(node_view(node_load($node_id), $view_mode));
}

This works if you go to /node/%/view_mode. However, it does not work if you got to /alias/view_mode. I get page not found. Is there a way to bind menu items to path aliases?

You'd have to extend the pathauto system to handle your specific pattern, like it does for node/x/feed items.


Using "Model Entities" Module to Create Custom Entities Model Entities: http://drupal.org/project/model

I've been trying to use this contrib module to create my own entity (the "client" entity). Steps I've undertaken:

Search and replaced "model" with "client", "Model" with "Client".
Upon enabling the module, the "client type" appears in "admin/structure", and I create a "client type" from the UI.
Go to "admin/content/clients" and added a new client, but the new "client" entity does not appear.

So far debugging has gotten me this far:

The database is being populated correctly - so the creating functions (and rest of CRUD - tested via direct calling) is working.
I checked entity_load('client') and it's loading the client entities properly as well.

So I suspected it's something to do with the custom "views" that the module is implementing. And indeed, it did not register the custom view properly since it did not appear in "admin/structure/views".

I can't seem to pin-point the error here. Any idea why the view isn't registering?

I know this question is a little old, but just in case you (or others) still need assistance...
Make sure the hook_views_default_views() was renamed properly.
If your module name is "client" then it should be client_views_default_views().

I was recently working with the Model Entities module and ran into the same issue. Turns out I missed renaming that function.

If it's named correctly, then I suggest comparing your file to the model.views.inc file to find the difference.


What limits the options in a Bulk Operations Menu (beyond their initial settings) regarding rule components? I created a View Bulk Operation (VBO) that should allow an admin user to change the author of several nodes at once.  Everything works fine when I am logged in as the root user.  However, when I am logged in as a different kind of admin user, the VBO drop down menu is empty.  I am assuming that there is a setting somewhere that is preventing the menu item(s) from appearing in the drop down list.  What could be causing this to happen?  I checked my permissions, but there did not seem to be a VBO related permission for the specific drop down option that I have enabled for this.

My setup uses a flag to target a user and a rules link to target an entity.  the rules link triggers a 'rule component rule' which changes the author of the target node.  I have a view table that renders this rule link as a column and also has a VBO column that can trigger the rule link for multiple columns.

Edit: I added a new test VBO action which calls a rule component rule (that only sets a Drupal message.)  This option does not appear for the admin users either.

Edit: the admin user role has full read and write permissions for the content type.

Edit: After enabling all VBO permissions for everyone, the option is still not available.

Edit: I noticed that the Rules Link is not shown in the view for the other admin role.

Edit: After enabling the permissions for all Rule Links, the link is displayed, but still not the VBO option.

Edit: I was able to add generic VBO operations (which could be seen by the admin roles.)  This problem only seems to effect VBO operations that are created by rules.

If you are adding operations using Rules Component then you have to set the permission.

Edit your rule component and under the settings there will be Configure access for using this component with a permission., set your permission here.


db_select() which selects nodes which have a certain term I feel like this should be a simple question and therefore have been answered before, but all of the other Stackexchange answers I find doesn't seem to directly answer the question (at least as far as I can understand).

$query = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('status', 1)
      ->condition('type', 'photo_gallery')
      ->orderBy('created', 'DESC')
      ->execute();

This is my db_select() to fetch a list of nodes.

My photo_gallery content type also has a term reference field named field_tags which references the tags taxonomy.

How do I select a list of nodes from the db and only get nodes which have a particular tag?

saadlulu's answer is also correct, but since it doesn't specifically address the topic of taxonomy terms, I want to post my solution which I got working just a few minutes ago and explain what is happening so that some other newbie who comes along can understand what is happening well enough to alter it for their own uses.

My nodes are of type photo_gallery and they have a taxonomy terms field called field_tags and I want to grab all of the nodes which have the term for $term_id

$query = db_select('node', 'n');
$query->join('field_data_field_tags', 't', 't.entity_id=n.nid');
$result = $query
  ->fields('n', array('nid', 'title', 'created'))
  ->fields('t', array('entity_type', 'bundle', 'field_tags_tid', 'entity_id'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'photo_gallery')
  ->condition('field_tags_tid', $term_id)
  ->condition('status', 1)
  ->condition('type', 'photo_gallery')
  ->orderBy('created', 'DESC')
  ->execute();

The part I didn't know/understand was how the tables were structured behind the scenes for things like a term reference. When I looked into the actual SQL tables, then it became clear. The connections between a node and a taxonomy term are stored in a separate table and knowing which table that is was one of the big questions.

So, my field_tags data is stored in the field_data_field_tags table. I grabbed the nid of one of my nodes to see what the data looked like.

mysql> select * from field_data_field_tags where entity_id=1082;
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
| entity_type | bundle        | deleted | entity_id | revision_id | language | delta | field_tags_tid |
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
| node        | photo_gallery |       0 |      1082 |        1082 | und      |     0 |              5 |
+-------------+---------------+---------+-----------+-------------+----------+-------+----------------+
1 row in set (0.00 sec)

Once I understood the info above, then I could see that I needed to join to the field_data_field_tags table and do that join on entity_id=nid.


How to create a page showing only articles in a certain language? I have several articles on my website in different languages. I would like to create a page on which only the articles in a certain language are displayed based on the url.

Only show articles in english when user is on www.website.com/en/blog
Only show articles in french when user is on www.website.com/fr/blog

How can I do that? I have Internationalization, Entity and Views.

My language detection/selection settings are, in the order:

URL (path prefix)
Default
User

I have two languages: english (default) and french.

All my articles have the vocabulary "Blog (taxonomy) > story (term)"

The only thing is, I'm not very good at using Views so I would need a really "step by step" explanation, because it is not really intuitive to me.

Many thanks for your help!

Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

Note: The Internationalizations Views module only has an alfa version for D7, but right now there are over 41K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +41K users can't be wrong, right?

PS: I'm assuming this question is about D7.


Why does the same Rule Calculating The Sell Price Of A Product fire multiple times? I'm having dreadful performance with Commerce Kickstart 2. Trying to troubleshoot.

I noticed that when viewing any Product in the catalog, the Rules Evaluation log looks like the log below.

Questions:
1. Why is the event Calculating the sell price of a product firing multiple times?

Why is the rule "Apply a discount to a given order" firing? The product I'm viewing has nothing to do with the reaction rule or the cart?

This adding a lot of unneeded overhead, right? How do I stop it?

    0 ms Reacting on event Calculating the sell price of a product.
    7.329 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
    7.698 ms The condition data_is_empty evaluated to FALSE [edit]
    7.903 ms The condition entity_has_field evaluated to TRUE [edit]
    8.669 ms The condition data_is evaluated to FALSE [edit]
    8.676 ms AND evaluated to FALSE.
    8.694 ms Finished reacting on event Calculating the sell price of a product.

0 ms Reacting on event Apply a discount to a given order.
0.256 ms Evaluating conditions of rule 10% Of AH-10. [edit]
0.854 ms The condition commerce_order_contains_products evaluated to FALSE [edit]
0.862 ms AND evaluated to FALSE.
0.876 ms Finished reacting on event Apply a discount to a given order.
0 ms Reacting on event Calculating the sell price of a product.
0.164 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.317 ms The condition data_is_empty evaluated to TRUE [edit]
0.324 ms AND evaluated to FALSE.
0.336 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.376 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.656 ms The condition data_is_empty evaluated to TRUE [edit]
0.673 ms AND evaluated to FALSE.
0.7 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.223 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.407 ms The condition data_is_empty evaluated to TRUE [edit]
0.42 ms AND evaluated to FALSE.
0.439 ms Finished reacting on event Calculating the sell price of a product.
0 ms Reacting on event Calculating the sell price of a product.
0.221 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.384 ms The condition data_is_empty evaluated to TRUE [edit]
0.393 ms AND evaluated to FALSE.
0.418 ms Finished reacting on event Calculating the sell price of a product.

0 ms Reacting on event Calculating the sell price of a product.
0.398 ms Evaluating conditions of rule Unset the price of disabled products in the cart. [edit]
0.67 ms The condition data_is_empty evaluated to TRUE [edit]
0.687 ms AND evaluated to FALSE.
0.714 ms Finished reacting on event Calculating the sell price of a product.

This is because the price is calculated during preparation for display where the field is rendered on the page, for the Add to Cart form to determine product availability, and for recalculation of any instance of that product in your cart. I believe we tried caching calculated prices in the product entity at one point in time to avoid duplicate calculation, but that obviously didn't stick. I don't have a solid recommendation here, just wanted to provide the info requested. Also, note that cart price refreshing is adjustable but is intended to happen in realtime with the full cart context. I'd think you could safely find a way to eliminate the duplicate calculation between the price field and cart form, but you'd want to do it without interfering with the cart refresh.


How to override hook_page_build? I have below code coming from External Link module in Drupal 7:

/**
* Implements hook_page_build().
*/
function extlink_page_build() {
   $path = drupal_get_path('module', 'extlink');
   drupal_add_js($path .'/extlink.js', array('every_page' => TRUE));
   drupal_add_js(array('extlink' => array(
     'extTarget'     => variable_get('extlink_target', 0),
     'extClass'      => variable_get('extlink_class', 'ext'),
     'extLabel'      => check_plain(variable_get('extlink_label', t('(link is external)'))),
     'extImgClass'   => variable_get('extlink_img_class', 0),
     'extSubdomains' => variable_get('extlink_subdomains', 1),
     'extExclude'    => variable_get('extlink_exclude', ''),
     'extInclude'    => variable_get('extlink_include', ''),
     'extCssExclude' => variable_get('extlink_css_exclude', ''),
     'extCssExplicit' => variable_get('extlink_css_explicit', ''),
     'extAlert'      => variable_get('extlink_alert', 0),
     'extAlertText'  => variable_get('extlink_alert_text', 'This link will take you to an external web site. We are not responsible for their content.'),
     'mailtoClass'   => variable_get('extlink_mailto_class', 'mailto'),
     'mailtoLabel'   =>   check_plain(variable_get('extlink_mailto_label', t('(link sends e-mail)'))),
   )), 'setting');
}

I want to add below code from above function only if my some condition is true (which will be based on some user filed) , without overriding files of module it self:

drupal_add_js(array('extlink' => array(
    'extTarget'     => variable_get('extlink_target', 0),)), 'setting');

I am not getting any solution how to override this function thorough my custom module, Please suggest !

To make more clear I just want to add condition in above function so that js will only get added if condition according to user field is true.

UPDATE: I have tried like below code but its not working, please suggest what I am doing wrong My custom module name: custom_overrides

function custom_overrides_page_alter(&$page) {
   global $user;
   $userid = $user->uid;

    if($userid){
        $path = drupal_get_path('module', 'extlink');
        drupal_add_js($path .'/extlink.js', array('every_page' => TRUE));
        drupal_add_js(array('extlink' => array('extTarget' => variable_get('extlink_target', 0),)), 'setting');
  }
}

Thanks!

In hook_page_alter you can override js settings just by using drupal_add_js like you pasted above.


Rules does not have any action for publish selected content In admin/content page we have some update options. I want to execute a Php code only when I use publish selected content or unpublished selected content on that page.

This rules should be fired JUST when I publish/unpublished selected content

You can use drupal's hook_form_alter() for firing your PHP code. Check below example:

function contr_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'node_admin_content'){
    $form['admin']['options']['submit']['#submit'][] = 'CUSTOM_SUBMIT_HANDLER';
  }
}

and then you can write your PHP code in CUSTOM_SUBMIT_HANDLER function as below:

function CUSTOM_SUBMIT_HANDLER($form, $form_state){
  if($form_state['values']['operation'] == 'publish'){
    // Do your stuff when PUBLISH here.
  }elseif ($form_state['values']['operation'] == 'unpublish') {
    // Do your stuff when UNPUBLISH here.
  }
}


EntityFieldQuery with date field I am running the following code, retrieving a list of job openings that will expire in 7 days.

$triggerDate = new DateTime();
$triggerDate->add(new DateInterval("P7D"));

$query = new EntityFieldQuery();
$query->entityCondition('entity_type','node')
  ->entityCondition('bundle','job')
  ->propertyCondition('status',1)
  ->fieldCondition('field_expires','value',$triggerDate->format('Y-m-d'),'=');

This is returning 0 jobs, even though I have several that will expire in 7 days.  For example, one of my job nodes, has the following value

[field_expires] => Array
     (
         [und] => Array
             (
                 [0] => Array
                     (
                         [value] => 2013-05-09T00:00:00
                         [timezone] => America/Los_Angeles
                         [timezone_db] => America/Los_Angeles
                         [date_type] => date
                     )

             )

     )

When I leave the filter off altogether, the query succeeds and retrieves all items.  I've tried many variations of the date format including Y-m-d\T00:00:00 and Y-m-d 00:00:00.

The field is of type: Date (ISO format).  What am I doing wrong?

This works perfectly fine:

$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type','node')
  ->entityCondition('bundle', 'product_display')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_expires','value', '2013-04-30T14:02Z', '>')
  ->execute();


How to uninstall one site of a multi-site? Things are bit messed up in one of my sites, partly because of modules that did not clean up after themselves when I disabled them and partly because I tried to clean up for them, which of course, only partially worked.

So I want to remove this site and start it over again with a fresh install. But I don't see anything on how to uninstall or remove a site.

(This is a development environment, of course!)

Thanks for your help.

Nothing to it as long as they have separate databases:

Deactivate the virtualhost pointing at your site and restart apache
Backup and delete the database for that site
Backup and delete the site folder inside Drupal_root/sites where Drupal_root is your core Drupal repository

Then rebuild however you please.


BlockContent::load for addtoany_block returns null I am trying to load the "AddToAny Buttons" block of AddToAny module inside a controller. My idea is to render the block content as a part of the page. I have verified the block id of "AddToAny Buttons" block in the Addtoany module's block plugin file which is 'addtoany_block'. But BlockContent::load('addtoany_block') returns null.
Could somebody help me identify where I'm going wrong?
Here is the code snippet

$block = \Drupal\block_content\Entity\BlockContent::load('addtoany_block');
$render = \Drupal::entityTypeManager()->
getViewBuilder('block_content')->view($block);

The addtoany_block is not a block content, but it's a plugin block.
So if you want to get the its build programmatically you should:
1. Get the block configuration (addtoany_block settings).
2. Create an instance of the block.
3. Get the build.

Try the following:

// Block manager.
$block_manager = \Drupal::service('plugin.manager.block');
// Load Block settings / Settings.
$addtoany_config = \Drupal::config('addtoany.settings')->getRawData();
/** @var \Drupal\addtoany\Plugin\Block\AddToAnyBlock $plugin_block */
$addtoany_block = $block_manager->createInstance('addtoany_block', $addtoany_config);
// Get Block build.
$build = $addtoany_block->build();


`drush uli` generates correct link but results in 'Access Denied' I have set up a Drush alias for my website (hosted on a shared hosting), the alias works correctly, because commands like drush status, drush cc all, etc. work. The problem comes with drush uli. It generates the one-time login link, the domain is correct, everything looks all right, but when entered into a browser, it results in standard Drupal

  Access Denied

page.

Part of setting up the alias and some interesting issues around path-alias-es, relations to database settings, it's usage and relevancy the aliases is originally discussed in Drush issues page on GitHub.

Technical information:

This is a clean Drupal 7 installation, without contrib modules.
I can log in using password (even using password set via drush upwd using the same alias).
I have checked all possible sources (like truncating sessions table, etc.) discussed in similar but yet different issue on StackExchange.
I have tried different browsers and cleared browser caches and cookies as suggested in various similar discussions on Drupal.org, all without luck.

Drush alias:

$aliases['myalias'] = array(
  'uri' => 'mysite.com',
  'root' => '/home/mysite.com/web',
  'path-aliases' => array(
    '%drush' => '/home/.composer/vendor/drush/drush',
   ),
  '%files' => '/home/mysite.com/web/sites/mysite.com/files',
);

The alias works correctly for other commands like clearing caches and drush status confirms that Drupal is bootstrapped correctly.

This can happen when the user is blocked. Setting the status to 1 in the Users table may resolve it.


How to Retrieve Env Var in Drush Is there a way to retrieve shell variables in Drush? I cannot find anything in Drush API docs. If there is no way, how does one handle environment (dev, staging, testing etc.) configurations? Any help is much appreciated. Thank you.

What do you mean by "in Drush"?

If you are working in a Drush commandfile (e.g. writing your own Drush command), then you can get environment variables via php using the getenv function.

If you are calling Drush from bash, then you can use bash to expand environment variables (e.g. drush dl --destination=$HOME/.drush)

If you are wondering what to do because you have set up your web server to define environment variables that you are using in settings.php to bootstrap Drupal, then you cannot read these from Drush or bash, because they are only defined by your webserver.  Try defining equivalent variables in your .bashrc.


Why can't I have hyphens in my db_query() I am trying to SELECT all the rows in my MySQL where a field matches a variable using the db_query() function. The variable is not a user input, it is retrieved from another database table based on the user currently logged on, so basically the variable is safe, but it does contain hyphens. Obviously without the hyphens the queries won't work properly, but for some reason if I include the variable the database query  stops working.

When I say it stops working, I can use the functions in the object that is returned but whenever I try to get individual fields I get an error. In case it affects any suggestions, the query has two more 'comparisons' but without the third, containing hyphens, the query could return more than one row. I only want either one or zero rows to be returned.

Anybody any ideas?

UPDATE: The code I have looks something like this:

global $user;

        $ukey = "A-B-C";

        $result = db_query("SELECT NAME FROM ukeys WHERE uid = :uid AND EMAIL = :email AND GENERATEDKEY = :key", array(
            ':uid' => $user->uid,
            ':email' => $user->mail,
            ':key' => $ukey
        ));

        if($result->rowCount() == 1){
            $name = $result->NAME;

And the error comes on the bottom line where I try to get the NAME from the results.

Make sure you use proper placeholders in your db queries, as per the Drupal API.

E.g in D7:

$query = db_query("SELECT * from {foo} WHERE bar = :bar", array(':bar' => $bar));

or

$query = db_select('foo', 'f')
  ->fields('f')
  ->condition('bar', $bar, '=')
  ->execute();

More info:

Database API
db_query
db_select

UPDATE: Now the the original SQL has been posted, the problem appears to be

Lack of use of fetchObject, fetchAssoc etc.. on the database result

You should be able to use

if($result->rowCount() == 1){
  $name = $result->fetchObject()->NAME;
}

As an aside, better to limit the query if you only want one record returned, e.g

$name = db_select('ukeys', 'u')
  ->fields('u', array('NAME'))
  ->condition('uid', $user->uid)
  ->condition('EMAIL', $user->mail)
  ->condition('GENERATEDKEY', $ukey)
  ->range(0,1)
  ->execute()->fetchfield();

That will return the $name value only, or FALSE if no record exists.


Commerce Flat Rate Shipping not being added in Paypal Express Checkout I'm hoping this is straight forward, but I can't seem to find the answer.

I have Drupal Commerce setup and working properly.
I have Commerce shipping setup to use a flat rate of $7.00
I have Commerce PayPal Express checkout setup.

Product is $40.00
Flat Rate shipping is $7.00
Once customer adds shipping the total reflects $47.00
When the customer goes to PayPal to pay, PayPal is only showing $40.00

For some reason, the shipping amount is being removed once the customer hits PayPal.

Anyone know what's wrong?

Did you enable shipping service selection in the order confirmation
  checkout pane provided by the PayPal Express Checkout module? – Ryan
  Szrama

Thanks again Ryan for pointing out another not so obvious answer!

To "enable shipping service selection in the order confirmation checkout pane provided by the PayPal Express Checkout module"

Go to:
admin/commerce/config/checkout/form/pane/paypal_ec_review

"Checkout pane configuration
These settings are specific to this checkout pane.
Checkout panes to include on the Express Checkout review and confirm page"

Check this box! - Shipping service

Ralph Manis - Infinitee Web Design


submit custom form drupal 7 I've created one custom module to display product review form on custom created block but i'm not able to submit form and also I can't see form name while I checked with inspect element. give me solution please.
Here is my code for it.

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

  switch ($delta) {
    case 'my_module_config':
      $block['subject'] = '';
      $block['content'] = my_module_form();
      break;
  }
  return $block;
}

function my_module_form($form, &$form_state) {

  $form['rating'] = array(
    '#type' => 'label',
    '#title' => t('Rating'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );

  $options = array(1 => t('1'), 2 => t('2'), 3 => t('3'),);
   $form['rating']['options'] = array(
    '#type' => 'select',
    '#title' => t('Rating'),
    '#options' => $options,
    '#description' => t('Give your rating.'),
    //'#access' => $admin,
  );

  $form['comments'] = array(
    '#type' => 'label',
    '#title' => t('Comments'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
  );
  $form['comments']['prod_comments'] = array(
   '#type' => 'textarea',
   '#title' => t('Comments'),
   '#cols' => 60,
   '#rows' => 5,
  );

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit Review!'),
  );
  $form['#submit'][] = 'my_module_submit';
  return $form;
}
function my_module_submit($form, &$form_state) {
    drupal_set_message(t('The form has been submitted.'));
}

You wrote
$block['content'] = my_module_form();
which mean you called a function which return just an array.

You need to tell drupal that i am creating a form, for this use drupal_get_form

case 'my_module_config':
  $my_module_form = drupal_get_form('my_module_form');
  $my_module_form = drupal_render($my_module_form);
  $block['subject'] = '';
  $block['content'] = $my_module_form;
  break;


Why do only some of my hooks get called? I made a test module and only a few of my hooks seem to get called. I get the Javascript console messages for the block_view, form_alter and form_user_login_alter hook functions when I do the corresponding actions. However, when I login, logout, view a node, create a node or delete a node I get nothing in the console. Shouldn't these hooks get called when I do those things? I reset my cache, disabled and enabled my module multiple times.
Here is the code for test_module.module:

<?php

function console_log ($stringIn) {
    print "<script>console.log('" . $stringIn . "');</script>";
}
function test_module_help ($path, $arg) {
    switch($path) {
        case "admin/help#test_module":
            return '<p>' . t("This is just a test module right now.") . '</p>';
            break;
    }
}
function test_module_insert ($node) {
    console_log("node inserted");
}
function test_module_user_login_submit (&$form, &$form_state) {
    console_log("login submitted");
}
function test_module_block_view ($delta = '') {
    console_log("block viewed");
}
function test_module_user_login (&$edit, $account) {
    console_log("user logged in");
}
function test_module_user_logout ($account) {
    console_log("user logged out");
}
function test_module_view ($node, $view_mode) {
    console_log("node viewed");
}
function test_module_form_alter (&$form, $form_state, $form_id) {
    console_log("form altered");
}
function test_module_delete ($node) {
    console_log("node deleted");
}
function test_module_form_user_login_alter(&$form, &$form_state, $form_id) {
    console_log("user login form altered");
}

Here is the test_module.info file:

name = Test Module
description = just a test module
package = ZZ Test category
core = 7.x

Those two files are in sites/all/modules/test_module/

What am I doing wrong?

I'm surprised doing a 'print' works at all and does not produce a headers already sent error.
Your hooks may well be being called.
Instead of calling your own console.log function, install the devel module and call dpm('my message');
It will give you a much better idea of what hook is and is not being called.

eg. (your module with devel enabled).

function test_module_help ($path, $arg) {
    switch($path) {
        case "admin/help#test_module":
            return '<p>' . t("This is just a test module right now.") . '</p>';
            break;
    }
}
function test_module_insert ($node) {
    dpm("node inserted");
}
function test_module_user_login_submit (&$form, &$form_state) {
    dpm("login submitted");
}
function test_module_block_view ($delta = '') {
    dpm("block viewed");
}
function test_module_user_login (&$edit, $account) {
    dpm("user logged in");
}
function test_module_user_logout ($account) {
    dpm("user logged out");
}
function test_module_view ($node, $view_mode) {
    dpm("node viewed");
}
function test_module_form_alter (&$form, $form_state, $form_id) {
    dpm("form altered");
}
function test_module_delete ($node) {
    dpm("node deleted");
}
function test_module_form_user_login_alter(&$form, &$form_state, $form_id) {
    dpm("user login form altered");
}


How to disable the revision feature completely? I've followed discussions here and on d.o about removing unneeded revisions tables.

How would I completely prevent any data from being written to the node_revision and field_revision_* tables?

Field SQL norevisions actually solves exactly that problem by

  Field SQL norevisions provides a field storage backend using SQL that does not create a revision table for each field.

I haven't tried it, but anything written by Alex Pott can probably be expected to work properly.

I assume however that this also goes for all entites as it changes the storage backend.

Without a new storage engine, the below is the original, less useful, answer:

The revision tables must be available, and they must contain data.
Unfortunately, you just cannot get rid of them without completely breaking Field API, the reason being that the revision, contrary to their name, is the data storage.

Perhaps it's possible, with more database wizardry than I know, that you can set the regular field_data_* tables to be mirrors of each revision table. That might work.

Other than that, I can't think of any solution that would do this.

Edit: While I don't know if this will have, "interesting", side effects, I asked the wizards if this was at all doable. Can I have one table be an alias or symlink to another?.

Edit 2: Actually, it seems like much wizardry isn't needed at all. One could try replacing the field_data_* tables with a View that replicates the corresponding revision tables. Again, I haven't tried this, and my understanding of the interals of field api are a bit lacking, but it certainly could work.

Edit 3: (Yes, this is getting silly), someone pointed out that the above will cause the same data to be written twice, now to the same table. So it probably wont work anyway.


Create a pager between fields I have a content type that has no limit on how many body fields it can have.

You can say that each body field represents a page in a book. You are supposed to switch page to see the next body field.

The client I am developing this site for needs to support visitors that have javascript disabled.

Is there a solution that makes it possible to add a pager for these fields using PHP?

If you can use Views, it'll be simple.

Views can provide each field's value as a row. Set it up to display fields, add your multivalue body field, filter by node id, and you can set up views pager to show one row per page.

Then, use Pathauto to create nice addresses for nodes of that type, like /multibody/[nid]. In views, use the same address and voila - node pages got overriden with your view. Use Global Redirect to redirect from /node/[nid] to /multibody/[nid] to make sure users will not end up reading whole node at once.


Drush enable module | not working | Drupal 7 on WAMP with PostgreSQL Based on
Drush on windows - Command pm-enable needs a higher bootstrap level to run, i have the following question.

I have the same problem found here https://drupal.org/comment/8533097 except I am using Postgresql and this solution did not work for me.

My Drupal installation is at: C:\SiteData\WebDev\gitproject (aka DrupalRoot). I successfully ran drush status in "[DrupalRoot]\sites\site1.example.com, but when I try to enable a module using drush en ccl and I get the following.

  Command pm-enable needs a higher bootstrap level to run - you will
  need to invoke drush from a more functional Drupal environment to run
  this command. The drush command 'en ccl' could not be executed.
  Drush was not able to start (bootstrap) the Drupal database.

  Hint: This may occur when Drush is trying to:

  bootstrap a site that has not been installed or does not have a  configured database. In this case you can select another site with a
  working database setup by specifying the URI to use with the --uri
  parameter on the command line. See drush topic docs-aliases for
  details.
  connect the database through a socket. The socket file may be wrong or the php-cli  may have no access to it in a jailed shell. See
  http://drupal.org/node/1428638 for details

  Drush was attempting to connect to:

  Drupal version         :  7.26
  Site URI               :  http://site1.example.com
  Database driver        :  pgsql
  Database username      :  user
  Database name          : site1dev
  Default theme          :  garland
  Administration theme   :  garland
  PHP executable         :  php
  PHP configuration      : "C:\Program Files (x86)\Drush\Php\php.ini"
  PHP OS                 :  WINNT
  Drush version          :  6.0
  Drush configuration    :
  Drush alias files      :
  Drupal root            : c:/SiteData/WebDev/gitproject
  Site path              : sites/site1.example.com
  File directory path    : sites/site1.example.com/files

My settings.php file looks like this.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'site1dev',
      'username' => 'user',
      'password' => 'secretpw',
      'host' => '127.0.0.1',
      'port' => '',
      'driver' => 'pgsql',
      'prefix' => 'dev_',
    ),
  ),
);

if (php_sapi_name() == 'cli') {
  $db_url = 'pgsql://user:secretpw@127.0.0.1/site1dev';
 }
 else {
   $db_url = 'pgsql://user:secretpw@localhost/site1dev';
 }

I have used both the "Drush Command Prompt" and "MINGW32" git command line tool and both work for "drush status" or "drush dl " but not for "drush en "

One last comment.  looking at the settings.php file permissions in MINGW32 they show the unix permissions of -rw-r--r--.. Tried changing this in using chmod but doesn't work on a windows file (not even sure that makes a difference).

I'm not on Windows or using postgres today, but I can suggest how to debug:

What you've got right now is that your cli environment seems to be failing to connect to the database correctly.
Checking your database-level access from drush, using verbose (-v) debug (-d) feedback may provide clues.

For instance, given your current failure, I would run

  drush -v -d sql-cli

that will, among other things, show you the exact database connection command being attempted that is failing.

You can then copy that yourself, run it again,  and see what variations of that
   command will and will not work. One of the more common issues seems
   to already be covered (the difference between 'localhost' and
   '127.0.0.1' depending on installation and version issues. There may
   be other issues such as 'cannot locate postgres.exe in the current
   $PATH' or whatever.

This is not an answer to the question, but a suggestion on how to get clueful when a (any) drush command just doesn't work. You can also use the -vd flags on your 'en' command, though I don't know how conclusive the feedback you get there will be.


Hiding a field in a node conditionally I have a field that's a term reference field. If it has a value 'x' I want it to show on the node page. However if it has the value 'y' I don't want it to show. Is this possible?

The Field Formatter Conditions module should do the trick. It's currently in beta and doesn't work on excluding fields based on their own value.

However, if you change function ffc_get_condition_fields on line 145 in ffc_conditions_info.inc such that $exclude_current_field is FALSE.

function ffc_get_condition_fields($context, $exclude_current_field = FALSE) {
...
}

it will let you hide field display when it has a certain value.


Images uploaded with CKeditor disappear after cron run When i upload images with CKeditor in a directory inline-images - they disappear after each cron run. Why is that happened? I had a look at db table file_managed it's status set to 0.

What it might be?

Whatever text editor are you using either Basic HTML, Restricted HTML or Full HTML.

In setting if Limit allowed HTML tags and correct faulty HTML is enabled under the Enable filters setting. Check under the Filter setting in the list of Allowed html tags, <img> tag has been enabled or not? If not listed in that list, the image will be strip off from the content as for that case it is restricted html element.

Update-1


When I save a user account as an admin, I get logged in as that user I'm experiencing a strange issue that I'm having a really hard time debugging.

When I save a user account (of an authenticated user) as an admin, the account is saved, but when the page reloads I get an access denied and I am suddenly logged in as the user I saved, not the admin.  This happens whether I save the account in the UI (via the People page) or save the account using a rules action.

Recently, I added a custom function and modified a few of my rules, so these changes are likely to be the cause of the problem.  The site is version-controlled using git, so I can roll back to a working version, but I would like to attempt to determine what I did wrong.

I have Netbeans working with Xdebug.  I just don't know where to set breakpoints or how otherwise to start looking for the source of this problem.

Can you re-produce the problem from CLI?

Using drush scr, bootstrap, login as user 1, save a new user, check if your ID changed.

If you can do this from CLI, git bisect can be very helpful in finding the commit that caused it.


'serialized' field in schema still needs manual unserialization? I've modified my schema so that I can store an array of items in one field:

"required_product" => array(
  "type" => "text",
  "length" => 'medium',
  "not null" => TRUE,
  "default" => "",
  "serialize" => true,
),

This works great when using drupal_write_record, as the array data is correctly serialized before putting it into insert/update query and executing.

However, I still have to manually serialize when I extract the data - example:

$form_state["values"] = db_fetch_array(db_query("SELECT * FROM {amh_shop_discounts} WHERE discount_id=%d", $discount_id));
$form_state['values']['required_product'] = unserialize($form_state['values']['required_product']);

This is less useful - shouldn't it do both?

Currently running Drupal 6.22

This is just a guess, so correct me if I'm wrong...

I think that automatic unserialization is not possible because the schema is not loaded by db_query. While drupal_write_record() loads the schema definition before writing to the database, db_query simply executes the query string you put into it, without knowing which schema definition the query relates to.


How should I let some users to download from Private folder I stored the names of some users in one table and they should be able to download certain files from private folder(not other users). As i see i have to use hook_file_download

In the page of that hook it is said:

  If the user does not have permission to access the file, return -1. If
  the user has permission, return an array with the appropriate headers.

I don't understand which array should be returned exactly! my file in private folder is mp4 file and user has to see save page.
some users  file_create_url() but i don't know how to use it inside hook_file_download. can u give me one example code?

thanks in advanced for your help

edit: I found this code here:

  if ($can_access_file) {
    $headers = file_get_content_headers($file);
    return $headers;
  }

I don't know exactly how to provide with $file!
here is file_get_content_headers help

What field type serve the link for the download ? Maybe the module behind this type already implement this hook ?
For example, File module or Image module already implement this hook_file_download.

In case of File module, it allow you to alter the permission to access to the file.

// Allow other modules to alter the returned grants/denies.
    drupal_alter('file_download_access', $grants, $field_item, $entity_type, $entity);

You just have to implement the hook_file_download_access_alter. By the way, there is this other hook (hook_file_download_acces) you can may be try to hook.

Finally, if no one of this hooks can help you, so may be you have to use this hook_file_download. But I don't really know what is expecting as headers, but you can look at the hook in the Image module.

There, it get headers from others modules (may be you can just use this trick) :

// Check the permissions of the original to grant access to this image.
  $headers = module_invoke_all('file_download', $original_uri);

And just after that, it make its own headers :

return array(

      // Send headers describing the image's size, and MIME-type...
      'Content-Type' => $info['mime_type'],
      'Content-Length' => $info['file_size'],
      // By not explicitly setting them here, this uses normal Drupal // Expires, Cache-Control and ETag headers to prevent proxy or // browser caching of private images.
    );

Hoping that help :)


How to remember exposed filter choices? We're hoping there's already a module that will do this...

We are creating a page that will contain three view blocks. Each view will have a different exposed filter (all based on taxonomies.) The views are completely independent of one another; they're just going to display on the same page.

What we're looking to do is allow a user to set the filters on each view, and then have Drupal remember those filters. This will be available to authenticated users only, and we're hoping that the filter values can be remembered from session to session.

Example: View 1 will have a Retailer filter, so the user can choose to view all content about Target. View 2 will have a Manufacturer filter, so the user can choose content about General Mills. And so on for as many views as we choose to display on the page.

I know we could do this to a certain extent with javascript and cookies, but as I said, we're hoping it's already been done, as we're under a deadline. Does anyone know of a module that does this? I've tried searching drupal.org for user customization and exposed filters, but the results are overwhelming, and not entirely relevant.

There is an option in views for this. Go and edit the exposed filter, In the edit form there will be option called

Remember
Remember the last setting the user gave this filter.

However I dunno, how to restrict this functionality only to authenticated user.


How to get the list of values and keys for a given list field I want to programmatically get the list of possible key values for a field, along with their labels. For example:

1 => red
2 => blue
3 => Yellow
...

and so on. How do I do that?

It's just a matter of getting the field basic data, then get a list of possible values using Field API function that is part of List module.

$field = field_info_field([FIELD_MACHINE_NAME]); // This one gets the field data
$field_values = list_allowed_values($field); // This one gets an array of values => labels
$field_key = array_search('red', $show_field_values); // This one gets the key for the value labelled "red", that is: 1


Export Apache Solr enabled facet settings On the Apache Solr settings page admin/config/search/apachesolr/enabled-filters you can control which filters are enabled on your site's search interface.

These settings are not stored in regular Drupal variables, hence, you cannot export these settings in a Feature like you would do with another variables. I am interested in making these settings persistent by storing them in Features.

This would allow to effortlessly switch from a produduction Solr instance to a local instance without having to manually re-apply all these settings by reverting the relevant Feature.

What would be best way to store these settings in Features?

This code resolved my need to backport production enabled-facet settings into localhost. Features are not used. tfk_search is the name of my module, substitute this for your own.

/**
 * Implement hook_form_FORM_ID_alter().
 *
 * Alter apachesolr_enabled_facets_form(), add an additional submit handler
 * that helps us export enabled facet settings via Features.
 */
function tfk_search_form_apachesolr_enabled_facets_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'tfk_search_enabled_facets_form_submit';
}

/**
 * An additional submit handler for the active facets form.
 *
 * Save current settings into default server. Allows backporting
 * production settings into localhost. No Feature revert needed.
 *
 * @see apachesolr_enabled_facets_form
 */
function tfk_search_enabled_facets_form_submit($form, &$form_state) {
  $enabled = array();
  foreach ($form_state['values']['apachesolr_enabled_facets'] as $module => $facets) {
    $enabled[$module] = array_filter($facets);
  }

  // We hardcode 'solr' here because apachesolr_default_server() resolves to something
  // else in production.
  apachesolr_save_enabled_facets('solr', $enabled);
}

After importing the database from production into local, while your default Solr instance is still the same as the one in production, go the enabled-facet settings page, and save it (even if you make no changes on it). Then switch the default Solr instance to the local one (solr). It should automatically pick up the facet settings for production.

Note that this solution is good for backporting settings, but not for exporting them á la Features. It would not work if you wanted to automatically push these settings into various sites.


How to prevent Drupal from scrolling to the bottom of ajax-appended content in a form I have a custom form in Drupal.

When a user first sees this form, the only thing on the page is a select box, along with a few other elements they have to fill out.

When they make a selection from the select box, the #ajax callback regenerates the form, and adds about 50 results to the page.

By default, Drupal is scrolling down to the last result.  This is a problem, because the users have to scroll back up to the elements near the top of the page to finish their work.

Is there a way to prevent Drupal from scrolling to the bottom of the newly-added form content?

Here is a snippet that shows how I'm setting up the form:

$form = array(
'#tree' => TRUE,
'#prefix' => '
',
'#suffix' => '
',
);

Here is a snippet from the select box that triggers returning the results.

$form['selectbox'] = array(
  '#type' => 'select',
  '#title' => t('Select box'),
  '#options' => $predefined_select_options,
  '#empty_option' => t('Select something!'),
  '#ajax' => array(
    'callback' => 'mymodule_form_ajax',
    'wrapper' => 'myform',
    'effect' => 'fade',
  ),
);

$form['other_stuff'] = array(
  '#type' => 'textfield',
  '#title' => t('Other stuff they need to fill out here'),
);

if (isset($form_state['values']['select box'])) {
  foreach ($lots_of_results as $result) {
    $form[$result] = array(
      '#type' = 'fieldset',
      '#title' = 'Lots of results in their own field sets',
    );
  }
  // It scrolls to the bottom of this huge list after it's rendered.
}

Here is the ajax handler for the select box.

function mymodule_form_ajax($form, $form_state) {
  return $form;
}

You could override the Drupal.ajax.prototype.success handler (/misc/ajax.js) in your theme  to control behavior, maybe commenting out Drupal.unfreezeHeight(); and Drupal.freezeHeight(); could do the job?
Just copy the whole function and manipulate it your own way.

/**
 * Handler for the form redirection completion.
 */
Drupal.ajax.prototype.success = function (response, status) {
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  $(this.element).removeClass('progress-disabled').removeAttr('disabled');

  Drupal.freezeHeight();

  for (var i in response) {
    if (response.hasOwnProperty(i) && response[i]['command'] && this.commands[response[i]['command']]) {
      this.commands[response[i]['command']](this, response[i], status);
    }
  }

  // Reattach behaviors, if they were detached in beforeSerialize(). The
  // attachBehaviors() called on the new content from processing the response
  // commands is not sufficient, because behaviors from the entire form need
  // to be reattached.
  if (this.form) {
    var settings = this.settings || Drupal.settings;
    Drupal.attachBehaviors(this.form, settings);
  }

  Drupal.unfreezeHeight();

  // Remove any response-specific settings so they don't get used on the next
  // call by mistake.
  this.settings = null;
};

Another option would be to render the ajax form with ajax_commands where you could add custom js handlers to your callback.


main menu disappears only on home page I have a site online engcorrect.net and for some reason my menu on my homepage disappears. On all other pages, it shows. The weird thing is that on my localhost (local machine) it shows correctly but not on the production site and it also shows if I use private browsing. What am I missing here? I am using Drupal 7 and bootstrap 3 theme with a subtheme called paper.

There is a css line that I cannot allocate:

body.front ul.menu { display:none;}

The inspector shows that it originates from engcorrect.net:1 where is that and who set it?

resizing doesn't fix the issue either.
Who can help me with this?

Ok. It's resolved. I cleared the browsers cache in Safari under: Preferences/Privacy/Manage Website Data and there I searched for my site name, selected it and hit "remove all". Therefore I presume it was my Safari browser's cache.


How to debug weird and random behavior I'm trying to figure out how to debug the following behavior and would appreciate some ideas on how to track down the source of the problem.

I run a website were some users have privileges to create and edit nodes and taxonomy terms.

Upon creating content or taxonomy terms, users report that, on occasion, content is created 3 times, for both entity types.

What steps can I take to find the culprit for this behavior knowing that...?

I have made sure users only click the submit button once, but that hasn't made any difference.
Both Drupal and PHP error logs are clean.  I can see 3 logged messages confirming content has been triplicated but nothing else.
It only happens in live environment.  I haven't been able to reproduce it in development environment
It happens randomly.  Users have reported this only happens ocasionally.
When this happens, any rules that react to the condition 'After saving node ...' or 'After updating node...' are also fired 3 times

Treat it like any bug:

Find a way to reliably reproduce the problem (this is essential to debugging any code issue for obvious reasons; the question "how do I debug this problem I can't reproduce?" doesn't have an answer, let alone a Drupal-specific one). You may need to set up a clone of your production environment as the issue might not be related to Drupal (e.g. you could have a rogue process duplicating MySQL records that Drupal doesn't get involved with)
Fire up XDebug or your debugger of choice.
Step through every single line of the code that gets involved in the problem you're seeing, keeping an eye on what parameters are being passed to methods, and if they contain the expected data. Basically run through an entire bootstrap for the page(s) you're having problems with, starting at index.php, narrowing down your target search area as you go.
Fix when you've identified the problem (you're not done yet though...)
To help for next time, write a test that fails before you implement your fix, and passes afterwards. Make it part of your deployment workflow to run this test after every change you make. Consider adding tests for other major pieces of functionality as you decide which are the most important, to help avoid this sort of situation in future.


Anonymous Users to view PRODUCTS I have enabled "View all products product" -- I have disabled sql rewriting.

Although I still cannot get anonymous users to VIEW ANYTHING in the store. Because of the ADMIN overlay?

It sounds like you aren't very clear on what that permission does vs. how products are displayed. I'm guessing here that you're using Drupal 7. If so, it seems your problem is you're trying to expose the admin paths to products to customers, but those paths aren't intended to be viewed by them. Instead, you're supposed to create either a View that renders product entities directly or a node type with a product reference field on it that functions as what we called a product display. When you attach a product reference field to a node type, it supports embedding product fields into that node while rendering the field itself as an Add to Cart form.

There are a variety of tutorials / guides to understanding and implementing this on the project website: https://drupalcommerce.org

When you need to grant that permission and / or disable SQL rewriting is when you have a View that creates a relationship between your node type (or order line items) to product entities. In that case, though, the View should have additional filters on it to apply appropriate access control so customers only have access to view in that context the products or line items they should.


Newly (created by Drupal) dir not writable after first upload? I'm working on Mac (Mojave) and using Vagrant for local dev. server. "nfs" is set to true if that maters. On Vagrant box I run Ubuntu 18.04. Drupal version is 8.7.2.

I add some new image field to some existing content type. For that field I set directory name, where files should be stored, i.e. "people" so dir is created in sites/default/file.

Then when I edit some node in that type and upload image for the first time it works fine.
But when I edit another one I can not upload image - this directory becomes write protected?! And then when I manually allow writing (change dir permissions) I can upload image again and it works well after that for all other nodes.

So it's like after first upload Drupal makes directory write protected for some reason?! Or is that done by virtual box?

Any idea why is that happening?

It's the server software that controls the file permissions, you need to have that set up correctly first. Drupal is then granted access to the dedicated folder for site uploads and other generated files necessary for the site activity.

It's very important for your site security to have the files' and folders' owners, groups, and permissions correctly set up, and this is a part of any Drupal installation.

This is a long but detailed resource on this: Securing file permissions and ownership

Usually you need to make the www-data user the owner of the files/ folder, this is the Apache server user on a lot of installations but YMMW, it can be called something different. And it's important to give all the necessary permissions for that user and the group too, but not more than necessary to keep it perfectly secure.

Doing this step during Drupal installation usually ensures you don't stumble upon file-upload-permission related issues.

Also check your Status Report for any messages related to file uploads. You will also have entries in the Latest log entries if the system encounters something worth throwing an error for. And check the File system related admin pages (under Configuration), try saving the form there and see if you get any errors and get more info about your case.

Did you use some special Drupal Vagrant setup?