Uninstalling an entity "BaseFieldDefinition" on module uninstall

Okay,

After a few more hours of head scratching and hair pulling, I think I've found (or so it would seem) the answer... I'm writing this for myself, as well as anyone else who might stumble across it by route of the all-mighty Google.

From what I can gather, the EntityManager Service has been split up in to several parts. As a result, the bit we're interested in lies within the Entity Field Manager service / class.

We can use this to grab the definition (which I believe is Drupal for - the set of instructions that provide relevant information about an entity [or part thereof]) of our custom entity field.

Now that we have a Drupal readable way of referencing the entity field we're interested in manipulating, we need to actually manipulate it.

Soo... There are a few ways to do this, but I believe the best way is to make use of Drupal's Field Definition Listener service, that seems to do the job we're after. What this listener will do is handle getting rid of all the places that the entity field has been buried away within Drupal itself. From the sounds of the service name it should be using the event dispatcher system somewhere, somehow; although, looking at the source I can't find anywhere that actually does this? (this is in contrast to field_storage_definition.listener, which does dispatch an event, but didn't seem to work, and would white screen with an SQL error, complaining that it can't find the given field when used...)

With these two pieces of the puzzle, it's just a case of putting them together to get the functionality working correctly.

I ended up with:

function detailed_menu_uninstall() {

  // Grabs the entity Field Manager service.
  $entityFieldManager = Drupal::service('entity_field.manager');

  // Grabs the Field Definition listener.
  $fieldDefinitionListener = \Drupal::service('field_definition.listener');

  // Ensures(?) that the field storage for the 'detailed_menu_heading' base field is deleted
  // properly when the module is uninstalled.
  $definition = $entityFieldManager->getFieldStorageDefinitions('menu_link_content')['detailed_menu_heading'];
  $fieldDefinitionListener->onFieldDefinitionDelete($definition);
}

One thing to note is that if I add more definitions to be installed, and consequently uninstalled in this hook, they don't actually need to be put in the uninstall hook, and I'm not sure why... It's as if Drupal just needs a nudge to be told that some things need to be removed from the entity properly, and Drupal does the rest to check what that is? I'm really not sure.


file_entity update means views now checks for public: in their uri?

File entity adds a tag to Views' queries called query_file_access.

This checks to see if a user has view private files privilege, and if not it denies access to any private files.

So you can get this view working again by granting this privilege to that user.

I find the privilege confusing because I do not want grant access to all files to this user, and the privilege screen warns that this has security implications.

I believe it's ok as long as the node access checks are done.


How to display menu bar over slideshow block?

You can increase the z-index property of your menu bar.

If this does not help, add the position:absolute property in CSS class; and also add the position:relative property to the container of the menu bar class.


Problem in drush configuration with wamp server 64 bit

PHP for Apache and CLI have different configuration files, so check if you're using the right one.

To identify which php.ini is used by drush, run drush status:

$ drush status
PHP executable         :  /path/to/bin/php
PHP configuration      :  /path/to/php.ini

then edit that file and check if you've the right extensions specified.

Alternatively check using php command, for example:

$ php -i | grep php.ini

Note: In case grep command is not found, replace with the with find.

If you still have a problem, possibly that your DLL library was compiled for the wrong version of PHP. So either use the one included with WAMP, or download the right one specifically for that version of PHP.

Also double check that your command-line php points to the right place (WAMP folder):

$ where php
$ which php

which should give you C:\WAMP\PHP\bin-like path, if it's not, update your system PATH variable in advaned system settings.

Finally to check if your GD2 library is loaded, check by:

php -r "phpinfo();" | grep gd2

Note: The grep can be replaced with find on Windows if you don't have Linux command utilities installed.


Creating custom field with Display Suite and Profile 2

Enough trial and error and I finally figured it out. I ended up using Display Suite Code as the text format, but writing php code in the field code box.

And to grab the first name the code was: $entity->field_first_name['und'][0]['safe_value'].


How to load multiple values from a field with views_php module?

As Syd said, it seems like you need a foreach loop. It's not readily apparent what you're wanting to do with the $source variable, but I'm guessing it's something like the following:

foreach ($data->_field_data['nid']['entity']->my_field['und'] as $a_file) {
    echo '<img src="' . $a_file['filename'] . '">';
}


If an image is inserted into a textarea like your wysiwyg editor, the node does not retain an entity relationship with that image, you would need to parse the full content of that field for images, figure out if they are internal, get their ID...

Your node should ideally have a field of type image, that way your saved node has an association with one or more images you have uploaded. You can then insert the images inline wherever you wish.


How to add a "?destination=URL" to the node links

You are doing it correctly but the theme_links() function is called after you create the link. That function calls the l() function, which in turn calls the url() function, which in turn calls drupal_encode_path(), and it's here your Url is getting encoded.

If you override the theme_links() function, you can undo the encoding. Copy the theme_links() function from theme.inc into the template.php of your theme. The function should be named mytheme_links() or, if you want it to apply only to nodes, you can name it mytheme_links__node(). The original theme_links() function has this:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $output .= l($link['title'], $link['href'], $link);
}

You can replace it with this to undo the encoding:

if (isset($link['href'])) {
  // Pass in $link as $options, they share the same keys.
  $link_html = l($link['title'], $link['href'], $link);
  // Decode the link HTML before adding it to the output
  $link_html = rawurldecode($link_html);
  $output .= $link_html;
}

This is just a basic explanation. There are good reasons for encoding links, so you might want to restrict the links you decode.


Figured it out. It was a problem with the reverse-proxy we're using. I installed a different version of drush in cygwin and tried to run it. Here it paused like I described above, but after a minute showed me this error:

  Drush needs a copy of the PEAR Console_Table library in order to function, and the attempt to download this file automatically failed.
  To continue you will need to download the 1.1.3 package from http://pear.php.net/package/Console_Table, extract it into C:\cygwin64\usr\local\src\drush/lib directory, such that Table.php exists at C:\cygwin64\usr\local\src\drush/lib/Console_Table-1.1.3/Table.php.

I installed this package manually and now things are working. I just didn't realize Drush was trying to download extra content.


Exposed Form: Send only selected filters

I can confirm that on page load the option jQuery UI slider of the Better Exposed Filters module does apply the minimum value set in options.

The minimum value is displayed in the slider, so it's a visible cue that it will be displayed.

If you delete the number in the slider and then apply other filters, the slider filter will not be applied!

But the minimum value will still be visible in the slider on page reload (if you're not using Ajax in Views).

I couldn't find any similar issues so I created a new one: jQuery UI slider Exposed filter always applied

Add your test results/observations there.


No, there is no views integration for config entities (that's the term you mean, not entity configuration).

The easiest way to achieve what you want is to write custom custom views field plugins and define it in a EntityViewsData class for your entity and then just access the config entity and render what you want.


error SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

sadly there is no "vanilla" way in migrate / migrate_tools / migrate_plus, to achieve this, at least that i know of.
I think the best solution is to create a custom plugin and append it to your yml file at the uuid field.
I should probably look something like this.
Disclaimer: The following snippet is derived from https://www.drupal.org/project/migrate_plus/issues/3060320 and modified to suit your case specifically. It is not tested though.
<?php

namespace Drupal\your_module\Plugin\migrate\process;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateSkipRowException;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Skips processing the current row when a same entity already exists.
 *
 * Examples:
 *
 * @code
 * process:
 *   name:
 *     plugin: skip_on_duplicate_entity_exists
 * @endcode
 *
 * @MigrateProcessPlugin(
 *   id = "skip_on_duplicate_entity_exists"
 * )
 */
class SkipOnDuplicateEntityExists extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $storage;

  /**
   * EntityExists constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityStorageInterface $storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->storage = $storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      // Use configuration instead of "node" for a mode generic solution
      $container->get('entity_type.manager')->getStorage('node')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $entityQuery = $this->storage->getQuery();

    $existingEntities = $entityQuery
      ->condition('uuid', $value)
      ->execute();

    /* The result is either an entity id string,
    or an array of entity id strings.
    If either one is not empty, there's a duplicate. */
    if (!empty($existingEntities)) {
      throw new MigrateSkipRowException();
    }

    return $value;
  }

}

You can find more on custom migrate plugins here https://www.drupal.org/docs/8/api/migrate-api/migrate-process/writing-a-process-plugin.
Let me know it it helped, or if you need any further assistance / clarification.


How could I automatically delete accounts with a given criteria?

You may not be able to stop the email being sent. But you can set up a rule to block the user to trigger on the event 'Before saving user account'.

You will require two conditions. First use the condiiton 'Entity has field' and check for the 'Reasons to join' field. This will make the field visible to subsequent conditions. The do a 'Data comparison' on account-unchanged:profile-main:user:field-reasons-to-join and check for your two charcter text. If the conditions are met use an action to 'Block a user' using account-unchanged:profile-main:user.

EDIT: Since your users are blocked pending admin approval, perhaps you should be looking at the Field validation module. With it you can specify a minimum length for the field (making sure you let your users know in the guidelines that the minimum length is required). You could also set up a field hidden with your css which you would require to be empty. Bots would likely fill it in with something.

You should also have a look at the Spambot module which uses the api at stopforumspam.com to catch known spammers. While it is not perfect (nothing is) it will certainly cut down on the number of bots that get through.


How do I programmatically assign the access to a block?

Setting the "roles" array in the array returned from hook_block_info() doesn't work because:

The roles that are allowed to see a block, and which are set in the user interface, are saved from block_admin_configure_submit() in the "block_role" table

$query = db_insert('block_role')->fields(array('rid', 'module', 'delta'));
foreach (array_filter($form_state['values']['roles']) as $rid) {
  $query->values(array(
    'rid' => $rid,
    'module' => $form_state['values']['module'],
    'delta' => $form_state['values']['delta'],
  ));
}
$query->execute();

The code that decides which blocks should be shown to the currently logged-in user is contained in block_block_list_alter(), which is an implementation of hook_block_list_alter(), and uses only the content of that table

$result = db_query('SELECT module, delta, rid FROM {block_role}');
foreach ($result as $record) {
  $block_roles[$record->module][$record->delta][] = $record->rid;
}

foreach ($blocks as $key => $block) {
  if (!isset($block->theme) || !isset($block->status) || $block->theme != $theme_key || $block->status != 1) {
    // This block was added by a contrib module, leave it in the list.
    continue;
  }

  // If a block has no roles associated, it is displayed for every role.
  // For blocks with roles associated, if none of the user's roles matches
  // the settings from this block, remove it from the block list.
  if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
    // No match.
    unset($blocks[$key]);
    continue;
  }

  // …

}

There isn't another Drupal function that checks the roles property in the data returned from hook_block_info(), nor is the content of the "block_role" table merged with what returned from the hook_block_info() implementations.

You could verify the user has the required role to see the block in hook_block_view(), but at that point Drupal is already rendering the block; that means the user would still see the block title, if one has been already set.

What you can do is implementing hook_block_list_alter() to remove the information about that block when the user doesn't have the required role.
To avoid confusion to the users who administer the blocks, I would also alter the form used to edit a block, and disable the form field used to set which roles can see that block, since the module implementing it is going to use its own list of roles; the minimal code should at least show a message about the role settings not having any effect, but I would also disable the form elements for the role settings.

Since the Block module already shows form fields to select which roles see a block, you could also simply set a default for your block, and let the administrator users change it if necessary.

As per checking the roles a user has versus checking the permissions a user has, the last is preferred, especially when the alternative would be hard-coding a list of roles in a module.
As shown from the Block module, using permission is not the only alternative: A module could have setting for deciding which roles are allowed to see something.
Clearly, it is not always worth having a setting for which roles are allowed to do something. I imagine also what for the administrator users would mean if 10 modules would have their own settings for which roles are allowed to do something, instead of using permissions, and allowing the administrator users to use a single page to set them.


If you just started a new site / doesn't contain any data yet as you seem to indicate in your question, it may be faster to reinstall Drupal than search for the source of the WSOD.

Otherwise, you could have a look in the database directly:

first, check the watchdog table: it may have error messages that don't show up in Apache and PHP logs
then, empty the caches by truncating every table named cache_something
then if you're sure this module is the one that caused the problem, you can edit the list of enabled modules in table system: find the module in the list and change its status to "0"

But if you make any modification directly in the database, make sure to save a backup first, just in case ;-)


How do I dynamically change cookie_lifetime?

You can override SessionConfiguration::getOptions to set the cookie lifetime dynamically:

/mymodule/src/MySessionConfiguration.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\Session\SessionConfiguration;
use Symfony\Component\HttpFoundation\Request;

/**
 * Sets session cookie lifetime dynamically.
 */
class MySessionConfiguration extends SessionConfiguration {

  /**
   * {@inheritdoc}
   */
  public function getOptions(Request $request) {
    $options = parent::getOptions($request);

    // Set the cookie lifetime dynamically depending on the request.
    $options['cookie_lifetime'] = 30;

    return $options;
  }

}

Swap the service class in the container:

/mymodule/src/MymoduleServiceProvider.php:

<?php

namespace Drupal\mymodule;

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

/**
 * Modifies the service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

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

}

See Altering existing services, providing dynamic services.


Get all related sister (same content type) nodes through a view in Drupal 7

To filter nodes with the same taxonomy term, when a node is displayed as main content (/node/???)

View , Display as block

2 contextual filters:

Content: nid -> provide default value: content id from url - more: exclude
Content: Has taxonomy term ID -> provide default value: taxonomy term id from url

It is important to put the contextual filters in this order, the first filter excludes the actual node from display, the exclude-checkbox is at the end under "More"

add additional filters, for example:

Content: your content-type
Content: Published (Yes)

Put the view block right below your Main page content in the Content-Region


Splitting exposed form filters amongst several blocks

In Drupal 8, Views pages allow you to render your exposed filters as a separate block. In your view, select your Page display, then, under Advanced, toggle on the option Exposed form in block.

You can now separately place the exposed filter like any other block. It doesn't even need to be on the same page as the view results.


It looks like you are using commerce shipping 2.x which differs a lot from 1.x in terms of integration.

What you need to do is:

Define a shipping method, use hook_commerce_shipping_method_info.
Define one or more shipping services use hook_commerce_shipping_service_info
When you define the shipping services, you can select a rate callback, if none is selected, commerce shipping will by default try to use SERVICE_NAME_rate, where SERVICE_NAME is the keyed name used in the hook_commerce_shipping_service_info hook. The rate callback have this signature:

function service_name_rate($shipping_service, $order) {
  // Logic here.
  return array(
    'amount' => $amount,
    'currency_code' => $currency_code,
    'data' => array(),
  );
}

You can look at the example module within the commerce shipping module which serves as documentation, or you can look at some of the other shipping methods, like UPS.


The data structure you want does not fit with what Views is supposed to provide. Views is intended only for generating lists. 'title' and 'body' are assumed to not be part of a list, so views has no configuration for defining single hardcoded values, and goes against how views works.

Your other option is to create a custom route with a node parameter (example) that returns a JsonResponse object with populated blocks property. So your code may look something like this (based on route parameter example above):

use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class ExampleController {
  function foo(NodeInterface $node) {
    $response = [
      'title' => $node->label(),
      'body' => $node->get('body')->first()->getValue(),
    ];

    $blocks = [];
    $block1 = $node->get('block')->get(0)->get('entity');

    $blocks[] = [
      'block_title' => $block1->label(),
      'block_url' => $block1->toUrl()->toString(),
    ];

    /* ... add the rest of the blocks ... */

    $response['blocks'] = $blocks;

    return new JsonResponse($response);
  }
}

The code will need to be adjusted according to your entity field setup.


How can I make entityQuery('commerce_order') return completed orders?

The solution is apparently to add $query->accessCheck(FALSE);.


Add #ajax event to a custom composite element

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.


Reading a file uploade in my module without saving it

Ok I figured it out myself!

function my_module_upload_form_submit($form, &$form_state) {
    //saved the file into a tmp folder (location to save not set)
    //this will also add a pointer in the database
    $file = file_save_upload('upload', array(
        'file_validate_extensions' => array('txt'),
    ));

    //get the content in the file
    $content = file_get_contents($file->uri);

    //remove the file in temp and the pointer in the database
    file_delete($file);
}


Why are my users are being forced to reset passwords on almost every login?

Out of the box, Drupal does not have a way to force reset password automatically for users, I am guessing there must of use of any contributed module or there might be custom module written.

One of the contributed module which could do this is Force Password Change, can yu check if you have this module enabled? If so disabling the module or changing the configuration could help, also can you list down all the enabled non-core modules you have, you can get the list by running the following drush command, that will help in identifying if there is any such module used.

drush pm-list --type=Module --no-core   --status=enabled


You need to set up cron tab on your server may be once a day
  use hook_cron() to add your custom code write query to grab nids for which field values needs to be updated.
  use node_load_multiple() to load all nodes with the query returned nids
  update the field values and save the node again in a loop.
  set the crontab to run at the time when your site receives least traffic, this way it will not be performance issue as well.


Is possible to have mutiple email for a user?

In the Users table, 'mail' - the field for email addresses, is unique, as it's tied to other criteria to control account management, login, logout, etc.

So depending on what you are trying to accomplish, I dont think you could have more than one email control one account without some custom database changes.

However if you simply want to link an account to multiple email addresses, perhaps this is as simple as an 'email address' field for the profile. Adding unlimited to that field for the form would invoke the 'add another' and the user could simply have as many as they needed.

If you wanted that person to be able to login with any of those email addresses, then a quick module could link the fields together so that the email addressed used had a primary account referenced by it, and, then would proceed with login.

Or, I could be way off - what are you ultimately trying to accomplish?


How will I access inner fields values in twig template

Similar question for the node id from today Reason for adding .value to access node id?

Either add .value to the field name

{{ author_picture['#user'].name.value }}

or use a specific method if the entity provides one:

{{ author_picture['#user'].getdisplayname }}

It is preferable to use  User:getDisplayName because it does extra processing:

  By default, the passed-in object's 'name' property is used if it
  exists, or else, the site-defined value for the 'anonymous' variable.
  However, a module may override this by implementing
  hook_user_format_name_alter(&$name, $account).

  Return value

  string|\Drupal\Component\Render\MarkupInterface Either a string that
  will be auto-escaped on output or a MarkupInterface object that is
  already HTML escaped. Either is safe to be printed within HTML
  fragments.


The issue is a known one, and a patch fixed the issue - http://drupal.org/files/drupal.simpletest-curl-cookiejar.33.patch


How to hide /node/ , /taxonomy/, /mymodule/, etc., from the URL path

If you set the patterns for a content type on URL aliases. You get the "Generate automatic URL alias" So you never get the node/* urls on that content type.

You find the URL aliases section on your configuration page.
Patterns is a tab there.


Hook_preprocess - disable CSS caching with drupal_add_css

You can try using AdvAgg. Not sure it'll fix your issue because the source of the problem hasn't been identified. https://www.drupal.org/project/advagg


How to programatically get the machine name of a node?

Individual nodes don't have machine names in Drupal 6 or 7, so you can't.

If you want a unique ID for each node, and Node ID won't do (for staging or migration for example), then try taking a look at the UUID module.

  This module provides an API for adding universally unique identifiers
  (UUID) to Drupal objects, most notably entities.

Also of note...

  Features in Drupal 6 version

  Automatic UUID generation for nodes, node revisions, users and taxonomy.
  Allow choosing which content types and vocabularies to create UUIDs for.
  Option to batch create UUIDs for objects which don't have it already.

If, however, you want the node TYPE to be available to your template, and you have the node object, it should be under $node->type, or possibly $vars['type'].


You might want to look at the Views Data Export contrib module:
https://www.drupal.org/project/views_data_export

This module exposes a drush command that can execute the view and save its results to a file.

drush views-data-export [view-name] [display-id] [output-file]

Since you can call this command via drush from the shell, you should also be able to add the drush command to the operating system crontab (not Drupal cron) so that it executes on a schedule:

https://www.ostechnix.com/a-beginners-guide-to-cron-jobs/


drupal 7, db_select(), strange behavior : malformed query

If the array is empty, you'll get WHERE foo IN (). That's invalid SQL syntax.

To prevent, use a conditional:

if (!empty($values)) {
  // Run the query.
}


Yes. One way could be:

You export your configuration. (drush cex -y, or on the interface configuration management)
You filter the configuration you need.
You import those configuration files into the other site (drush cim, or manually).


The last version of Drush on drupal.org has a GPL v2 license in it.  The license itself is not in the repository.  Modules and themes on drupal.org automagically get LICENSE.txt added by the packaging script (the automated process that creates the tarballs and zips from central git repo).

This means that drush is technically still GPL v2, even though it doesn't have an explicit license in it.  There is talk about relicensing drush, though.


How can I make Rules react to `User has logged in` when user logs in through CAS?

I ended up using hook_user_login, which detects all logins without problem:

myModuleName.module

function myModuleName_user_login (&$edit, $account) {
    my_user_login_function($account);
}


Missing icons with CKEditor for Drupal 7

Try re-upping the CKeditor library (not the module) and double-check that the owner/file permissions are set correctly on the server.

I believe TinyMCE also works with CKeditor. If you only need to attach images to content and don't need a WYSIWIG editor for your input area, you can add an Image or File field to the content type. If you're using a File field, you might also want to look up the File Entity and Media modules.


I solved that problem using Features for Drupal 8 as suggested by @leymannx.

I have exported media, taxonomy and the article content type to one feature that I can now use across multiple sites.

The cool thing is that configuration still lives in the config_sync directory, so other content types that depend on media and taxonomy don't need to be exported to features as well.


How can an existing user login to check on previous orders?

The Drupal site login and Commerce login are definitely the same; check the login details again.

Commerce 2 supports checking the details of orders out of the box.

It adds an "Orders" tab to the user profile (/user/UID/orders), and a view (that you can customize if you like) is provided to display the order history (/admin/structure/views/view/commerce_user_orders/edit/order_page).


If the module uc_restrict_qty not working file your issue there. Alternatively You can achieve this with help of hook hook_uc_add_to_cart

hook_uc_add_to_cart($nid, $qty, $data)

  Performs extra processing when an item is added to the shopping cart.

Inside hook you can check your conditions, and prevent your new item to add.

uc_cart_get_contents() can used to get existing contents of cart. If it is greater than 1 you can do your logic here, either remove previous one and add the current one or remove the new item


How to create a responsive views block in bootstrap?

The grid default format is not responsive, you can trie Semantic Views


Crumbs is not showing parent of taxonomy term

After spending more time than I wanted to to dealing with this—exploring solutions and Googling seemingly forever—I came across this post on the official Drupal site titled “Crumbs not working” and specifically this answer from ‘donquixote’ which states:

  are these system paths or node aliases? If they are node aliases, do you have the "path" plugin enabled? (*)

Okay, so that seems like an idea. So I went into the Crumbs settings area under “Structure > Crumbs” and dragged the path setting—which describes itself as “Chop off the last fragment of the path alias, consider the result as the parent path.”—from “Disabled by default” to the second position of “Enabled” (see attached screenshot), hit “Save configuration” and… et voilà… It works! Parent and child taxonomy terms are being rendered in the breadcrumb path as expected.


How do I load the current items in cart of the anonymous user?

Get the current anonymous user's cart

  $cart_provider = \Drupal::service('commerce_cart.cart_provider');
  $cart = $cart_provider->getCart('default');

Get a list of items still in that user's cart

$order_items = $cart->order_items->referencedEntities();

Bonus
$cart_manager = \Drupal::service('commerce_cart.cart_manager');

Update order item
$cart_manager->updateOrderItem($cart, $order_item);

Remove order item
$cart_manager->removeOrderItem($cart, $order_item);

Empty cart
$cart_manager->emptyCart($cart);

Create order item
$order_item = $cart_manager->createOrderItem($entity, $quantity);

Add order item
$cart_manager->addOrderItem($order_item);


Apparently with Vue Resource, I need to add emulateJSON:

  emulateJSON boolean Send request body as application/x-www-form-urlencoded content type.

this.$http.post('http://mydrupal8.url/simple_path', {
  params: {
    'message': 'hello world'
  },
  headers: {
    'Access-Control-Allow-Origin': 'http://localhost:8080',
  }
}, {
  emulateJSON: true
}).then(response => {

  console.log(response);

}, response => {
  // error callback
});

Now in my D8 backend:

$params = $request->request->get('params');
$message = $params['message'];

And now it works as expected.


How to show filesize when content type contains more than one file?

Actually it works fine for me without additional settings

My configuration :

I used content-type : Article and create some fields file
Your first step is good, you need to add a relationship select File Usage: File
Then in your fields section you can add : Content: Title , File: Size, File: Name

I have a listing of all the name of the file with their size.
If you want you can group by Articles.


Google Page Speed Insights recommends Leverage browser caching

As these files ain't located on your server you can't do anything about it except wondering why Google Page Speed isn't smart enough to distinguish between on-site resources and external resources. Or why Google itself doesn't do with these files what it suggests should be done with them. I guess, that's some weird kind of paradox ;)

All you could do (highly hypothetically) is to download these files and  add them to your own server and let Drupal use these local copies instead of the remote files. But I assume very strongly that this would break the functionality of these services.


Your canonical reference for this is here. In short:

Save the CSS or JS to a file. (I normally do this at
docroot/themes/projecttheme_directory/js/)
Define a "library", which can contain both CSS and JS files.
"Attach" the library to a render array in a hook.

You can add these files globally, (see "Attaching to all pages") or to specific pages or blocks, (Attaching a library in a Twig template) There's a good deal of flexibility in how you can add your javascript, so be sure to review all the options listed there.


Drush upwd Changes Database Hash but Login Fails

Check to see if your cookies are being set correctly. It's possible that your login is succeeding, but if the session cookie is not set, then you will be immediately logged out again (or, more to the point, the browser won't get the message about you being logged in and will continue to present an anonymous user to your site).

Check your settings.php file and see if you have any configuration options related to the cookie domain that are not correct.


How to get taxonomy contextual filters working by name for users?

You should just be able to add the Taxonomy field you associated with the user as a relationship, and then filter on that.


Rules module: How do I execute code just before content is deleted?

You might be looking to implement hook_delete().

You can also check node_delete_multiple() in node.module, if you want to have an idea of what Drupal core does when it delete nodes...there's other hooks that get called as well.


As megadesk mentioned its hook_form_alter you're after.

Depending on what your more comfortable with you can either add this to your theme in template.php or you can add it to a module. I'm going to assume from now on that you'r putting it into template.php. An infact rather than hook_form_alter we'll use hook_form_FORM_ID_alter.

/*
* Implementation of hook_form_FORM_ID_alter
*
* Adding text after the comment form
*/

function YOUR_MODULE_NAME_form_comment_form_alter(&$form, &$form_state) {

    //add an I agree to house rules checkbox to the form
    $form['markup'] = array(
                 //This is the text you want to add to the form, using the t() function allows it to be translatable
                '#markup' => t('You can leave us a message using the contact form below.'),
                //By making the weight 20 we insure that it appears at the bottom of the form
                '#weight' => 20,
        );
}

I havnt tested this but that should be what your after... Let me know if you need more.


PDF version is different from Printer frendly version - using dompdf

Instead of using that module, I prefer to use PrintFriendly where you don't need to install additional scripts. And it's customizable too.


Disable search form in nav from collapsing

You can change your markup using the page.tpl.php

Copy the page.tpl.php file from /bootstrap/templates/system to your theme.
Edit the page.tpl.php that you've copied.
Move the line 108 - 110 below / above the navbar-collapse collapse div.

Create a new div.
Put the code from line 108 - 110 into the new div.
Save
The changes should be like the screenshot below.

Flush cache


Add an attribute to a specific tag in text body of page

Since you are just looking to add an attribute to a tag, you could do your changes to the field #markup instead. A simple example:

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'body') {
    $markup = preg_replace('/href=/', 'title="foo" href=', $variables['items']['0']['#markup']);
    $variables['items']['0']['#markup'] = $markup;
  }
}


How know if user is visitor or logged member?

For the sake of more robust and descriptive code, you can make use of the handy User::isAnonymous() method, e.g.

if (\Drupal::currentUser()->isAnonymous()) {
  // Anonymous user...
}


How to detect Panelizer use in template_preprocess_html()?

I'm not sure if this is quite what you're after, but these hooks will fire if your page is using panelizer.

/**
 * Implements hook_preprocess_panels_pane().
 */
function YOURTHEME_preprocess_panels_pane(&$$variables) {
  // If this triggers then you are in a panels pane.
}

OR

/**
 * Implements hook_panels_pane_content_alter().
 */
 function YOUR_MODULE_panels_pane_content_alter($content, $pane, $args, $contexts) {
  // If this triggers then you are altering panels content.
}

If you want to check for panelizer in the node you could try something like this:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node->hasField('panelizer')) {
  // Do stuff
}


Using to user_profile_form being used on a page thats not /user/#/edit

You're likely using module_load_include() to include modules/user/user.pages.inc.

However, you need to use form_load_include() whenever you attempt to load, build, process, and render a form that is defined and constructed in an entirely different include file.

form_load_include() requires to pass the $form_state in order to record the file to include (and automatically load it later, if needed). This needs to happen before the form structure is cached (which happens directly after invoking the constructor).

In order to do that, you can resemble what drupal_get_form() does, and inject the needed form_load_include() prior to building the form, like this:

$form_id = 'user_profile_form';
$form_state = array();
$form_state['build_info']['args'] = array($user);

// Load user.pages.inc and ensure it is automatically reloaded if
// this form is rebuilt via AJAX or other means.
form_load_include($form_state, 'inc', 'user', 'user.pages');

$form = drupal_build_form($form_id, $form_state);

More details:

Normally, Form API automatically takes over the include file to load (if any) from the menu router item definition in hook_menu().

In your case, your custom 'my/account' menu router item is not directly related to user.module, nor user.pages.inc, so the system does not know that this include file is required to build the form, especially when the form is submitted and rebuilt via AJAX — which happens on yet another system path/menu router item, namely 'system/ajax' (which, by default, would only know about an include file of your 'my/account' menu router item, if any).

In turn, Form API gets a request to rebuild user_profile_form, but the form constructor function user_profile_form() is not defined, because user.pages.inc was not loaded, since the cached $form_state does not contain a pointer that the file needs to be loaded.


Getting views contextual filter from url for display suite block

Here is a kind-of-complex sketch for your problem, using only Views:

Create a block view displaying Content of type Event
Add a "Content: Nid" contextual filter, using the default settings. You may need to set the default value to "Content ID from URL" for the case "When the filter value is NOT available"
In your View configuration, under "Relationships", create a "Entity Reference: Referenced entity" relationship for your reference field (e.g. field_venue) and click on "Require this relationship": This relationship will retrieve the venue of the Event that is defined from the contextual filter.
Create a second relationship, one of type "Entity Reference: Referencing entity", again for your reference field (e.g. field_venue) and click on "Require this relationship". Important: Use the first relationship (step 3) for this one: This second relationship will retrieve the events that reference the venue we got from the first relationship.
Set your Views format to use fields (either by using a Table or by ticking the "Force using fields" option).
Add the fields you want to display and select the second relationship you created for them.

At this point your block should list all events for the venue of your current event. The problem that still remains is excluding the current event from that list. Follow steps take care of that:

Add two "Content: Nid" fields, set one of them to use the second relationship and exlude them from display.
Set a "Global: Fields comparison" filter and set it to filter out rows when the two excluded fields from above are equal: This will take care of excluding the actual event from showing in the block.

Once you place this block inside an event node page, it should display a list of Events from the same venue excluding the current event.

Cheers and let me know how this goes.

Appendix A:

Appendix B:


How to stop Privatemsg showing user role in 'To' field

Inside the privatemsg module, in hook_menu search for $items['messages/autocomplete'] this is where the menu defines the auto complete path.

Search for privatemsg_autocomplete function where the output is defined.

UPDATE:

To remove just the role, here is a patch for that. Here is a thread on drupal that shows how this has progressed https://drupal.org/node/1852746


menus from modules: help me understand basic menu concept in drupal7

Take a look at the Views Module.  You can define your page view and attach it any menu.
Define it with a path such as control/%/jobs and set it to provide a list of all jobs using filters and format settings Set the menu type as menu tabs, and give it a name.
Add additional pages to the same view and with paths such as control/%/job and use a contextual filter to read the value in the URL in the % wildcard position. (You may have a bit of trouble if the wildcard is multiple words due to spaces vs. dashes in the path. If so ask another question here). Set the menu tab for this item as well.

Menu tabs are the menu that appears above the content (user Admin has View and edit tabs for content pages).  Note that you must have two menu tabs for them to show.

Your pages for download and settings sound like they require user input.  Those pages will require either an add-on module or custom coding to design a form.


What I'm getting here from your question is, you want to search on the basis of category.
I think, you can use exposed filter in the views to get your desired result.

You can find exposed filer in views Under "Filter Criteria".

Hope it will help you.


How do you get the url of an image in a view twig template?

There is a raw variable available - you can use it to get raw result from the query, with all data it fetched.
You can inspect it with the devel or twig_vardumper module using xdebug or dump(raw). More about debugging twig templates: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates#s-viewing-variables


The guide you are referring to assumes that you will be tracking your website as a git project. This is the best way to develop locally before deploying on the server.

The workflow for that is to use composer create-project, then initializing the git repository and adding everything. The default .gitignore should ensure that the installed code isn't added. However, the scaffolding files like index.php and autoload.php are. Once that is done, you can deploy the site on any server by cloning the repository and running composer install.

When the guide says that after updating you should

  Run git diff to determine if any of the scaffolding files have changed. Review the files for any changes and restore any customizations to .htaccess or robots.txt.

it means that updating may have replaced these files, and you may need to re-add custom changes and then commit the new files to git.

composer doesn't create any "backups" when overwriting the scaffolding files - this is why it is important to track the scaffolding files in git, especially if you have custom modifications.


Adding a filter to a view "or" remove results?

I figured this out.  In order to prevent this behavior, I had to check "reduce duplicates" in the filter, as well as remove some "required relationships.


MIssing 'Drush configuration' and 'Php configuration' when running 'Drush status'

One of my colleagues has MAMP installed and that's what his Drush status looks like too.

I'm using the build of Apache built in to OSX and the only difference I see is that the PHP configuration is filled in:

Like you, neither my colleague or I suffer any problems with these settings missing so I wouldn't worry too much about it.


Where is source code of advanced search form?

The advanced form is altered in node.module and not in search.module. you can find the below function for advance search in node.module, Please have a look in the below hook:
 function node_form_search_form_alter(&$form, $form_state)


Form theme function is not invoked for a block content

Somehow, this started working on my localhost. I think this was a cache issue. If you have the same problem, try clearing the cache.


You should not try to hard-code the URL to the item in the menu item edit screen.

You should add a View to your Menu.

Views allows you create a view including a filter to show only recent content.

You can then add a filter for a specific Content Type, User or whatever. And you can limit the View to show only N items.

You can insert the View of new items into your menu with the help of 3rd party modules, an example is Menu Attach Block, see the project page for a list of similar helper modules.


How to invite Facebook, twitter, gmail friends into organic groups

You can make use of Contact Importer module.

  Contact Importer provides a form for your users to enter their email
  address and password. The contacts from their address book are then
  retrieved.

Of course you need to alter the module to send invites.

Or

Try using Rules Module with this, to make it a chained process.


Trying to modify Main menu by testing $vars['heading']['text'] == 'Main menu',

You can do it by using this code in template.php file of your active theme.

function mytheme_links__system_main_menu($variables) {
  $html = "
";
  $html .= "
";
  foreach ($variables['links'] as $link) {
    $html .= "
".l($link['title'], $link['path'], $link)."
";
  }
  $html .= "
";
  $html .= "
";

  return $html;
}

or you can add customization in $variables also if we have do minor customization to do.
Here replace mytheme with name of your theme.
Clear you cache after using this code.

Hope it will help you!


How can I use session variables in a report created with the Forena module?

I'm not (yet) sure about this one, because of the "session variables" that aren't clear enough to me (yet) ... Below are a few techniques (features) that you may want to consider to get it to work.

1. Using JavaScript and/or Skins

A possible solution "might" be to think of some technique you can implement via a JavaScript. And then make that JavaScript available via what in Forena is called "skins" (used for e.g. theming a report, like to enable the 'DataTables' plugin if you want, etc).

There are some "interesting" issues in the Forena issue queue with some great examples (ideas) of things you can do (add to Forena) via JavaScripts and/or Skins. HEre are a few of them:

Using the dataTables plugin to format reports, via an appropriate "skin".
Making table headers sticky, note the comments nr 8 (using Drupal Behaviours) and nr 10 (adding some JavaScript library).

2. Specifying Report Parameters as part of the URL

Report Parameters are similar to using arguments in Views. You can specify them as part of the URL, by first adding a ?-mark, followed by the name of the report parameter, a =-sign, and then the parameter value. So something like ?state=VA that you append to the report URL.

To see it at work in the demo site, try this example which uses ?state=VA (watch the URL of it also). Then change the end of the URL to something like ?state=IL,  ?state=CA, etc. To be complete, you can also specify multiple parameters (+their values) in an URL.

So if you have a way to massage those session variables in a such string added to the URL, then the answer to your question is something like "pass them as report parameters via the URL".

3. Other approaches

If what is above won't work, then please add more details about those "session variabes" (so that I can refine/rework my answer accordingly).

And if we don't find a real answer, then its time to experience the "support" that comes with Forena, via its issue queue on D.O. ... After all, keep in mind that I'm only a co-maintainer of this module. When I'm stuck (or out of Forena-inspiration), I escalate such questions/issues to David (the module owner and creator or Forena).


Having been through this before with OG tags and Facebook, if your site has been up and you verified the OG tags are in the source and work, then the likely culprit is that Facebooks crawler cached the page before you added the tag and you will need to wait a while.

If the image url resolves and the tag is right, it just takes time.

Perhaps try to look into using the Facebook debugger, something like in this article: https://www.braveriver.com/how-to-clear-facebook-open-graph-and-twitter-cards-cache-on-demand/

We saw this behavior with both Facebook and Twitter. IIRC it took about 3-6 hours to see them "appear" after initial attempts.


How can I add an operation to the node and user lists?

If you look at the User module in DRUPAL_ROOT/modules/user you'll see the user_menu() function:
http://api.drupal.org/api/drupal/modules!user!user.module/function/user_menu/7

You can add your own operation by making your own hook_menu() that mimics what Core does for the "Permissions" Operation. Its also important to note that these tabs or drop down operations (depending on your theme) are essentially defined as MENU_LOCAL_TASK items in the drupal menu system. See below:

// What Core does in user_menu() ...
 // Permissions and role forms.
  $items['admin/people/permissions'] = array(
    'title' => 'Permissions',
    'description' => 'Determine access to features by selecting permissions for roles.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_admin_permissions'),
    'access arguments' => array('administer permissions'),
    'file' => 'user.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );

// You do something similar in your own module ...
  function mymodule_menu() {
    $items['admin/people/foobar_operation'] = array(
      'title' => 'Foo Bar Operation',
      'description' => 'A form with my custom settings',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('yourmodule_foobar_permission'),
      'access arguments' => array('administer yourmodule permissions'),
      'file' => 'yourmodule.admin.inc',
      'type' => MENU_LOCAL_TASK,
    );

    // Do the same for stuff under admin/content.

    return $items;
  }

Hopefully this tidbit helps...


Set the default value to now using GUI. This should give you what you need without any code.

If you need to use fiscal years, either create own custom filter, one that will translate real date to fiscal year. Read manual and more detailed manual to see how to do it. Simply changing default value in date will not be enough, as user may inject date with more than a year set, making built-in filter not work the way you want it to. And then, well, then use now as default value.

You probably want to inherit from class views_handler_filter_date and override it's extra_options() method


Is there a way to setup a site monitor on drupal?

mysql and httpd logging on your server should help a bit.  turn them on (and adjust reporting levels) but make sure you don't fill up your disk with logs.  turn the logging level back down to something normal once you've looked for a while.


How do you embed an external URL (to a software application) in Drupal with 508 compliance?

I can't find a single reference on Google that says iFrames aren't section 508 compliant...however they will fail compliance if you do not:

  Provide alternative content for IFRAME elements

iFrames can contain nested alternative content, like so:

Description of the loaded content

The rationale listed for this is:

  Some browsers do not support the IFRAME element, or do not have the ability to load multiple documents together. It is therefore necessary to provide alternative content for this element even if the IFRAME only loads HTML.

This information came from here, but all of the other links I found on Google said exactly the same thing in one way or another.


How to convert a timestamp field into a date field?

Export/import with Feeds

Feeds module can help to export the existing Timestamp field data and import it into a new Date field.

Feeds Tamper to convert from timestamp to ISO date format

I'm not sure if you can export timestamp into the ISO format directly. If you can't, then you may convert the timestamp to ISO format externally once you have it in a CSV file for example, or you use Feeds Tamper module to convert it during import.

Unix timestamp to Date is on the Feeds Tamper plugin list.

Setting up Feeds can take patience and time, so arm yourself with those, backup everything before starting to meddle with it, and test everything on a local/dev instance. (This always applies, but I find it's good to remind when dealing with Feeds.)

After you have the Date field correctly filled with data, you'll want to delete the Timestamp field.

Delete old Timestamp field

To do that you need to delete the Timestamp data and then the field from your system. You won't be able to delete the field that has some data in it.

To delete the Timestamp data you can use another Feeds import to update the nodes and make that field empty.

You could also delete the data with the help of Views Bulk Operations (VBO) or work directly on the database through some other SQL tool but that is probably out of scope here.

When the Timestamp field is empty you can delete it from your content type through the usual Drupal interface.


I found mistake. I accidently named field_file as field_fiele. Damn it four houers from life. Code works correctly.


How do I generate an order using the "Add to Cart" button in a custom PHP page?

Though I prefer the Commerce Add To Cart Filter module to adding a "Add to cart" button anywhere in my content by mentioning the product ID with the suggested method, since you need PHP code, I am copying my old code which I don't use anymore; maybe it can help you.

function MYMODULE_commerce_menu() {
  $items = array();
  $items['mysite/trial-buy'] = array(
    'title' => 'Trial Plan',
    'page callback' => 'MYMODULE_add_single_product',
    'access arguments' => array('view published content'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MYMODULE_add_single_product(){
  global $user;
  $product_id = 59;//This is my product ID, place your's here.
  $order = commerce_order_new($user->uid, 'checkout_checkout');
  commerce_order_save($order);
  $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  commerce_line_item_save($line_item);
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;
  commerce_order_save($order);
  drupal_goto('checkout/' . $order->order_id);//Forward to checkout. You can have your method here.
}

This is the code I came out with the help of Commerce guys documentation when I was working with some custom need like yours.


I ran into this issue as well moving to opensuse leap from another distribution.  There was more than one problem.

Even if rewrite_module is listed in loadmodule.conf, this file is not not read without a change to httpd.conf.  You can check if the module is loaded with
apache2ctl -M

As is posted elsewhere Options and AllowOverride arguments need to be placed within the relevant Directory tags.

If there is a subdirectory of the webserver, there needs to be a RewriteBase argument given in the .htaccess file.

Try this to get things working:
In file /etc/apache2/default-server.conf
Within the <Directory> tags add or edit the Options and AllowOverride lines to
Options All
AllowOverride All

In file /etc/apache2/loadmodule.conf add
LoadModule rewrite_module    /usr/lib64/apache2-prefork/mod_rewrite.so

In file /etc/apache2/httpd.conf uncomment the IfDefine tags
#<IfDefine !SYSCONFIG>
  Include /etc/apache2/loadmodule.conf
#</IfDefine>

In file /srv/www/htdocs/NAMEOFYOURSUBDIRECTORYHERE/.htaccess add a line
RewriteBase /NAMEOFYOURSUBDIRECTORYHERE

Check if the configuration file "Syntax is OK."
It will probably complain that some modules have already been loaded, but that's alright.
 apache2ctl configtest

Restart Apache
systemctl stop apache2; sleep 5; systemctl start apache2


How to increase password length while creating account on a drupal website?

Sounds as if you need the Password Policy module.

From the project page:

  This module provides a way to enforce restrictions on user passwords by defining password policies.
  A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.


It is correct that Drupal has only a very course access control structure for individual nodes (the basic access control system in Drupal is by content type).  For more fine-grained access control than content type, you need to add a node access control module to your site.

There is a page at the Drupal.org wiki giving an overview of node access modules.  You may start by reading that and try to find a suitable module. This page also provides a gentle introduction to node access control in Drupal.

One of these modules is Nodeaccess (also suggested by Ursula).  It lets you control node access (i.e. view, edit, delete) by user and by role.

A simpler alternative is a module named Flexi access.  This only let you set up lists of users (Access Control Lists) that indicate type of access (i.e. view, edit, delete) these users shall have.  It may be simpler to set up and use than Nodeaccess if you don't need to control access by role.

Disclosure: I am a co-maintainer of Flexi access.


Execute actions (actions module not rules module) programatically

You should inject the plugin manager as a service if possible, but for a plugin (code) based action:

$manager = \Drupal::service('plugin.manager.action');
$action = $manager->createInstance('action_plugin_id')
$action->execute();

Or if it's an advanced action, it's a config entity, so load and execute it that way:

$action = \Drupal\system\Entity\Action::load($action_id);
$action->execute();

Again if DI is an option, inject the entity type manager service and use that to load the action instead.


How to handle a post request from an external application in Drupal?

Your path is wrong I think. You should be able to access that callback here.

https://mydrupalsite.com/bh_commerce_stripe_oauth/callback/randomstring

So actually your hook_menu should look like this.

/* Implements hook_menu */
function bh_commerce_stripe_oauth_menu() {
  $items = array();
  $items['callback'] = array(
    'title' => 'bh_commerce_stripe_oauth_callback',
    'page callback' => '_bh_commerce_stripe_oauth_handle_callback',
    'type' => MENU_CALLBACK
  );
  return $items;
}

Note: You don't have any path wildcards (represented by % in your array key) in the callback you are getting that are useful. Therefore you don't need any page arguments. The interesting things are in the $_GET (or $_REQUEST).

And then to access the results something like:

function _bh_commerce_stripe_oauth_handle_callback() {
  $scope = $_GET['scope'];
  $code = $_GET['code'];
  drupal_set_message(t('_commerce_stripe_oauth_handle_callback: called'));
  drupal_goto('<front>');
}


Is a session alone enough for non logged-in users to see some information?

To answer a couple of questions asked:

Extra features to increase safety? You're tying identification/authorization together here; if I know an ID number then I'm authorized to view details associated with it. A malicious actor can just throw guesses at that field to start pulling data they shouldn't have access to. You should increase your authorization criteria (e.g. ask additional details to prove the user is who they say they are)
and make the form more robust against brute-forcing (e.g. limit requests, use other bot-defeating tools, etc.).
Can a session be stolen? Yes. A PHP session is vulernable to session hijacking if you're using unsecure transport. You should enforce an encrypted session so you can rule that out.


Found the problem.

I had a View in the Featured section which showed an image gallery. The Views configuration had a pager on that data and so it was overriding the main pager on the page. I changed the Pager config on the View to "Display All Items" and the main pager is showing now.


Users can now be added in bulk to organic groups using Views Bulk Operations out of box. The simplest way to do this is to take the following steps:

Download Admin Views
Edit the people listing page view at
/admin/structure/views/view/admin_views_user/edit
In the view under
fields, select "Bulk operations: User" Under "Modify entity values",
be sure that either "All" or at least "Group Membership" is selected
Save the view if needed
Go to /admin/people and filter the users as
desired Select "Change value" and click Execute
Under "Fields", select "Group membership", and select the group(s) you wish to assign the users to.
Be sure the "Add new value(s) to Group membership, instead of overwriting the existing values" checkbox is checked or your users will lose their existing membership settings.
Click Next to complete the operation.


How do I fetch the password from the database?

The short answer is you cannot. Drupal is using a SHA-512 which is a cryptographic hash function. SHA-512 is one way which means it is not possible to get the original data back.

You can check this api. https://api.drupal.org/api/drupal/includes%21password.inc/function/user_check_password/7.x and this https://api.drupal.org/api/drupal/includes%21password.inc/function/user_hash_password/7.x.


How do I import configuration without getting these errors?

I have fixed the issue using config suite module: install this module and it will assign the uuid for those enviroments so you don't need to worry to set up manually.


Alter all Webform's form with hook_form_BASE_FORM_ID_alter

the base form is webform_client_form and hook look like

  HOOK_form_webform_client_form_alter

or if using HOOK_form_alter we need statement as

if (strstr($form_id, 'webform_client_form_')) {
  //our code for all webforms
}


How to change items under edit tab on user account page?

If you'd like to hide fields or properties from the user account edit form, you can create a custom module implementing either hook_form_alter() or hook_form_FORM_ID_alter(). The ID of the form in question is 'user_profile_form'.


Not really related to Drupal, but this works on mySQL

MONTH(NOW() - INTERVAL 1 MONTH)
MONTHNAME(NOW() - INTERVAL 1 MONTH)
YEAR(NOW() - INTERVAL 1 MONTH)


How can I make downloads available only to authenticated users?

You can try Private Files download permission module for drupal 7 and you can set permission to download to certain users.


How do I in code add new field values to a D8 content entity?

I'm not sure what you mean with "field value", do you mean field items with multiple values?

It's the same as reading them, nothing special:

// Those are identical, not specifying [0] results in that using by default.
$entity->some_field->value = 'Whatever';
$entity->some_field[0]->value = 'Whatever';

// To add a value for the second item:
$entity->some_field[1]->value = 'Something';

// And persist to DB:
$entity->save();

Edit, the following script works for me and gives me the following output:

<?php
use Drupal\node\Entity\Node;

$node = Node::create(array('type' => 'article'));
$node->field_tags->target_id = 5;
var_dump($node->field_tags->getValue());

$node->field_tags[] = 6;
$node->field_tags[] = array('target_id' => 7);
var_dump($node->field_tags->getValue());

unset($node->field_tags[1]);
var_dump($node->field_tags->getValue());

Output:

array(1) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
}
array(3) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
  [1] =>
  array(1) {
    'target_id' =>
    int(6)
  }
  [2] =>
  array(1) {
    'target_id' =>
    int(7)
  }
}
array(2) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
  [2] =>
  array(1) {
    'target_id' =>
    int(7)
  }
}

The delta is off then in the last example, but this will probably be fixed in https://www.drupal.org/node/2164601, which might also affect how the code above works..


I have Created a form to upload images, where i should display error message if i upload more than 3 images and should disable submit button

Follow the steps

Go to image field settings of you content type.

Then Go to Image Field Settings and select '3' for number of values for the image

That's it. When user reaches their upload limit (3) the submit button will be disappeared automatically. and display like follows.


Exposed Filter Not working in Views Json Query

Try to use a contextual filter (CF) instead of a Filter criteria - When you pick the CF type - Make sure its one of the options that takes filters the data based on something from the URL (in this case, A JSON file name I guess as I Never worked with VJQ).


Problem with overlay in custom webform extension (D7)

The overlay automatically applies to paths that Drupal recognizes as being 'administrative'. That's always the case for paths that start with "admin", for example.

For custom node tabs, however, you'll need to implement hook_admin_paths() to register your custom path pattern:

<?php
function hook_admin_paths() {
  $paths = array(
    'node/*/webform-factors' => TRUE,
  );
  return $paths;
}
?>


Add new existing field for existing content type

if I am not wrong, I believe, Site 1 is your local development environment, and site 2 is your production environment.

I wrote an update hook which will create the same config file (except order), when my module will be updated on other sites, where it was previously installed my module
Why would you write an update hook ? You can simply export the configs, and import them on prod.
If this does not suit you, I would suggest you to use Features module for this. It will make sure you get a working module which can be installed even without features module in place on Prod.


The commands are in a folder called 'commands' in the root of the Drush folder.

If you don't know where that folder is on your machine, running locate drush.php in terminal should help you find it pretty quickly.

In fact, running locate drush/commands should give you a list of all the individual include files related to commands, but it depends if your Drush files live in a folder with that name.


Thanks to the suggestion of @kenorb, I have found a good way to solve this:

I init the git repository in drupal/, and I put  only the following line into .gitignore:

*

Then, I add (by force) my custom module and theme folders:

$ git add -f sites/all/modules/custom
$ git add -f sites/all/themes/custom

With this, my repo still contains only my code and no Drupal modules. And this allows me even to track also my .htaccess, with:

$ git add -f .htaccess


How do I use a display mode for anonymous users, and another one for logged-in users?

This is similar to How do I change the node view mode before rendering?, only that you want to add conditions for the route name and the current user:

/**
 * Implements hook_entity_view_mode_alter().
 */
function mymodule_entity_view_mode_alter(&$view_mode, $entity, $context) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article') {
    if (\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical') {
      if (\Drupal::currentUser()->isAnonymous()) {
        $view_mode = 'teaser';
      }
    }
  }
}


Any twitter boostrap(ish) theme for Drupal 6?

Either you may start creating your own theme (you can use any light weight theme as base theme) from scratch using Twitter Bootstrap, or you may check the couple of options present on the sandbox project, which contains experimental code for developer use, as below:

HTML5 CSS3 base Drupal 6 theme built using Twitter Bootstrap: https://drupal.org/sandbox/drewkennelly/1276010 (Also check issue queue of it: https://drupal.org/node/1276060)
A Drupal 6 Theme with Bootstrap installed: https://github.com/sdmunoz/Drupal-6-Theme-Bootstrap
Twitter bootstrap theme for Drupal 6 created using zen as base theme: http://www.eliotdill.com/2012/06/twitter-bootstrap-theme-for-drupal-6/

If any of the above suits your requirement, then you can use them and modify it as per your need, instead of creating it from the scratch.


Node Access permission for anonymous users

Content Access controls access by content type. The module you want is the Nodeaccess module.


The line-item unit price is used throughout commerce and the total order amount is based on the line-item total value (quantity * unit price). There is no way to circumvent this behavior.

Better would be to add another price field to the line-item Price per length-unit. Hide the default price field and calculate the sales price as you've found in other answers.

Basically this is a pricing rule in Store > Configuration > product pricing rules where you add the event Set the unit price to a specific amount to a calculated value.


I tracked it down.

Node_load() was dying whenever the query it was trying to run, failed. The query failed because it was joined on the UID of the author, and some users had been deleted. Lists of content that didn't use node_load() yielded the node's info without incident.


Bulk Generating URL aliases for taxonomy terms doesn't do anything

You'll need to troubleshoot your own site configuration to understand what's not causing the path update on the bulk form. If you look at the flow of execution, you can follow

The bulk update submission handler
The bulk update batch processor
The bulk updater

Ultimately, all the form is doing to update is using pathauto_taxonomy_term_update_alias_multiple() to load/save a group of tids in bite-sized chunks; if you fail to pinpoint the problem, you can use that function to do what you're already doing manually.


Why running cron tasks would hit a REST service endpoint?

It's impossible to answer the question directly because we'd have to speculate about the all the possible states of your Drupal installation where rest_server_server() is hit in a a cron context.

However, since you know where the notification message is being produced, and you can trigger it in a Drush command, what you can do is insert something like debug_print_backtrace() in the rest_server_server() function then re-run the Drush command to get an idea of what module/configuration is causing that to occur and if it's causing cron to die on you.


Alternatively, you could implement template_preprocess_html in your [themename].theme file.

function themename_preprocess_html(&$variables) {
  $variables['attributes']['class'][] = 'class-name';
}

See the documentation: https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/template_preprocess_html/8.2.x


views replacing ul li within a large block of html text

I would suggest installing the Theme developer module and tracking down the template that might be rendering that output.


Displaying a Block on 2nd level pages but not 3rd level

The drupal.org/project/context module can do this. In addition to the typical wildcard * operator ... its Path conditions support a Not operator ~.


How can I check the changes for the fields at form alter submit?

Try comparing both $form_state[input] and $form_state['values'] .

After that check both values using the key's in foreach loop and compare both values, if changed then do your things there.


The easiest way to load a field from any entity when querying is to use the entityTypeManager:

$users = \Drupal::entityTypeManager()->getStorage("user")
        ->loadByProperties(['uuid' => $uuid]); // or any other properties.

foreach ($users as $user) {
    var_dump($user->field_customfield->getValue());
}

see:  working-with-the-entity-api

Be careful to not use \Drupal::entityManager, since it is deprecated.


Uninstalling modules doesn't remove them from modules list

The modules on the file system are not intended to be deleted if you uninstall them. Although I can see that the terminology may be confusing.

Uninstalling will delete any references to the module in your site (assuming the module is written to do so), but will not affect the file system in any way.

The only reference to the module will be on the modules page, it will not be used in any live pages on your site. So should be harmless, but if you don't want the module to appear on the modules page you will have to manually delete the files.


Permission to edit orders, but not delete

Here's the proper way to do it with

hook_commerce_entity_access

  Allows modules to deny or provide access for a user to perform a
  non-view operation on an entity before any other access check occurs.

  Modules implementing this hook can return FALSE to provide a blanket
  prevention for the user to perform the requested operation on the
  specified entity. If no modules implementing this hook return FALSE
  but at least one returns TRUE, then the operation will be allowed,
  even for a user without role based permission to perform the
  operation.

  If no modules return FALSE but none return TRUE either, normal
  permission based checking will apply.

Example

/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order' && $op == 'delete') {
    // Require administer orders permission to delete orders
    if (!user_access('administer commerce_order entities', $account)) {
      return FALSE;
    }
  }
}


Select the right pathauto alias for a node

Another option, and I find this to be preferable to altering the token because it's exposed to site builders and makes what's happening perfectly clear in the UI, is to create your own custom token that will return /global or /local for that piece of the url. You just need to implement hook_token_info and hook_tokens. This blog post walks you through the process.

Ex:

/**
 * Implements hook_token_info().
 */
function MY_MODULE_token_info() {
  $info['tokens']['node']['MY_TOKEN_ID'] = [
    'name' => t('MY TOKEN LABEL'),
    'description' => t('Return "/global" for nodes with the global checkbox checked, otherwise returns "/local".'),
    'type' => 'url-fragment',
  ];
  return $info;
}

/**
 * Implements hook_tokens().
 */
function MY_MODULE_tokens($type, $tokens, array $data, array $options, Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'node' && !empty($data['node']) && isset($tokens['MY_TOKEN_ID'])) {
    $node = $data['node'];
    $global_or_local = '/local';
    if ($node->hasField('MY_GLOBAL_FIELD') && !empty($node->MY_GLOBAL_FIELD->value)) {
      $global_or_local = '/global';
    }
    $replacements['[node:MY_TOKEN_ID]'] = $global_or_local;
  }
  return $replacements;
}

Note: I'm not sure if that logic to determine global or local is perfect, but it should be close.


Facet API: grouping indexed values into several drop-down facets

If possible, I'd use a vocabulary for each of the facets ('dropdowns'). Add a term referenece field to your node for each of those as well. Then add these fields to your search index and add the facets for them.

E.g.,
Vocabulary:
CPU

Terms:
Core i5
Core i7
...

Vocabulary:
Memory

Terms:
4 GB
8 GB
..


I suggest implementing hook_entity_presave() getting values from taxonomy term reference field. If always the pre-term will be the parent of the current term then loop through the results of the term ids:

 if ($entity->getEntityTypeId() == 'node') {
    if ($entity->bundle() == 'Machine_Name_content_type') {
    // Get the values from taxonomy term:
    $terms = $entity->get('field_tags')->getValue();
    if (!empty($terms)) {
        foreach($terms as $key => $value) {
            // Exclude the first term because this will be the parent.
            if ($key != '0') {
                // Get the parent of the element.
                $parent = $terms[$key -1];
                // Load the current term.
                $term_loaded= \Drupal\taxonomy\Entity\Term::load($value['target_id']);
                // Set the parent: the term before.
                $term_loaded->parent = ['target_id' => $parent['target_id']];
                $term_loaded->save();
            }
        }

     }
  }
}

Hope to help you!


How does one create terms on hook_install if hook_taxonomy_default_vocabularies is used in the same module?

Although you can use hook_install(), it's best to use hook_enable() to check if the vocabulary exists and, if not, create it programatically:

$vocabularies = taxonomy_vocabulary_get_names();
$pos = array_search('my_vocabulary', $vocabularies);

if ($pos !== FALSE) {
  // its a keyed array so the $vid is actually $pos
  $vid = $pos;
} else {
  // arrays are more convenient to initialize
  $vocabulary = array(
     'name' => t('My Vocabulary'),
     'machine_name' => 'my_vocabulary',
     'description' => t('My description'),
     'hierarchy' => 1,
     'module' => 'your_module', // or nothing
     'weight' => 1
   );
   // argument must be an object
   $vocabulary = (object) $vocabulary;
   taxonomy_vocabulary_save($vocabulary);
   // horray, we have a vid now
   $vid = $vocabulary->vid;
}

// now that the vocab exists and you know the $vid, create your terms
// ...


Generate google search result for my website like that of flipkart

I believe this technique is call Rich Snippets and this might be a cool module for you: https://www.drupal.org/project/schemaorg


It sounds to me like you need a multi-site Drupal installation and each of those sites needs something like organic groups and also i18n.

Unless I am misunderstanding... what you're describing only makes sense if all the content across all sites is the exact same,  just translated versions.


You can tell the Pop-up date widget to use wvega-timepicker depending whether you're using a Date field or custom module there are different ways of using it.


Drupal 7 Display a list of reference node in node being display

You need to create a view of contents filter by Course content type. Now I assume you have a field name field_school.

Add this field in Contextual Filter and select default argument Content ID from URL.

When this block will be added on node page, it will automatically filters the courses of that school. Otherwise pass the school id as argument to view. :)

Here is the screenshot :


What does 'Rebuild Permissions' actually do?

Drupal core uses database tables to control some aspects of content viewing/editing permissions. These tables are used by contrib modules like Domain Access or Taxonomy Access Control to store information about which roles/users can see which nodes. Because it is not easily determinable which configuration changes will result in actual permission changes Drupal marks these tables as needing updating for a broad set of configuration changes.


Include HTML in theme_pager_next $text variable?

If the rest of the code is the same used in theme_pager_next(), then it is not possible to add HTML tags to $text.

This is because theme_pager_next(), and theme_pager_last() call theme_pager_link(). theme_pager_next()'s code is the following one.

if ($page_new[$element] == ($pager_total[$element] - 1)) {
  $output = theme('pager_last', array('text' => $text, 'element' => $element, 'parameters' => $parameters));
}
// The next page is not the last page.
else {
  $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters));
}

theme_pager_link() then contains the following code.

$attributes['href'] = url($_GET['q'], array('query' => $query));
return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';

As it calls check_plain(), if $text contains HTML tags, they are shown as plain text.

To achieve what you are trying to do, you should override theme_pager_link() with a theme function that doesn't call check_plain(). filter_xss() could be a better function to use in this case, but remember to pass in $allowed_tags the list of the tags you want to allow.

As side note, when you want to alter the content of the $variables array a theme function gets, in Drupal 7 you can use its preprocess functions. Every theme function has preprocess functions, and in your theme that is THEME_preprocess_pager_next(). (Replace THEME with the short name of your theme.)


Get Absolute url using hook_preprocess_node

In order to get this to work, I did the following. This assume you have access to the $node object, which you would if you are performing this within the hook_preprocess_node() hook.

$variables['url'] = $node->toUrl()->setAbsolute()->toString();


Something like this may work:

/**
 * Implements hook_field_widget_form_alter
 */
function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'image' && $context['instance']['widget']['type'] == 'image_image' && !empty($context['instance']['settings']['title_field'])) {
    foreach (element_children($element) as $delta) {
      $element[$delta]['#process'][] = 'mymodule_image_field_widget_process';
    }
  }
}

/**
 * Image field process callback
 */
function mymodule_image_field_widget_process($element, &$form_state, $form) {
  // Set title maxlength, if accessible
  $maxlength = variable_get('imagefield_maxlength', 40);
  if ($element['title']['#access']) {
    $element['title']['#maxlength'] = $maxlength;
  }

  return $element;
}


Fatal error "Cannot redeclare template_preprocess_select()" on every attempt to install modules or themes

Mac OS X should have any of these possible reasons:

Your site folder name is mixed case
You cd'd into your site folder name with the wrong case i.e. cd ~/sites/myproject instead of cd ~/Sites/myproject
Your groups are incorrect (use staff not wheel)
Drush is using a different version of PHP from MAMP (Check the output of php --version.)

If you get a redeclare error running drush cc all, check one of the above issues. If sudo drush cc all does not produce the error, it could be one of them. In my case, changing the case of my project from ~/Sites/MyProject to ~/Sites/myproject made the issue go away.

For more in-depth discussion, see:

https://www.drupal.org/node/1305254
https://www.drupal.org/node/1296594


How to create display page depending on role?

Try Front Page Module
Features

The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:

Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
Redirect - Allows you to redirect users to a local or remote URL.
Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

Hope this will help you..


Add/remove roles after submitting a certain webform

\Drupal::currentUser() loads only an Account, but you need a fully loaded entity to modify and save the user:

$account = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($account->id());
$user->addRole('styled');
$user->save();


How do I recover a deleted Views display?

To revert the whole view back to what the faq module provides by default:

Go to the views listing (admin/structure/views).
Click the little arrow next to "Edit" in the operations column.
Click the "Revert" link.
Click the "Revert" button.


How to print user role in body profile page

The html.tpl.php template uses the $classes variable to add classes to the body element. You can use template_preprocess_html() to add classes to this variable. Add this function to your theme's template.php

//Replace MYTHEME with the name of your theme
function MYTHEME_preprocess_html(&$variables) {

  //Check if the path is a profile page with a valid user
  if(preg_match('/^user\/(\d+)/', current_path(), $matches) == 1) {
    if($user = user_load($matches[1])) {

      //Add each role to the $classes_array which makes it available in $classes
      foreach($user->roles as $rid => $role) {
        $variables['classes_array'][] = str_replace(' ', '-', $role);
      }
    }
  }
}


Why isn't the value for a new Boolean field rendered?

This is a Durpal 7 Problem.
It lies about that it will fall back to 0/1 if you don't provide your custom true/false values, when it actually does not fall back.
See
https://www.drupal.org/project/drupal/issues/1750950

In short, in the field-settings, you have to set on-/off- values.
If you don't the default renderer will output an empty string and in the edit forms the field's checkbox or radio-buttons will have no label.


You can install the Administration menu module. Then you can navigate to your Content Types like this:

Or you can install the Menu block module and create a block with the links to your Content Types like this:


Do i need to worry about using deprecated functions in Drupal 8?

I don't have a reference handy, but I had the conversation about removal with one of the Drupal committers this weekend.

Right now, the committers will not remove any functions from core that are marked as deprecated.

Currently, there is no work being done on Drupal 9.  When the 9.0.x branch gets forked from 8.x.y, they will start to accept patches against 9.0.x that remove deprecated functions.

However, there is work to remove usage of deprecated functions in core.  For example, format_date() is marked as deprecated.  This function will remain until 9.0.0 is released, and it will never actually be removed from any 8.x.y version.  However, patches against 8.x.y will be accepted to replace format_date() in core with use of the date formatter service.  And, in general, no new usages of deprecated functions are allowed in patches (there are some small exceptions for this for consistency sake, mainly in tests).

Should you use them?  In general, no.  Typically, a deprecated function was a placeholder from Drupal 7 while Drupal 8 was being developed that didn't get replaced (eg, format_date()), or left for backwards compatibility as Drupal 8 got refactored (eg, the Entity Manager service).  Nearly all of the docs on deprecated functions describe what should be done instead.  In PhpStorm, Command-B will take you to the function definition, and Command-[ will take you back to where you were.


How to use the Elements module to make $form['element'] = array( '#type' => 'number' );

Have a quick look at the code of the elements module.

The number field is defined like this:

  $types['numberfield'] = array(
    '#input' => TRUE,
    '#step' => 1,
    '#process' => array('ajax_process_form'),
    '#element_validate' => array('elements_validate_number'),
    '#theme' => 'numberfield',
    '#theme_wrappers' => array('form_element'),
  );

So you should use '#type' => 'numberfield' instead.


How do I allow users to determine which other users can edit their content?

Node access user reference worked for me, and was quite easy to use from the users perspective.


Edit: I wrote this for Drupal 8 before reading that the question is for D7. Hopefully it works in D7 as well.

You can do this using a views attachment. I'm basing it off the image you provided.

Set up

Create a new content type, call it Person, give it a title, image and body field. Set up the teaser for that content type according to how you want the selected person to display in the top view.
Install the Ajax links API module. This is required for this solution to work.

View 1, the list

The list is the bottom half of the image, which is a list of the people, showing a thumbnail of the image, and the title of the person.

Create a new view of the people content type. Create a page for this view.

Set 'format' to 'grid'
Set 'show' to 'fields'
Add a field for Content: ID. Check 'exclude from display'
Add a field for Content: Image (or whatever you named the image). Make sure it comes AFTER the Content: ID above. Rewrite the results to {{ [FIELD_NAME] }}. Note that you have to replace [FIELD_NAME] with the name of the field, and [VIEW ID] with the machine name of your view.
Add a field for Content: Title. Make sure it comes AFTER the Content: ID above. Rewrite the results to {{ title }}. Note that you have to replace [VIEW ID] with the machine name of your view.
Set up a pager if necessary, and customize the number of items to be shown in the grid.

Now you have a page that lists off your items in a grid, with both the title and the image ajaxified using the Ajax links Api module, ready to load content into a div. The final thing to do is to load the content into the div.

View 2, the attachment

Next, a View's attachment is created. This will display the teaser for the first person in the list, when the page is loaded.

Click the "+Add" Link, and select "Attachment"
Set 'Format' to 'Unformatted list'
Set 'Show' to 'Content', and select 'Teaser' as the view mode.
Under 'Attachment Settings', set 'Attach to' to the first view you created (the page view).
Set 'Attachment Position' to 'Before'
Set 'Inherit contextual filters' to 'Yes'
Set the pager type to 'Display a specified number of items', and set it to show a single item.

Now, when the page from the first view is loaded, the teaser for the first person will be loaded. You can alter the display of the teaser of the person content type accordingly, to show whichever fields you need.

View 3, the ajax-loaded content

The first view is set up with ajaxified links, set to display the content of the path /node/%/teaser. This page does not yet exist. The final step is to set up this page, so that the links can load this content into the container specified in the ajax links.

Click the "+Add" Link, and select "Page"
Set the title to <none>
Set the format to 'Unformatted list'
Set 'Show' to 'Content' with the 'view mode' to 'teaser'
Set the 'path' to /node/%/teaser
Set the 'pager' to 'Display a set number of items' and set it to show 1 item.
Add a contextual filter for Content: ID. 'When the value is not in the URL' set it to 'show page not found'

Now you should be able to access the page created in the first view, and click on the links to ajax load the content replacing the attachment that is initially shown on page load.


How to update Geofield using a custom form and DrupalGap's node_save?

From this example it looks like the syntax is along these lines:

var node = {
  type:"donation",
  title:"Donation",
  field_donation_amount: {
    und: {
      0: {
        value: form_state.values.amount,
      },
    },
  },
};

Addition:

So have you looked at something like this then?  Nesting things further, eg:

var node = {
  field_geocoordinates: {
    und: {
         0: {
            geom: {
                  lat: FOO,
            },
         },
    },
  },
};

(I think I have the correct number of }s :)  Perhaps a js version of php's print_r (here is an example) of a valid node object from node_load() would help out?


You could use Search Api  Module

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine. For site
  administrators, it is a great alternative to other search solutions,
  since it already incorporates facetting support and the ability to use
  the Views module for displaying search results, filters, etc. Also,
  with the Apache Solr integration, a high-performance search engine is
  available for this module.

Using It you could create index for the field you choose!!


Re-authenticate a user with X-CSRF-Token

Rasjaad, You can use android account manager https://developer.android.com/reference/android/accounts/AccountManager for this purpose

Here is a sample Drupal 8 Android app code that uses account manager to reauthenticate. https://github.com/onedrupal/One-Drupal-Android

https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityAuthentication.java
At the launch of the activity AccountManager.getAuthTokenByFeatures is called

mAccountManager.getAuthTokenByFeatures(AccountUtils.ACCOUNT_TYPE, AccountUtils.AUTH_TOKEN_TYPE, null, this, null, null, new ActivityAuthentication.GetAuthTokenCallback(), null);

Here is the AccountAuthenticator  https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/authenticator/AccountAuthenticator.java

authToken = AccountUtils.mServerAuthenticator.signIn(site_protocol+site_domain, account.name, password);


How much data is ok to put in the global $user object or $_SESSION variables?

It's hard to put a limit on things like this. But if you have more than a few pieces of data related to the user, you should probably put it in a table of it own. You can add the data to the user when loaded, and the performance hit will only be a few ms, not measurable really. You will make things easier on yourself by being able to query the data instead of having it stored as serialized data.

One thing to note about $_SESSION is that it should only be used for storing temporary data. A use case could be storing the values entered in a form, to let the user pick up from where he left, if he moves away from the form and comes back later.


You can just return an empty string with your custom token.

Or you could make your custom token return the title and course code and handle it that way.


Make sure that:

theme('links__system_main_menu', ... is actually used to output the menu.
There are no issues with your code.
Caches have been cleared after adding the function (admin/config/development/performance).

To better understand what system_main_menu is all about check keithm's answer here. The main part of the explanation is this:

  links__system_main_menu is a theme hook pattern of the form [base
  hook]__[context]. When links are themed with
  theme('links__system_main_menu', $vars), theme() will search for
  and use theme_links__system_main_menu() if it has been defined. If
  not, it will use theme_links().

Official documentation about it can be found here.