Ubercart change product image thumbnail in cart view to a different field

One option would be to use form_alter hook to change the display.


You can try using system_settings_form which is simple way of storing settings in Drupal..

function registration_pdf_form($form, &$form_state) {
   $form['registration_body_twoside'] = array(
        '#type' => 'text_format',
        '#title' => t('Two-sided PDF'),
        '#default_value' => variable_get('registration_body_twoside', ''),
    );
    $form['registration_body_threeside'] = array(
        '#type' => 'text_format',
        '#title' => t('Three-sided PDF'),
        '#default_value' => variable_get('registration_body_threeside', ''),
    );
  return system_settings_form($form);
}

you can read values using

$twoside = variable_get('registration_body_twoside', '');
$threeside = variable_get('registration_body_threeside', '');


add js by #attached - hook_page_alter in theme's template.php

I think your problem is you're trying to use a hook from a theme template.php? (Assuming because you have mytheme_page_alter as your function name for hook_page_alter). If you're not getting the JS included, it's specifically because you can't use hooks in template.php files. You need to create a new module.


Is Drupal Console aimed to replace Drush?

Drupal console is a Drupal CLI tool, from the-ground-up, that leverages Symfony CLI components and modern PHP OOP design practices. Drush is a venerable Drupal CLI tool that has been around since Drupal 4.7, thus built with an older design practice. However, since Drush 9 it's been rearchitected to use the Symfony components as well.

There is overlap based on both projects being a general purpose Drupal administration CLI tool. Drush has more features, due to its age, but Drupal Console has some new features due to its more modern design.

In a commercial software world, there would be some profit motive to merge/buy-mind-share/etc. However, in the open source world they both stand as their own independent projects, with its maintainers motivated for other reasons than to build the one true Drupal CLI tool to bind them all (tm).

It might help to read Ten things you need to know about Drupal Console coming from Ray Saltini of FFW (the company supporting the lead developer Jesus Olivas of Drupal Console), & Drush and the Drupal Console with Drupal 8 from Greg Anderson (one of the maintainers of Drush).

To explicitly answer the question, maybe. If you're wondering which should I use?, the answer is maybe both for the time being. Perhaps Drupal Console will eclipse Drush, but right now both have useful feature sets for administering your Drupal site.


Config entity form field with multiple/unlimited cardinality

(Content) fields have cardinality. There is no such concept for form elements.

However, entity_autcomplete does have a #tags flag, which you can see in the getInfo() method of the class: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Element%21EntityAutocomplete.php/function/EntityAutocomplete%3A%3AgetInfo/8.

If you set that to TRUE, then it allows you to select a comma-separated list of references.

If you're looking for the "Add another" functionality of entity_autocomplete or any other form element, then you have to build it yourself.


Correct views hook to alter contextual filter

I was able to use achieved what I wanted by using hook_views_pre_build() as below
hook_views_pre_build(ViewExecutable $view) {
  $args[0] = '1234';

  $view->addArguments($args);
}


Views is the standard option for achieving your goal.  Check out this video series to learn more


Getting total vote results for several nodes in a view (Drupal 7, Views 3)

Create a view:

Use Agregation.
Use fields.

Add fields in this order remove everything else:

Taxonomy or (Category) as you call it. (Aggregation settings = Group results).
field_rating (or your five star field). (Aggregation settings = Average).

Filters.

Published (YES).
Content type = (restaurants).

What you need to do in resume, is to call all the nodes of type "restaurants" group the results the taxonomy field by Aggregation and AVERAGE all the ratings.


Someone (or something) is trying to submit a value for field_item_type_tid that isn't in the list of allowed options for that field (as prepared by the form API prior to rendering the form/element).

The FAPI is objecting to that attempt (as it should; it's a security feature), so the user will receive the standard "Illegal choice" error message.

It might be an attempt at a hack, it might be something weird instigated by a user/browser extension, or it might be the result of some javascript trying to change the allowed values on the client-side, without informing the backend that the options need to change.

Without analysing the page and all the involved parameters it's only speculation, though. It might be being caused by any of the above, or perhaps some other external factor.


Drupal 7 module recommendations for mailman listserv?

you can try http://www.drupal.org/project/simplenews .. i personally use mailchimp with the drupal mail chimp module drupal.


How to extend (alter) webform submit function to add more funcitionality?

Just append your function to the #submit element to add it to the list of handlers.

MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'webform_client_form_1') {
    $form['#submit'][] = 'webform_client_form_submit';
  }
}


Go to the sites/default directory. Open up to the setting.php file. Around line 500 uncomment this drupal_fast_404(); by removing #

Source


Display unique text and button in nodes in a view in drupal 7

Not quite sure if there's a module for that. Is Flags enough? In basic, it has a 0 or 1 option: respond and already attending.

And how to distinct users? I presume, users are logged in. Add a role to give certain users the privelege to see the RSVP-button/block/whatever.


Entity Reference View Widget problem with add selective

I solved a very similar issue by changing the display type to "Entity Reference" (not "Entity Reference View Widget") and using using the ER Widget only for the view checkbox selection field.

Here is a detailed step-by-step guide to a solution which worked for me using the latest Drupal 7 dev version of the ER Widget module.


"Add link" attempt for a Menu yields 500 error

Change MYSQL max_allow_packet_size.

Incase you are on MAMP you can add --max_allowed_packet=32M to /Applications/mamp/bin/startMysql.sh and restart MAMP.


What is the order of page load in Drupal?

With regard to error pages, Drupal has its defaults, but you can create your own just like any other node.  Just create a page for the error, then go to yoursitename.com/admin/settings/error-reporting and specify it as the page to display. You can do this for 403 and 404 errors.

The error pages are loaded just like any other. Which theme files are loaded depends highly on the theme. In Drupal 6, page.tpl.php is the top-level template file in the theme, and would be used for error pages just like any other page. However, it is quite possible to have other files that only theme certain portions of the page.

I would highly recommend a slow, methodical reading of Drupal's theming guide for an introduction. This will help you understand how Drupal decides which .tpl.php files (as well as CSS, JS, etc.) to use for a given page request.

Also, note that a lot of the details have changed significantly between Drupal 6 and Drupal 7. If you're doing new development, you'd probably be better off focusing on version 7—but of course if you have older sites to maintain, you'll need to look at the relevant documentation.


Getting fields of a content type in template file - creating a slideshow

If I understand well your question, I guess that node.tpl.php is more suitable for use templates per content types an control over individual fields:

page.tpl.php: Default theme implementation to display a single Drupal page.

node.tpl.php: Default theme implementation to display a node.

About how to name your templates according your needs, see this documentation: Drupal 7 Template Suggestions http://drupal.org/node/1089656. Regarding your case, I guess, a template for content type, the name could be node--slideshow.tpl.php. see this answer that have information related with node.tpl.php.

and about how to see your fields, the same link to the answer have one example:

I have a field called field_demotext1, then this is the way that I can use to call their respective value inside any custom html zone of a node layout:

print $content['field_demotext1']['#items'][0]['value'];

whit print_r($content); (or dsm($content); if you use Devel module) you will see fields that can be pulled. this screenshot is using dsm($content); related with the example;

Render Drupal API is an alternative to the previous way. In this way you does not need seek the file using dsm() or print_r()

print render($content['field_demotext1']);

Also, seems that field_view_field is another alternative to render Drupal fields. see this related document:

I hope information be useful.


Additional file entity fields in widget_form

You have to add it to the field type, not entity type.  Extend FileItem and override propertyDefinitions() to add it to the field properties. Like the description you've mentioned was added by FileItem extending EntityReferenceItem:

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['display'] = DataDefinition::create('boolean')
      ->setLabel(t('Display'))
      ->setDescription(t('Flag to control whether this file should be displayed when viewing content'));

    $properties['description'] = DataDefinition::create('string')
      ->setLabel(t('Description'));

    return $properties;
  }


Getting nodes related to a taxonomy term selecting from a drop down into another drop down

Yes, you need to implement this using hook_form_alter() and #ajax. The following is an example code you could try. The field field_category and the table field_data_field_category would be your taxonomy field. The field_nodes would be your another drop-down where you want to list the selected nodes related to the selected taxonomy.

The example code would sort the nodes by content types. To sort price of each particular content type, you would need to join another table in the query, for example, field_data_field_price and add your price field to the order-by clause. HTH.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if( $form_id == 'your_node_form' ){

        $form['field_category']['und']['#ajax'] = array(
            // #ajax has two required keys: callback and wrapper.
            // 'callback' is a function that will be called when this element changes.
            'callback' => '_mymodule_ajax_dropdown_alter',
            // 'wrapper' is the HTML id of the page element that will be replaced.
            'wrapper' => 'replace_field_div',
        );

        $form['field_nodes'] = array(
            '#type'     => 'select',
            '#title'    => t('Nodes'),
            '#options'  => array('' => '- Select -'),
            '#required' => FALSE,
            '#prefix'   => '
',
            '#suffix'   => '
'
        );

        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['field_category']) && $form_state['values']['field_category']['und'][0]['tid'] ){
            # when the respective taxonomy is selected, get the nodes related to the selected taxonomy
            $tid = $form_state['values']['field_category']['und'][0]['tid'];

            $query = db_select('node', 'n');
            $query->join('field_data_field_category', 'c', 'n.nid = c.entity_id');
            $query->condition('n.status', 1, '=')
                    ->condition('c.field_category_tid', $tid)
                    ->fields('n', array('nid', 'title'))
                    ->orderBy('n.type', 'ASC');
            $result = $query->execute();
            foreach($result as $row){
                $form['field_nodes']['#options'][$row->nid] = $row->title;
            }
        }else{
            # No taxonomy selected
            $form['field_nodes']['#options'] = array('' => '- Select -');
        }
    }
}

function _mymodule_ajax_dropdown_alter($form, $form_state){
    return $form['field_nodes'];
}


Display twitter tweets for own account in drupal 6

The easiest way is definitely to install the Twitter module that you have already discovered. I used to do this on my website as a way of pulling in tweets to my blog. You will only need the read-only configuration for the module, and you may find it easiest to use the Views integration.

If you'd rather code your own, the QueryPath module allows you to write jQuery-like requests directly against Twitter's API, but you'll have to write your own module. (You can start with the sample modules that come with QueryPath).


How to get rid of the '-' sign before sub taxonomy term?

In Drupal 6, the function that outputs the list of taxonomy terms is _taxonomy_term_select(), which contains the following code.

  if ($tree) {
    foreach ($tree as $term) {
      if (!in_array($term->tid, $exclude)) {
        $choice = new stdClass();
        $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
        $options[] = $choice;
      }
    }
  }

  return array(
    '#type' => 'select',
    '#title' => $title,
    '#default_value' => $value,
    '#options' => $options,
    '#description' => $description,
    '#multiple' => $multiple,
    '#size' => $multiple ? min(9, count($options)) : 0,
    '#weight' => -15,
    '#theme' => 'taxonomy_term_select',
  );

Since it uses theme_taxonomy_term_select(), overriding that theme function is possible to remove those hyphens added at the beginning of the term name.

In Drupal 7, that code is contained in taxonomy_allowed_values().

  $options = array();
  foreach ($field['settings']['allowed_values'] as $tree) {
    if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
      if ($terms = taxonomy_get_tree($vocabulary->vid, $tree['parent'])) {
        foreach ($terms as $term) {
          $options[$term->tid] = str_repeat('-', $term->depth) . $term->name;
        }
      }
    }
  }

Unfortunately, the function calling it (options_field_widget_form()) uses a theme function used for every form element (including the ones not associated with taxonomy terms), for example theme_select().

  switch ($type) {
    case 'select':
      $element += array(
        '#type' => 'select',
        '#default_value' => $default_value,

        // Do not display a 'multiple' select box if there is only one option.
        '#multiple' => $multiple && count($options) > 1,
        '#options' => $options,
      );
      break;

    // …

  }

Fortunately, options_field_widget_form() uses some custom properties that allows to check if the select form element is being output for an entity. In fact, it uses the following code.

$entity_type = $element['#entity_type'];
$entity = $element['#entity'];

This is true also in the case the used form element is checkboxes, radios, or checkbox.
If $variables['element']['#entity_type'] passed to the theme function for the select form element is set, and it is equal to the entity type for the taxonomy terms, then the theme function can assume it is outputting the select element for a taxonomy term, and remove the hyphens at the beginning of the term name.


Implement Field API Pane Editor into Views

For editing single-field values in views, there's the editable fields module rather than FAPE. However, this edits a single row at a time, rather than bulk updating all nodes or entities in the view at the same time.


How to migrate tables in nodes from D6 to D7, created with the tablefield module

Tablefield does not currently include migration support - there is a patch to add it at https://www.drupal.org/node/2317245. If you try out the patch and report on your results there, you may help move it forward.


Writing a migration from non a non Drupal site

It might not be the answer you are looking for, as it is not Migrate, but when I did this a couple years ago for a large client this is how I did it.

First, I set up the Feed Import module and a map of column names to desired fields.  Second, on the various non-drupal sites that I was migrating to a single drupal install I exported the data to csv files paying careful attention to the column aliases so they matched the map.  Also, as it totalled a lot of rows, I broke it into several files to run them in batches.  Using an anchored feed import, I was able to run them in batches and subsets of data, to purge and re-import any set as needed, and to group all the difficult international names together by sorting my csv files.

It took a day for every 10,000 nodes I imported.


How to conditionally not load js for anonymous users?

If you don't want to load your JS in anonymous user, check the user if its logged in then load the JS file if its true. use user_is_logged_in() to check if user is logged in, place it inside your hook_preprocess_page().

Example:

  $theme_path = drupal_get_path('theme', 'zen');
  // This will load only in authenticated user.
  if(user_is_logged_in()) {
    drupal_add_js($theme_path . '/plugins/jQuery/jquery-2.2.3.min.js');
  }


Other (related) nodes with the same taxonomy block grouping problem

I've used tags as the term field, so adjust for that.

Create the block view as follows:

A view of content (nodes).

Relationships:

Content: Tags (field_tags), require relationship  // you will use your term field here
Taxonomy term: Content using Tags (Relate each Content with a Tags set to the term.) and set the relationship to the first relationship added, and tick require this relationship // yours will be named differently

Contextual filters:

Content: Nid (node id). Set the relationship to the second relationship added. Provide a default value of Content ID from URL for WHEN THE FILTER VALUE IS NOT AVAILABLE. Specify a validation criteria of Content -> your content type -> Node ID -> Hide view
Content: Nid (node ID). DO NOT USE A RELATIONSHIP. Provide a default value of Content ID from URL for WHEN THE FILTER VALUE IS NOT AVAILABLE. Specify a validation criteria of Content -> your content type -> Node ID -> Hide view. Click on more and tick Exclude.

Fields:

Content Title (NO relationship)
Taxonomy term: Name, use relationship 1, and hide from display

Sort Criteria

Taxonomy term: Name, use relationship 1, ascending
Content Title, ascending

Filter Criteria

Add a filter of Content (node) type to filter on your content type.

Format:

Unformatted list, with settings: Grouping field Nr.1 set to the term field (field 2)


How to allow an OG group admin to create and add a user to a group?

I found a round about way. I made my own form with two values and a user_access('administer group') check. The first value is the group id and the second is the user name.

In the myform_form_submit(), if the user name exists in the users table, I run og_group to subscribe that user. If the username does not exists and the user has not logged in, I add them to a queue as a key value pair of username and group id.

When the user logs in, hook_user_login() searches through that queue to find any instance and if so, subscribes them to that group.


I don't see anything in Database or DatabaseConnection specifically. In a pinch you can just run a query that you know won't throw an exception in a Drupal site:

try {
  db_set_active('mymoduleDB');
  db_query('SELECT COUNT(nid) FROM {node}');
}
catch (\PDOException $e) {
  // Berate the user.
}
// PHP5.5+ only
finally {
  db_set_active('default');
}


Views Slideshow, white backround when hover

As Sohail mentioned, it's really hard to figure this out for you without being able to view the actual web page. It's most definitely a CSS issue and is just a matter of finding the right selector. Can you just use Inspector in Chrome to find the selector that encompasses that area, and then search within the stylesheet it says it's using for that selector with hover? Perhaps just search the stylesheet for #fff to see where white is being used and then see where it is making that area white?


What is the easiest way to export Field settings into a .install file?

There are some useful resources on how to do this. And you dont have to use Features.

Exporting and creating field definitions in Drupal 7 blogpost by Joel Stein
Drupal 7 export content type and fields blogpost by Kristian Nissen

Features is great if you understand what it's doing (calling Field API in an automated fashion and exporting definitions). You can use the Field API to define, create instances, attach fields to entities -- and then remove them all module uninistall as you need.

The easiest way for me to do this is look at the functions in the link above and use var_dump() on $field or its $settings after you make it using the Field UI. Then just use the appropriate Field API call like field_create_instance() to wire these var_dump'd arrays into your modules hook_install(). So i'm saying dont create the arrays by hand, create them in Drupal and just copy an export to your code ...


The mapping information is stored in the fb_user table in the database.

I'm not aware of any API functions the module provides for querying this data but I wouldn't be surprised if something exists.

If all you are doing is authentication I'd have a look at FBOauth module instead, it provides a similar table and makes the whole process a lot easier.


How do I include a Javascript Library from a Twig Extension in Drupal 8?

Partial Answer that works

... but I don't like it because the list of paths in the config never gets reset.  I think I need to figure out how to do Cache Contexts for a proper answer.

In my modules/custom/MY_MODULE/src/TwigExtension.php file:

class TwigExtension extends \Twig_Extension
{
   const CONFIG_KEY_NAME = 'MY_CONFIG_NAME';
...
    public function MY_MODULEWidget($MY_VARIABLE)
    {
        /* @var $config Drupal\Core\Config\Config */
        $config = $this->configFactory->getEditable($this->getName() . '.settings');

        $paths = (array)$config->get(self::CONFIG_KEY_NAME);

        /* @var $currentPath string */
        $currentPath = \Drupal::service('path.current')->getPath();        // returns '/node/47446' not the alias

        if (in_array($currentPath, $paths)) {
            // Good
        } else {
            // Add $currentPath to config
            $paths[] = $currentPath;
            $config->set(self::CONFIG_KEY_NAME, $paths)->save();
        }

        return array(
                '#type' => 'inline_template',
                '#template' => '
Loading Widget ...
',
                '#context' => array(
                    'MY_VARIABLE' => $MY_VARIABLE,
                    ),
                );
    }
}

The above code will add the current path to a config.  Unknown if there's an upper limit to the size of the data in the config; however, in my implementation the number of pages that this is on will be small (< 100).

Then once the path is added to the module's config setting then we read it to conditionally add a library like this using hook_page_bottom() like this in my modules/custom/MY_MODULE/MY_MODULE.module file:

/**
 * Implements hook_page_bottom
 */
function MY_MODULE_page_bottom(array &$page_bottom)
{
    /* @var $paths array of strings */
    $paths = (array)\Drupal::config('MY_MODULE.settings')->get(Drupal\MY_MODULE\TwigExtension::CONFIG_KEY_NAME);

    /* @var $currentPath string */
    $currentPath = \Drupal::service('path.current')->getPath();     // like '/node/47446', not the Alias

    if (in_array($currentPath, $paths)) {
        // Include the library that will modify jQuery(".MY_CLASS")
       $page_bottom['MY_MODULE']['#attached']['library'][] = 'MY_MODULE/my-twig-extension';
    }

}

EDIT 0

Added a hook_build() to my module like this so I could clear the setting manually:

function MY_MODULE_rebuild()
{
    /* @var $config Drupal\Core\Config\Config */
    $config = \Drupal::service('config.factory')->getEditable('MY_MODULE.settings');

    $config->clear(Drupal\MY_MODULE\TwigExtension::CONFIG_KEY_NAME);

    $config->save();

}

Note: $config support fluid interface (e.g. $config->clear(...).

I will still not accept my answer because I still believe I should be using Cache Context for this.


How to pass a variable $ _ GET in a page?

Try the following code:

    $items['candidate/%user'] = array(
      'title'            => t('My candidate space'),
      'page callback'    => 'cel_configuration_custom_page',
      'page arguments'   => array(1),
      'access arguments' => array('access user profiles'),
    );

    function cel_configuration_custom_page($account){
      return 'Custom page for ' . $account->name;
    }

You can't use %candidate as an argument for user accounts. Also, if you want to restrict access by a particular permission, don't set access callback to TRUE as that will grant access to everyone.


Permission denied (publickey,password).

This means the issue isn't with Drush, it's that the server that matches up to your @dev alias doesn't have your SSH public key set up to allow you access. Either your public key hasn't been added to the ~/.ssh/authorized_keys file or the permissions on that file (or the ~/.ssh/ directory) have the wrong settings.


I have found the solution.

You need to add these 3 lines of code to the page where the link Open modal is displaying.

ctools_include('ajax');
ctools_include('modal');
ctools_modal_add_js();


How to see override functions and template files in use for any part of the drupal site?

You are thinking about the Theme Developer module.  When you install and enable, it you can click on just about any properly rendered element and see

Preprocess and process function candidates
Theme function candidates
Template file suggestions

Just keep in mind that it can interfere with some themes, and doesn't work well in some versions of IE.


I decided to use gmap module as it provides widget to change Display format for my geofield.


Local json migration: how to set the value of the urls variable?

The data fetcher plugin can't find your JSON file because the format is wrong. The plugin is expecting Drupal's URI format (e.g. public://path/to/data.json or private://path/to/data.json) under its private/public file dir. For example, see the included example migration with the module:

  # The data_parser normally limits the fields passed on to the source plugin
  # to fields configured to be used as part of the migration. To support more
  # dynamic migrations, the JSON data parser supports including the original
  # data for the current row. Simply include the 'include_raw_data' flag set
  # to `true` to enable this. This option is disabled by default to minimize
  # memory footprint for migrations that do not need this capability.
  # include_raw_data: true
  # Flags whether to track changes to incoming data. If TRUE, we will maintain
  # hashed source rows to determine whether incoming data has changed.
  # track_changes: true
  # Copy the example JSON file in artifacts folder to sites/default/files folder.
  urls:
    - 'public://migrate_json_example/products.json'


Drupal.settings.basePath is not giving the base_url in js

You need to pass it manually like this.

global $base_url;
drupal_add_js(array('baseUrl' => $base_url), 'setting');

Then call like this Drupal.settings.baseUrl.

Drupal.settings.basePath value is coming from base_path() api. See this documentation about base_path.


Why is the jquery_update module not supporting the latest jQuery version?

You'll want to use the latest dev version of jQuery update, 7.x-3.x-dev to get the latest version of jQuery, or at least jQuery 3.1.  See this drupal issue for more insight.

You can see in the 7.x-3.x dev branch, it has jQuery 3.1.

Note, there is also a patch for jQuery 3.2, 3.3, and 3.4 against the 7.x-2.7 branch.


Why is this method not recommended?

The function comments do give a nod to the reason:

  Instead of directly deleting a file, it is strongly recommended to delete file usages instead. That will automatically mark the file as temporary and remove it during cleanup.

But perhaps the "file usage" part of that could have been expanded upon, if you're not aware there's proper reference tracking going on it could be confusing...

Put simply, multiple entities/things can reference a single file. Those references are stored as file usage records, which are consulted when the system wants to know if it's safe to delete a file. If a record exists, for the target file, it can't be deleted without breaking a link, so the system doesn't do it.

Rather than go through that process of checking usage then deleting every time a file is dereferenced, the system batches it up on a cron job for convenience.

If it's not convenient for your use case, and you are comfortable that the file delete is 'safe' with the above in mind, then you can happily ignore the recommendation and use file_delete directly.

If you do, make sure you clear up the file usage records at the same time, or you might end up with inconsistent data some time down the line.


What can I use for something like Google web analytics for a Drupal website?

Drupal have the Google Analytics too

  Adds the Google Analytics web statistics tracking system to your
  website.

also install the Google Analytics Reports module to track within the site itself.

  Google Analytics Reports provides graphical reporting of your site's
  tracking data. Graphical reports include a dashboard widget for
  admins, a small path-based report in blocks, and a full path-based
  report.


How to call a drupal custom module function from a basic page?

I guess you want to create a menu callback which will call your form right?
Here is how to-

Create your menu hook like bellow:

function mymodule_menu($node) {
  $items['my-frm'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_form'),
    'access callback' => TRUE,
  );
  return $items;
}

Than create your form like below:

function my_form() {
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

And after that here is your form submit:

function my_form_submit() {
  drupal_set_message("Hello World my form submit hook is called here");
}

Do a clear cache and navigate to yoursite/my-frm link you should see your form.


How can add Contact-Us-form in custom place of page.html.twig file?

You can do this in four steps:

Build a contact form.
Put this contact form in a block with Contact Block.
In block layout put the block in a region -> myregion.
Place the region in page.html.twig -> {{ page.myregion }}


Alter the exposed filters of a view, based on the view result

Since this has gone unanswered, I decided to get creative and it's very easy with Entity Reference, Views Reference Filter and optional Rules.

Add an entity reference field to the content type that will reference its own node. So node/5's field will reference node/5. This can be done with Rules
automatically. Old nodes can be updated with VBO if needed.
In your view, Add > Entity Reference with the exact same filters
etc. That should be automatic. Remove unwanted fields. Save the view.
Go back to your regular view, add an exposed filter (only for that pane) for the entity reference field we just created with (reference filter) written beside it.
In the exposed filter's settings, choose the Entity Reference view we just created. If it's just using contextual filters, don't worry about sending arguments.

The logic: The view will process the entity reference view first and provide its results to the first view as an exposed filter. I just tested it and it works perfectly. Takes about five minutes.


Block in Utility menu top only shows on home page

Please tell us about the view you have defined. What is the path, the filters, etc that have been included. The pages your view shows on are dependent upon the address or block settings you have defined for the view.


Using content type fields within page.html.twig

In the preprocess_page set up the variable

if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
 $variables['bg_color'] = $node->field_header_color->value;

}
     and use this in ur twig file

<header id="header" class="header" role="banner" aria-label="{{ 'Site header'|t }}" style='background-color:{{bg_color}}'>


How to create a view block of one content type filtered by author?

I eventually got this to work by using a page view with a path /reading-list/% rather than trying to make it work through panels.


Redirect to custom URL while logging in user through Webform

Another current question here inspired me for this short solution within your hook_webform_submission_insert():

 // Create user account.
 $my_user = user_save(NULL, $user_data);
 // Whether the user account was created successfully.
 if (!empty($my_user->uid)) {
   global $user;
   $user = $my_user;
   user_login_finalize($user_data);
   // Do the redirect here.
   drupal_goto('target_uri');
 }
 else {
   // User account could not be created. So do some error handling.
 }


Customize Flag Ajax Message on Rules Trigger

Rules don't support siuch feature. Change "Link type" to Normal link or Confirmation form, so you will got drupal messages from Rules.


How to auto-insert a sequence number in a Webform?

There is a module for this: Webform Serial number:
https://drupal.org/project/webform_serial

  This module provides an auto-incrementing number field for webforms.


Display a view block with a list of content excluding the one currently displayed on the page

Considering the first option, it is simple :

add a contextual filter of type "ID: Content" with the following configuration :

WHEN THE FILTER VALUE IS NOT AVAILABLE > provide a default value > content id from url
Go all the way down in the "more" section, expand it and check "exclude".
Then click apply
And save the views

That's it !


Can I show the answers to a previous round of questions in webform?

Your question is not completely clear, but as I understand you want to load a custom set of dropdown options as a webform element.

You can do that from a custom module with the following example code:

/**
 * Implements hook_webform_select_options_info().
 *
 * Defines a custom dropdown form element to be used with the Webform module.
 */
function YOURMODULE_webform_select_options_info() {
  $items['last_time_answered'] = array(
    'title' => t('Last time you answered'),
    'options callback' => '_YOURMODULE_get_options',
  );
  return $items;
}

/**
 * Generate "Last time answered" options for the current user.
 *
 * Used for sample webform element.
 */
function _YOURMODULE_get_options() {
  // Your query goes here
  // Return should be an array with $value => $label structure.
  return array(
    1 => 'Option 1',
    2 => 'Option 2',
    3 => 'Option 3',
  );
}

I also suggest to drop in a custom validator to the webform:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {
    // Sample webform custom validation
    case 'webform_client_form_1':
      $form['#validate'][] = '_YOURMODULE_validate_custom_field';
      $first = array_shift($form['#submit']);
      array_unshift($form['#submit'], $first, '_YOURMODULE_validate_custom_field');
      break;
  }

}

/**
 * Custom validation function for webform component.
 */
function _YOURMODULE_validate_custom_field() {
  foreach ($form['#node']->webform['components'] as $element_id => $element) {

    if ($element['form_key'] == 'last_time_answered') {

      // Perform the check here
      if ($element['value'] != 'Sample value') {
        form_set_error('', t('Validation message.'));
      }

    }

  }
}

To use this custom field, create a new webform element (select options) and choose your new list from the "Load a pre-built option list" dropdown.


Create node and photo gallery during installation of Drupal 6

The short answer: Yes!

You would need to use an installation profile for this.  With an install profile you can enable and configure modules, create new content types, add content, etc.

Here's one place to start:  http://drupal.org/node/1089736


So your solution hacks the module code. Do the community a favour and submit your change to the issue cue for the module so that everyone can share in your success or even better roll a patch for the authour to apply to the module code.


How to set different paths to different images on the same views block

Ok, so here is a step by step "how to manage this" ;)

Step 1: be sure to have the content type for your images containing a field "link", where you can add the link to your specific page section.

Step 2: Add some content with image and URL to page section (e.g: node/13)

Step 3: Make sure you have some nodes like this:

Step 4: Create a new view for the block you want to fill with your content-type:

Step 5: Add the fields you want to show to the view: (here: the field for the image and the field for the link). If the link should be shown seperate from the image as well, you'll have to add the field for the link twice, because we'll "pass over" one link to the image)

Step 6: Now re-arrange the fields so that the order is the following. This is important, because the image field will hold a replacement pattern of the above Link field (which is excluded from display, because we don't want the link to show up, we only need its data).

Step 7: Now configure the first image field "excluded (mylink)" so that it is excluded from display and rewrites the output of the field with the replacement pattern for the "Raw url" value:

Step 8: Now configure the image field like this. Mark "Output this field as a link" and use the replacement pattern for the above link field "[field_mylink]".

That's it. Now you have a view that pulls the URL from the content type and puts it on the image of it.


D8 Install/uninstall custom module - 'field_storage_config' entity with ID already exists

Try putting the files in the config/optional directory either at first install or after uninstalling (because they will already exist). They should get installed even on first install if all dependencies are met. From the docs:

    For example, in the scenario that module A has optional configuration which requires module B, but module A is installed first and module B some time later, then module A's config/optional directory will be scanned at that time for newly met dependencies, and the configuration will be installed then. If module B is never installed, the optional configuration item will not be installed either.

https://www.drupal.org/docs/8/api/configuration-api/configuration-storage-in-drupal-8


The format of the pager header can be modified on the date view configuration page admin/config/regional/date-time/date-views. On that page, find the format that you wish to update, in your case Date views day format with year, which by default is l, F j, Y.

Update that value to be F j, Y, since l returns the weekday, and your date will show as you need it.


I would recommend you to have a look on the Display Suite module. This module allows you to add different view modes (displays) for your content. These view modes can then be used in several places. Beside that, the display suite module offers a lot of other very handy features to deal with any entity in your system and how they are displayed.


It sounds like you've got some pretty serious problems here.

The fact that you can't use PHPMyAdmin because of the session.save_path setting (which is in php.ini by the way, it's not file name) would suggest that something on your server has changed. At a guess I'd say your web server no longer has write access to the session folder, but without seeing the full error message it's hard to say.

The fact that the you can't enable the db log module is also quite worrying. That module defines the watchdog table upon install so the fact that it's missing might suggest Drupal is having problems creating database tables.

The best advice I can give is to get a local version of the site up and running, with permissions for files/databases set up in a way you know is correct, and see if you still have problems.

If you do, then you know that the problem is somewhere else and you should start methodically disabling and uninstalling modules until you can narrow down the culprit.

If you don't, then you know the problem is with the live server configuration.


You could use Homebox and redirect the user to their individual dashboard on login (possibly using LoginToboggan or Rules).  I've used it before and it's pretty neat.

Following that, you just create views to display your tickets/issues/tasks etc and display them in the homebox.


How to only display Second level of menus in Superfish?

Hit 'configure block' on your superfish menu block. Under 'Menu depth' make your desired changes. This sets number of child levels starting with the parent selected above. -1 means all of them, 0 means none of them. (Default: -1)


What kind of content ends up in the "System help" block? How could I answer this question myself?

Help content, defined in hook_help is added to the "System help" block for display in

system_block_view

via

menu_get_active_help

which returns the valid help content for the current menu path.

  How could I answer this question myself?

You can answer this question yourself by

Studying the Drupal API
Grepping / searching the codebase for relevant text
Asking on Drupal Answers ;)


How do I set a dynamic variable in the menu links yml file for route_parameters?

Create a second route that has no user parameter and when accessed redirects to the first route with the current user parameter inserted.


Create a general rewrite rule in .htaccess

I think your rewrite collides with the other rewrites in drupal standard .htaccess. Try a redirect. The redirect will be executed right away and the rest of .htaccess will no longer be processed. And it will also tell search engines that the url has changed.

RewriteRule reading_(.*).html reading/$1 [L,R=301]


What's the default expiration time for block caches?

Nothing special here. It's the same as on your admin/config/development/performance page. Module Block Cache Alter just alters 'cache' key for block and does not interfere with the mechanism of caching in Drupal.

Example 1:
Minimum cache lifetime: none,
Cron: every day,
Block cache will be flushed every day or if someone flush cache manually.
On node or comment submit: the whole block cache will be flushed.

In Example 1 the whole block and page cache will be flushed immediately on every new comment, node, vote submit because of Minimum cache lifetime: none. See where cache_clear_all() is called.

Example 2:
Minimum cache lifetime: 12 hours,
Cron: every 6 hours,
Block cache will be flushed every 12 hours or if someone flush cache manually.
On node or comment submit: only block cache older than 12 hours will be flushed.

Block and page cache items which are older than 12 hours will be flushed immediately on every new comment, node, vote submit. See where cache_clear_all() is called.

Cron period is important because Drupal tries to flush caches on every cron run.

This behaviour can be changed with Cache Expiration module.


My solution was to patch the search api db implementation.

This looks to see whether the field is a one-to-many relationship; if it is, then the table is added for each condition. I presume that this is so that these matches can then be counted and add towards the relevance score. However, for access restriction we're only interested in a single match, and (presumably) shouldn't add this to the score anyway. Therefore for this case there is no need to add a join for each possibility.

The patch below looks for this use case and ensures the user access table is only joined once.

--- a/sites/all/modules/search_api_db/service.inc
+++ b/sites/all/modules/search_api_db/service.inc
@@ -1028,7 +1028,12 @@ class SearchApiDbService extends SearchApiAbstractService {
           $cond->condition('t.item_id', $query, $f[2] == '<>' || $f[2] == '!=' ? 'NOT IN' : 'IN');
         }
         else {
-          $alias = $this->getTableAlias($fields[$f[0]], $db_query, search_api_is_list_type($fields[$f[0]]['type']));
+          // the user access node table only needs joining once; we're not interested in
+          // scoring based on access; access is a boolean, so we do not need muliple joins
+          // which can break the query if there are more of them than the SQL engine allows joins
+          // (e.g. MySQL is limited to 64 joins).
+          $rejoin = search_api_is_list_type($fields[$f[0]]['type']) && ($f[0] != 'search_api_access_node');
+          $alias = $this->getTableAlias($fields[$f[0]], $db_query, $rejoin);
           $cond->condition($alias . '.value', $f[1], $f[2]);
         }
       }

EDIT: LOL - or as they did it...

+          $new_join = search_api_is_list_type($field['type'])
+              && ($filter->getConjunction() == 'AND'
+                  || empty($first_join[$f[0]]));
+          if ($new_join || empty($tables[$f[0]])) {
+            $tables[$f[0]] = $this->getTableAlias($field, $db_query, $new_join);
+            $first_join[$f[0]] = TRUE;
+          }
+          $cond->condition($tables[$f[0]] . '.' . $field['column'], $f[1], $f[2]);

Answer is: upgrade module to v7.x-1.0!


Is a mailchimp newsletter with an entity view in the content area possible?

So nope. But there is another way using simplenews and place the view in the template of the newsletter, and then use another smtp instead of Mailchimp, like Mailjet which now has a release on D8.


If you want to show only text, use '#markup' form element, with syntax like this:

$form['status'] = array(
  '#markup' => '<p>' . variable_get('status', t('Off')) . '</p>',
);


How to set page-specific CSS classes on the page callback build array?

#attributes is the correct property, but the problem is that $build itself is not actually an render element (unless make it one), it's just a collection of render elements.

To make it an actual render element, you have to set the #type property to for example 'container'. That is nothing more than a div with attributes that contains other elements. See When should the "container" form element be used? and theme_container().

You can however not affect the mentioned content div, that is outside of your control. Adding a container will add a new div inside that one.


I used a patch from an issue queue in drupal to sort me out on that one. I should say it works well for me. You can find it here


No need to reinvent the wheel: valid_email_address().


Count nodes that referenced current node in VIews

In the Advanced section of the view's configuration, there is a subsection Other. This subsection holds an item Use aggregation. Turn this item on. This allows you to configure the Aggregation settings for each field in the Fields section. One option is to use COUNT.

What remains is to navigate from the current node to the nodes that reference the current node. In Drupal 6, this could be done with the Reverse Node Reference module, which suggests the References module for Drupal 7. I think you have to add a Relationship then add a Node:Nid field that uses this relationship and is aggregated using COUNT.


Make sure you check the correct permissions for the roles you want in the "RESTful Web Services" section on the /admin/people/permissions page.


By default the output at taxonomy/term/% (with % being the term ID) is a collection of teasers for nodes to which the term ID is assigned.

You can alter the teaser display for each content type by going to Structure > Content types > [type] > Manage Display > Teaser. This is the simplest method, but note that this will alter the teaser display for the content type site-wide, not just on the taxonomy term results page.

If you want to alter the overall display of the results and you don't want to alter the teaser output everywhere else, @ShawnCohen's answer is your best bet. Views provides some powerful options for customizing a result set, including Relationships (mentioned by @Screenack in the comments).


How to force homepage to non-default language

At admin/config/system/site-information add your system path (node/1, node/2 or whatever) to Default front page field. (Don't ask why the "prompt" sometimes displays the language prefix, sometimes doesn't, I don't know.)

Language detection settings have no effect here, I think. At least when you have URL first.


You have to add cache tags of all entities you get data from. Add this line to the foreach loop:

$variables['#cache']['tags'][] = 'node:' . $schedule_entity->id();

The parent node is already tagged, which would also happen for the schedule entities if rendered normally.

This is all you need to do, adding the tags of the entities you use to build the rendered output. The entity system invalidates cache items, which are tagged correctly, automatically on all CRUD operations.


Need a more specific price calculation rule in Drupal Commerce

Depending on your multiplication factor (I suppose you want to give a discount), you might want to try Commerce discount which has support for discounts per order and discounts per product.

  Commerce Discount provides a new user interface for defining and
  managing product and order level discounts. Using just the core
  pricing system of Drupal Commerce requires knowledge of how to use the
  Rules UI, which is beyond the capabilities of most merchants.
  Additionally, the core system cannot support order level discounts or
  certain types of shipping / product discounts. This module addresses
  all of those things.

The role based discount condition is provided by Commerce discount extra.


In Views, how can I show users with one role before all other users?

It looks like it's not possible with one View (Sort By User Role, Sort By User Role:  A New Idea?) which does kinda suck.

One option is to make two Views, one that filters on the user role you want at the top, and then one that filters OUT the user role.

Another option (this one would probably be easier to maintain) would be to create a field on the user accounts called Weight (you could hide it with Field Permissions), and then use Rules to populate that field with a high number for your chosen role when a user is created or edited, then you should be able to sort on that field.  If you do this though don't forget to create a second rule to remove/change the value in that field if the role is removed form a user.

tl;dr

Create Weight field on users
When a user is created, fire off a rule that looks for a particular user role
If it finds it, put a number in the Weight field
Sort your view on the Weight field
Make an "opposite" rule to remove the Weight value on Role removal.
Profit


Create a user Programmatically in Drupal 6.22

Looks like you've included the bootstrap.inc but you haven't actually bootstrapped drupal.

Example:

require_once(includes/bootstrap.inc);
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Get link for same page in different language

It should work when using this function: https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation_node_get_translations/7

This will return all the translations of a given nid, when an ES translation is given you can print your l().


Drupal 7 Ajax Form, add elements dynamically to a fieldset

The problem was in the AJAX callback, and specifically the code line:

$task_key = (int) substr($name, strpos($name, "_") + 1);

The buttons are named add_todo_key, and the code above returns todo_key, and not the key.

It was solved simply by using strrpos, which find the position of the LAST occurrence of a substring, rather than strpos that finds the first.


Resize Image for more than one Image Size profile automatically

Image styles in Imagecache Actions should handle this for you. But as said above, it will do it on display, not on upload. It will scale/crop however you like (there are extra sub modules for this), and the styles will be sorted into folders by image style, but not rename them. But it will put them in folders like Thumb/MyImageName, Big/MyImageName, etc.

Imagecache actions does have a custom option, I'm not sure if it would let you rename the file:

  Custom Actions - Execute your own PHP/GD code in the middle of an
  imagecache generation process. Requires some familiarity with imageAPI
  internals.


How to on Multisite manage users over 1 site

LDAP, you should define in an external directory (openldap, AD or whatever) which website a user can access or not and define rules inside each website (mapping rôles/sites/ldap properties, more infos here).
From there, you can add SSO like CAS.


Getting first the terms starting with the string I am searching for

The Taxonomy Autocomplete Settings module has now a Drupal 7 version, and an official release (7.x-1.0).


How to validate a form without the user pressing submit?

Clientside Validation will do your job.

You may however have to modify a javascript a little bit by incorporating jQuery('input').blur(function(){ //invoke the clientside validation });


Need a solution to search by sales person based on unique territory

Found something that might help you Locator tutorial and use Location Map if you want to display the results in a map.


Display newly added form element at the bottom

Like KrishaWeb said you need to add a #weight attribute to your new element.

It would look like:

$form['priorities'] = array(
  ...
  '#weight' => 99,
  ...
);

You can also set weights on the other form elements so the form is explicitly in order.


You should look at Conditional Fields Module. Does exactly what you need.

You can also find nice tutorial here: CFM Tutorial


Create path alias programatically when node is created

Instead of using hook, Pathauto module should be used where you can define specific pattern how aliases are generated per content type (at /admin/config/search/path/patterns). In there you can use replacement patterns or code your own. It's much cleaner approach.

Otherwise you can try hook_node_presave($node) and change the alias directly:

$node->path['pathauto'] = 0; // Required only if Pathauto is enabled.
$node->path['alias'] = "foo/bar";

or use the path_save(&$path) function directly as below:

$path = array('source' => "node/$node->nid", 'alias' => 'foo/bar');
path_save($path);


How to grab a user's Fivestar voting value with Rules?

I finally found a solution for my problem. This is my exported rule:

{ "rules_new_vote" : {
    "LABEL" : New vote",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php", "radioactivity", "comment" ],
    "ON" : { "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "field_popularity" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "integer",
            "value" : {
              "select" : "comment:cid",
              "php" : { "code" : "$comment = comment_load($value);\r\n$vote = $comment-\u003Efield_stars[\u0027und\u0027][0][\u0027rating\u0027\r\nif ($vote == 20) {return -4;}\ r\nif ($vote == 40) {return 2;}\r\nif ($vote == 60) {return 3;}\r\nif ($vote == 80) {return 4;}\r\nif ($vote == 100) {return 5;}" }
            }
          },
          "PROVIDE" : { "variable_added" : { "rating" : "Rating" } }
        }
      },
      { "radioactivity_emit" : { "data" : [ "comment:node:field-popularity" ], "value" : [ "rating" ] } }
    ]
  }
}

The trick was to store the cid as a new variable and to use that value in the PHP evaluation (the proposed values in my code can be changed to your needs). I've no idea why this wasn't possible in an easier way via the UI, but maybe it's a bug in the Firestar module.


Clean URL pagination (rewrite ?page=parameter)

You should write a PathProcessor that implements:

Drupal\Core\PathProcessor\InboundPathProcessorInterface
Drupal\Core\PathProcessor\OutboundPathProcessorInterface

Example:

file: modules/custom/mymodule/src/PathProcessor/MymodulePathProcessor.php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;

class MymodulePathProcessor implements InboundPathProcessorInterface, OutboundPathProcessorInterface {

  public function processInbound($path, Request $request) {
    if (strpos($path, '/my-page-') !== 0) {
       return $path;
    }
    $page =  preg_replace("/^\/my-page-(\d+)/", '$1', $path);
      if (ctype_digit($page)) {
        \Drupal::request()->query->set('page', $page);
        return "/my-page";
    }
    else {
      \Drupal::request()->query->set('page', 0);
      return "/my-page";
    }
    return $path;
  }

  public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($path === '/my-page' && isset($options['query']['page'])) {
      $page = $options['query']['page'];
      unset($options['query']['page']);
      return '/my-page-' . $page;
    }
    return $path;
  }

}

file: modules/custom/mymodule/mymodule.services.yml

services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
    tags:
    - { name: path_processor_outbound}
    - { name: path_processor_inbound}

We also need to do a custom alteration to the pager. For the full pager the links are not created as the usual link render elements, so they don't go through the processOutboud, instead the twig file (classy/templates/navigation/pager.html.twig) uses a custom format. The next hook function does the adjustment.

file: modules/custom/mymodule/mymodule.module

/**
 * Implements hook_preprocess_HOOK().
 * Implements hook_preprocess_pager().
 *
 * @param $variables
 */
function mymodule_preprocess_pager(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  if ($current_path === '/my-page')
  foreach ($variables['items']['pages'] as &$page_link) {
    $page =  preg_replace("/^\?page=(\d+)/", '$1', $page_link['href']);
    $page_link['href'] = 'my-page-' . $page;
  }
}


rest namespace not recoginzed in custom REST API class

As indicated by the comment by @ssibal, I just had to remove the line and then manually add it back in. The second time it took fine, and my resource works now.


We tend to use:

print format_date(strtotime($node->field_date[0]['value']), 'custom', 'H:i');

Perhaps that would work in your situation?


Through some trial and error and some further digging, I figured it out. Here's what works:
URL: [entityform:field-file-upload:0:file:url]
Filename: [entityform:field-file-upload:0:file:name]
Upload date: [entityform:field-file-upload:0:file:timestamp:short]
Increment the 0 to return more files from the multi-value array of uploaded files.
Once I had the basic syntax, the Drupal List of Tokens page was particularly useful.


Grouping modules is allowed in Drupal, when the modules are not already modules. Because, the modules are registered in System table by the location of the module. So, Changing the folder structure will result in fatal errors.

If you would like to change the folder structure then you need to disable the modules and uninstall them. After that, you can re-enable them after changing the folder structure by grouping them.

Note: Make sure you won't lose any data when you un-install the custom modules. Take a backup of database and source code before doing any changes for safe side.


Transforming a Webform upload field into a single Attach button

I found these 2 tutorials, with this I can manipulate the upload field only with CSS, without touching the PHP code:

http://jsfiddle.net/gabrieleromanato/mxq9R/

http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/

With this, it creates the link based on an image as background that imitate the form of the button.

Thanks again to @Mołot for helping.


Sending webform submissions to email with csv export of submissions

As tenken wrote, Webform module has a function for that, namely webform_results_export

Do you really want a single line of CSV e-mailed when a form is submitted, rather than periodic downloads?  You could modify your e-mail template to print each value, comma, value, but it wouldn't be an attachment.  If you absolutely need an attachment some custom code and/or Rules is the way to go.


Sending mail to an adress specified in a node creation form with an CCK email field with Rules

As long as you have the Rules module and the Token module installed, it should be a pretty straightforward.

1) Create a rule that responds to the event "After saving new content"

2) Add an action to that rule "Send a mail to an arbitrary mail address" (from the System section)

3) Use a token for the Recipient field. As long as there is a CCK field for the email address, there will be a token provided for it. It will be listed in "Token replacement patterns."


Find out if you're viewing a taxonomy page

When a taxonomy page is rendered, the template file used is taxonomy-term.tpl.php that receives, among other variables, the $term variable, which contains the term object for the taxonomy term associated to those nodes.
Basing on the vocabulary that owns that taxonomy term, you can change the layout of the page.

If you want to find out in page.tpl.php the taxonomy term associated with the nodes shown in the page (where the page's URL is example.com/taxonomy/term/[tid]), then you can use the following code:

$term = menu_get_object('taxonomy_term', 2);

If the page's URL is not example.com/taxonomy/term/[tid], then the function returns FALSE. The code can also be executed in a preprocess function, such as hook_preprocess_page().


Undefined variable: _SESSION in template.php

Apparently the $_SESSION variable is not available on the login page (I don't know why, but probably to avoid conflicts with logged in users trying to log in again).

Try checking for it before you try to unset it:

function theme_preprocess_page(&$vars) {
    if (variable_get('maintenance_mode', 0) && isset($_SESSION['messages']['status'])) { //no maintenance mode message on front-end
      $message_count = count($_SESSION['messages']['status']);
      if($message_count > 1) {
        array_shift($_SESSION['messages']['status']);
      }
      else {
        unset($_SESSION['messages']['status']);
      }
    }
}


printing file entity fields in a node.tpl

You could do this in a variety of ways. One way: in template.php, invoke YOURTHEME_preproces_node(&$vars){}. Inside it, do:

if($vars['type' == 'YOUR_CONTENT_TYPE'){
   $wrapper = entity_metadata_wrapper("node", $vars["node"]);
   $file = $wrapper->YOUR_FILE_FIELD->value();
   ...
 }

The $file variable should now contain your file object (or an array of file objects). Debug that with print_r($file) (or, preferably, with xdebug or another debugger) and you can add variables the $vars array there with:

$vars['YOURVARIABLE'] = $file->YOURFIELD...

which will then be available in your template as $YOURVARIABLE.


How do I reset all user passwords to 123 with drush or SQL?

Yes, you can do this using Drush, with following steps (e.g.):

1.Generate a password hash using following command:

$ cd [/var/www/html/drupal7]
$ php scripts/password-hash.sh '123'

2.Now run following drush command:

$ drush sql-cli
mysql > UPDATE users SET `pass` = 'pasted_big_hash_from_above' WHERE uid > 1;

Update pasted_big_hash_from_above with password hash generated using php command in step #1.


showing an image field from solr index on custom solr search page

We managed to solve this with help from user Gaele Strootman.

There are three steps to solve this:
1) add the image to the solr index using a custom module
2) add the image field to your apache solr view
3) add a template file for the image field that displays the actual image

ad 1) create a custom module to add images to the solr index.

You only need two files, my_module.info and my_module.module. We name the image field ss_field_image_uri.

my.module.info:

name = Apache Solr Image
description = Add image field to the solr index so we can display images in search results
package = Apache Solr
core = 7.x

dependencies[] = apachesolr_search

my_module.module:

<?php
/**
 * Add field_image uri to apache solr index, so that we can later display image in search results or custom apache solr views page.
 * @see apachesolr.api.php
 */

function apachesolr_image_apachesolr_index_document_build($document, $node, $namespace) {
  if (isset($node->field_image['und']['0']['uri'])) $document->addField('ss_field_image_uri', $node->field_image['und']['0']['uri']);
}
?>

ad 2) add the image field to your apache solr view

First re-index solr so the images actually get indexed and show up. Then add the image field to your view.

ad 3)  add a template file for the image field that displays the actual image

This is the template we added. Since the field is called ss_field_image_uri the template name is: views-view-field--ss-field-image-uri.tpl.php. This is the code:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php
/**
 * For additional parameters see
 * http://api.drupal.org/api/drupal/modules!image!image.field.inc/function/theme_image_formatter/7
 */
?>
<?php $variables = array('item' => array('uri' => $row->{$field->field_alias})); ?>
<?php $variables['image_style'] = 'thumbnail'; ?>
<?php print theme_image_formatter($variables); ?>

Now clean your caches and the images should show up in your apache solr view. Note that you can change the image style in the code from 'thumbnail' to whatever image style you like.

Hope this helps anyone!


How to use an external jQuery plugin with Drupal's no-conflict jQuery

In Drupal 7, if you a certain that the external scripts are attempting to use "$" as an alias for jQuery, and you can't get the script author to patch their code, and you aren't loading any other JavaScript libraries, then in your template_preprocess_page, place the following drupal_add_js before the set of all drupal_add_js that reference external files. All scripts in the header region that use "$" as an alias will then refer to jQuery:

drupal_add_js('var $ = jQuery;', 'inline');

If your external javascript is added in another region, for example, the footer, then use something similar to the following instead:

drupal_add_js('var $ = jQuery;', array('type' => 'inline', 'scope' => 'footer'));


Why does my newsletter keep sending the same copy our time and time and time again?

The following issue in Simplenews Issue queue Issue #351379: Keeps sending newsletter provides a few troubleshooting options. It is usually created by an invalid email address (that has a dot at the end for example: email@hotmail.com.)

If you have an existing Newsletter that is still sending emails you can stop it in the simplenews_newsletter table, set the s_status to 2 (sent) and empty the simplenews_mail_spool table.


Override twig template file from classy theme

As discovered through the comments discussion the answer in this case is to place the template into the admin subtheme (not the default theme).

When adding new templates to your subtheme it's important to be aware of the fact that there are usually two active themes in any Drupal site: the default one for "front-end" and an admin one for the "back-end" side.

There is also a part of the site that is ambiguous about whether it falls under "front-" or "back-end", and that is Editing content pages.

There is a setting under Appearance that controls which theme should be used for editing content. When adding a template for content-editing pages it's important to double-check which theme is chosen there to know which theme to add the template to.

As always, don't modify the contributed themes, instead add a subtheme that extends them and add the template there. Then adjust the Appearance settings to use the subtheme.


How to use dependency injection to apply a class static method?

In __construct() you can implement like this:

use Drupal\Core\Entity\EntityTypeManagerInterface;

public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
}

and create() method

public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
    );
}

You can use this service to get the file storage:

$file_storage = $this->entityTypeManager()->getStorage('file');

and then load the file:

$file = $file_storage->load($fid);


I'm looking for a Drupal Commerce Shipping in-cart estimate

link- https://drupal.org/project/commerce_shipping
Commerce Shipping provides a shipping rate calculation
system for Drupal Commerce , integrating shipping
service selection into both the checkout form and order
edit form. This module is a framework that is meant to
be used in conjunction with shipping method modules
like Commerce Flat Rate , Commerce UPS , and others.
Shipping service availability and rate calculation is
handled in the user interface through Rules and is
backed up by an API that gives you a high level of
flexibility to implement simple or complex shipping
scenarios.


How to display a flag to anonymous users?

You can do this in your 'node.tpl.php' by something like below, if user is logged in display flag as normal and if is not logged in redirect user to logging page with destination parameter

global $user;
if(!$user->uid) {
    // $flag: bookmark or make_feature, $action: flag, $content_id: $nid.....
    $flag_link = flag_flag_link($flag, $action, $content_id);
    $flag_url = $flag_link['href'];
    if(isset($flag_link['query']['token'])) {
        $flag_url .= '?'.$flag_link['query']['token'];
    }
    print l(t('bookmark'), 'user/login' , array('query'=> array('destination' => $flag_url)));
} else {
    print render($content['links']['flag']);
}


Use CAPTCHA module on a custom HTML form? (no use of Drupal Form API)

I'm wondering maybe my custom HTML form doesn't have a $form_id because it doesn't use any drupal form modules? If that's the case, then I probably can't use the CAPTCHA module. Could someone please confirm?

Correct - the Captcha module has been written exclusively for integration with forms built by the core form API. Without a lot of changes, it's not possible to use any of its functionality on a form that hasn't been built by Drupal.


Disabled date field on node form stops it from saving

If using hook_form_alter you can use #limit_validation_errors to exclude that field from validation.

  The #limit_validation_errors property is a list of "sections" within
  $form_state['values'] that must contain valid values. Each "section"
  is an array with the ordered set of keys needed to reach that part of
  $form_state['values'] (i.e., the #parents property of the element).

Example 1: Allow the "Previous" button to function, regardless of whether any user input is valid.

  $form['actions']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Previous'),
    '#limit_validation_errors' => array(),       // No validation.
    '#submit' => array('some_submit_function'),  // #submit required.
  );

Example 2: Require some, but not all, user input to be valid to process the submission of a "Previous" button.

  $form['actions']['previous'] = array(
    '#type' => 'submit',
    '#value' => t('Previous'),
    '#limit_validation_errors' => array(
      array('step1'),       // Validate $form_state['values']['step1'].
      array('foo', 'bar'),  // Validate $form_state['values']['foo']['bar'].
    ),
    '#submit' => array('some_submit_function'), // #submit required.
  );

More info: form_set_error


Altering Create New account tab link in user login page

Well, you could use hook_menu_alter() to change the call back function of that menu item:

function MY_MODULE_menu_alter(&$items) {
  $items['user/register']['page callback'] = 'my_custom_function';
}

And then you could redirect to a new page in the callback:

function my_custom_function() {
  drupal_goto('customlink');
}


Remove the extra headers from the e-mails sent

Apparently someone came up with code to put in a custom module that will remedy this issue:

http://drupal.org/node/461324

I've yet to try it though.

UPDATE:

I tried out an altered version and it worked for me. Here's what I had:

email_sender_override.info:

name = E-mail Sender Override
description = Overrides the 'Sender' of an e-mail message with the 'From' address.
core = 7.x
package = Webform

email_sender_override.module:

<?php
/**
  * @file
  *
  * Mail altering function to override the 'Sender' of a mail message with the address
  * in the 'From' field.
  *
  */

/**
  * email_sender_override_mail_alter
  *
  * Alters the sender of the e-mail message to be the same as the 'From' address.
  * Taken from: http://drupal.org/node/461324
  * See also:   http://api.drupal.org/api/drupal/includes!mail.inc/function/drupal_mail/6#comment-3243
  *             http://drupal.org/node/656472
  *
  * @param message
  *    the full e-mail message being sent -- this will be altered
  */
function email_sender_override_mail_alter(&$message)
{
    $message['headers']['Sender'] = $message['headers']['From'];
}
?>


Problem in sending mail with attachement

For sending mail with attachment you should use Mail System and Mime Mail module
Attachment functionality is built into the Mime Mail module.

After that you must set up drupal_mail() to use mime mail as the mail system interface. This is where the mail system module comes into play. The module is pretty straightforward, and lets you set a different mail system per module. There is a straightforward configuration at admin/config/system/mailsystem where you create a new setting for your module, and select mime mail as the mail system.

Assing anttatcment in variable

$message['params']['attachments']

After that you will be able to send mail with attachment.

For more information visit here


When sending a Drupal database to a developer, how can I remove users' personal info (e-mail addresses, passwords)?

Drush supports an sql-sanitize function:

    $ drush help sql-sanitize Run sanitization operations on the current database.

    Options:

    --db-url=<mysql://root:pass@127.0.0.1/db  A Drupal 6 style database URL.
    Only required for initial install - not re-install.

    --sanitize-email        The pattern for test email addresses
                        in the sanitization operation, or
                        "no" to keep email addresses
                        unchanged.  May contain replacement
                        patterns %uid, %mail or %name.
                        Default is "user+%uid@localhost".

--sanitize-password     The password to assign to all
                        accounts in the sanitization
                        operation, or "no" to keep passwords
                        unchanged.  Default is "password".

    Aliases: sqlsan

You could always setup a clone of your live site using drush archive-dump or drush sql-sync then run sql-sanitize on that cloned sites db and get everything cleaned. I believe sql-sanitize provides a hook so you can sanitize custom drupal data you deem sensitive beyond the scope of the default username and password.


How to let the users input the filters in views

The exposed filters are not displaying because the view is empty and therefore not rendering.  As per this issue, if you give your view something to display when it is empty (i.e. a no results behaviour setting), it will show your filters.

Then, if you really don't want to show 'no results' (which is what most people put in there) you could hide it wish CSS.


Migrate Site from aegir Drupal hosting platform to Acquia hosting

Disclaimer: I do not use Acquia and don't know their service.

  Should I need to move the code as a normal multisite setup to Acquia?

The documentation seems to say that multisite is supported: https://docs.acquia.com/cloud/multi-site

You would probably need to copy the platform from /var/aegir/platforms. If you look in that directory, each directory is a pretty normal Drupal multisite codebase.

  Since the codebase is extracted from aegir environment, I don't have any files on the drupal root like install.php, update.php?

The platform is just a normal Drupal codebase, it should have these files (even if it doesn't use them).

The hard part will be to move the databases, you will (presumably) need to create them in the Acquia frontend, and change the settings.php file of each site to use the new database info. Aegir creates a drushrc.php but in a non-Aegir environment you can just take the settings and move them into settings.php.

Hope this helps.


Views will display entities the user does not have "view" access permission

Option A
Create a custom access handler for your view.
Drupal 8 - Views Custom Access with a Plugin is a great guide. It seems like your scenario may fit the use case outlined in the beginning:
"... prohibit the display of a Drupal 8 View dependent upon some custom rules that don't fit easily with Drupal's permissions model ..."
Pro: You will get exactly the control features you want.
Con: A lot of custom code.
Option B
If you want permission for viewing the entity to be directly tied to the view access, there is an "Access" section on the view configuration form. Select "Permission" and then select the permission for viewing the entity you have created.
Pro: Easy to set up.
Con: Your use case must fit into Drupal's permissions system.


Is it important to reset the $user object when accessing global $user?

It depends..

Since you load the user object from the global scope, everything you change on it will affect other functions further down the line.

If you make alterations to the user object that only apply to your module, you might want to reset those changes so other modules won't be able to see the alterations you made. Think about adding something like adding a security key, then run it through some of your functions. You don't want other modules and functions to see the key, so you want to remove it from the user object after your functions are done with it.

For only loading the user and reading it, I'd say it doesn't make sense to reset the variable.

Update

As for your example, to bypass the access check the global user object (current logged in user) is swapped with the object of user 1.
In this case it is very important to switch back, otherwise all other functions will see you as user 1 rather than your own account!

See https://www.drupal.org/node/218104 for documentation on impersonating other users.


It is possible that a module that you just updated now has a new module dependency. Go to your module listing page and see if any enabled modules now have a dependency listed as missing. Download the missing dependencies, enable and run update.php


I have found the solution: I have to create a new display suite formatter because that page use ds for the display.

I have read this

  http://www.previousnext.com.au/blog/creating-custom-display-suite-fields-or-how-i-learned-stop-worrying-and-use-hookdsfieldsinfo

and I have created my formatter. All works. Thanks for all to all.


How do I avoid caching a redirect response from a form?

I just discovered that it's related to the TrustedRedirectResponse.

A standard Symfony\Component\HttpFoundation\RedirectResponse is not cached.


Add country, state dropdown to user registrtaion

I think you can achieve that by using the Conditional Fields module

  Define dependencies between fields based on their states and values.

check out  A Drupal Dropdown List of Countries, States, Cities for more info


Views display product attributes with prices

You need to group your fields by the title. Specifically:

click on the settings button of the table format in your view and then select to group by the field that is the same in the 2 entries:

EDIT:

You can now hide your title field since it will appear in the group name:

and your final view (that you can theme according to your needs) will look like this:


If it is showing for you (user one or admin) but not someone else logged in, it could be permissions.

I would create a test account with the same permissions as the person having issues. Do you see the ckeditor toolbar while logged into the test account?

If that is working, try the solution mentioned here.


Date Module / Date Repeat: Hourly or Minutely Recurrence?

Recurring events are handled in good old unix cron, see (http://drupal.org/cron). But there is a more, Php way .. Poor Man's Cron, see http://drupal.org/project/poormanscron (in D6, part of core in D7).

Basically, since some hosts didn't allow cron jobs Poor Man's Cron simply "hooked" a bit of code into each page using Ajax. If an amount of time had past it would run cron.php (which in turn calls drupal_run_cron()).

Either way ... you need to put your task into the cron queue, make sure your site is set up correctly and let the core system execute it. If your going to use a custom module see

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_cron_queue_info/7


What you describe is something that Drupal core already does. Take as example the Node module; it defines its own template file (node.tpl.php) that is then overridden from themes, such as the Bartik theme, with their own template file (in the case of the Bartik theme, with templates/node.tpl.php).

What is wrong in your implementation of hook_theme() is the name you give to the template file. Despite what it could seem, the template key doesn't allow to give the template name an arbitrary name; the name must match the theme name you are using, in your case mymodule_list. You can replace the underscores in the theme name with hyphens, but that is the only change you could do.

See Override template files based on template filename as well as hook name, where the user suggesting the change says:

  Turns out the template file name needs to exactly match the array key used in hook_theme() (with the exception of dashes and underscores). In the case of my example, the template value would need to be my_abc_index and the file name my-abc-index.tpl.php. Failure to do so will result in an un-overridable template.

(I slightly changed formatting, and the spelling of a word.)

Also, as you see in the code used from Drupal core, the theme_ prefix in the the theme name is not necessary.

function node_theme() {
  return array(
    'node' => array(
      'render element' => 'elements',
      'template' => 'node',
    ),
    'node_search_admin' => array(
      'render element' => 'form',
    ),
    'node_add_list' => array(
      'variables' => array('content' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_preview' => array(
      'variables' => array('node' => NULL),
      'file' => 'node.pages.inc',
    ),
    'node_admin_overview' => array(
      'variables' => array('name' => NULL, 'type' => NULL),
      'file' => 'content_types.inc',
    ),
    'node_recent_block' => array(
      'variables' => array('nodes' => NULL),
    ),
    'node_recent_content' => array(
      'variables' => array('node' => NULL),
    ),
  );
}


How to overwrite /modules/user/user.module text?

You can use hook_form_alter to change this text

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_profile_form':
    case 'user_register_form':
      $form['account']['mail']['#description'] = t('My text');
      break;
   }
}


"Order items" view displaying removed items (variations)?

foreach ($items as $item) {
  $quantity = $item->getQuantity();
  $itemVariationId = $item->getPurchasedEntity()->id();
  if ($variationId == $itemVariationId){
    foreach ($orders as $order) {
      $cart_manager = \Drupal::service('commerce_cart.cart_manager');
      $cart_manager->removeOrderItem($order, $item);
    }
    return $quantity;
  }
}
// return 0; <-- not necessary, functions don't have to always return.


How to add the "user role field" in View showing users

So you need to add 2 field into your view User uid(exclude from display) and Custom text, next go to your template.php and do next

//implement hook_preprocess_views_view_fields
function YOURTHEME_preprocess_views_view_fields(&$vars) {
    $view = $vars['view'];
    $fields = $vars['fields'];

    if ($view->name == 'usr1') { // change on your view name
        $results = $view->result;
        $roles = array();
        foreach ($results as $row) {
            $user = user_load($row->uid);
            $roles = implode(', ',$user->roles ); //get all user roles
            //check if user name from field equal to current user in array
            if ($fields['name']->raw === $row->users_name) {
                $fields['nothing']->content = $roles;//put that roles to custom text field
            }
        }
    }
}

THIS CODE NEED IMPROVEMENTS, cuz it iteracts on every field of your view, so you can work on this :D.


How do you programmatically delete a field?

Drupal 8 is using object-oriented programming (except for some procedural bootstrapping files and the *.module and *.theme files).

When trying to access static methods of a class without a namespace, the class is expected to reside within the same namespace of the file you use the class name with.

This is not true for classes provided by Drupal core or other modules, when you use them within your own module.

So you have to properly use namespaces. When checking the API docs for example for FieldStorageConfig and scroll a little down, you will find the correct namespace of this class. The same goes for the FieldConfig class.

So you could use both classes by altering your source code to:

// Deleting field storage.
\Drupal\field\Entity\FieldStorageConfig::loadByName('entity_type', 'field_name')->delete();

// Deleting field.
\Drupal\field\Entity\FieldConfig::loadByName('entity_type', 'bundle', 'field_name')->delete();

However, it is best-practice to not prefix the class names by their full namespace, but use use directives at the top of your source code (after a possibly existing namespace declaration, if you are within the context of an own class).

This sums up to the following correct and working example:

use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

// Deleting field storage.
FieldStorageConfig::loadByName('entity_type', 'field_name')->delete();

// Deleting field.
FieldConfig::loadByName('entity_type', 'bundle', 'field_name')->delete();

PS.: When learning Drupal 8, it is always a good idea to check how other modules/core are doing it. You can search the code base for the class in question or use the API reference, which has a search function, and you may find plenty useful examples.


You can use javascript and ajax to update your image
just when hover your link replace src of image It is javascript only
it is not drupal all your html in the same page so it is easy to change any block when hover over another block


How to use views replacement patterns while using the PHP filter?

Figured it out. When using replacement patterns within the PHP filter you simply use double quotation marks over single ones.

i.e: $urlhere= "[field_story_url]"; over $urlhere= '[field_story_url]';

Looks like the double quotes is what allows Drupal to see the replacement tokens outside of the PHP code.


You can set a node's title with the "Set a data value" action - you don't need to write your own action. I'm going to assume that you're putting this into your own action because there are other things you want to do that you haven't mentioned or because you are learning how to write an action - if this is ONLY about setting the title then I don't see the point of a custom action.
Problems with the approach and the partial solution given in the initial post:

You don't need to get the entity ID then load the entity from
storage, because Rules is already passing you the loaded entity.

You're using entity instead of node, which wrong - Nodes have
titles, Entities in general DON'T.

You're hardwiring in a title taken from a specific field 'field_xyz'.
Instead, you should pass in a string variable which holds the title.
That way the Rule configuration can get the value out of 'field_xyz'
or out of 'field_nlm' or from a thousand other places - writing the
action with a string parameter will make it far more useful.

The EntityManager has been deprecated since Drupal 8.0 and should not be used. You should be using EntityTypeManager instead. But as I said in #1, this isn't even needed.

You don't have to save the node, Rules will handle the saving
automatically.

This really only requires one line of code (plus some boilerplate code, like all plugins...). Here's a complete solution that takes two context variables:

The node to change.
The title to use.

namespace Drupal\my_module\Plugin\RulesAction;

use Drupal\node\NodeInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Sets the title of a content item.
 *
 * @RulesAction(
 *   id = "rules_node_set_title",
 *   label = @Translation("Sets the title of the selected content item"),
 *   category = @Translation("Content"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node",
 *       label = @Translation("Node"),
 *       description = @Translation("Specifies the content item to change."),
 *       assignment_restriction = "selector"
 *     ),
 *     "title" = @ContextDefinition("string",
 *       label = @Translation("Title"),
 *       description = @Translation("The new title.")
 *     ),
 *   }
 * )
 */
class NodeSetTitle extends RulesActionBase {

  /**
   * Executes the action with the given context.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node to modify.
   * @param string $title
   *   The new title.
   */
  protected function doExecute(NodeInterface $node, $title) {
    $node->setTitle($title);
  }

  /**
   * {@inheritdoc}
   */
  public function autoSaveContext() {
    // The node should be auto-saved after the execution.
    return ['node'];
  }

}


What is the best (secure) way to run PHP code on a Drupal 8 system?

Some Drupal devs are keen on never putting PHP code in the Database, but this means you will have to know the intricacies of Drupal 8 in order to figure out how to expose what you need by creating a custom module. This can be a time sink if you just want to do something super simple.

But if you aren't that hardcore, turning on the PHP is fine if you just don't have the time or need to create a custom module to say print something out from the $user array.

I personally just use the PHP module on my sites. It's quick and efficient vs making a custom module. Obviously deciding on which approach to take depends on the site and client your working with. Does it have valuable user data? Does it have millions of user hits a day? Or is it just a purely informational site with only a few hits a day? Do you think the client would mess around with other parts of the site or are they just purely just updating content?


Set height and width of image field being rendered with views PHP

The context: drupal 7, views, views PHP, rendering some fields with
  PHP because there's no other way.

There definitely is another way, you're just not aware of it, this article was written 5 years ago:

  As of this writing, 44,497 site maintainers have read that warning and
  chosen to ignore it. They’ve chosen to put their PHP into a
  non-revisioned, difficult-to-access place, and to enable PHP input in
  a module that was never designed for security. They’ve left their site
  at risk of a very difficult to diagnose and even harder to fix WSOD.

I suggest that you fully read and understand that article and rethink your position about there being no other way.

  Because my PHP is sketchy at best and the knowledge of the drupal API
  is null. Every change costs me a lot of time and energy because,
  honestly, I lack the basics and I'm not sure of what I'm doing until I
  do it right.

Welcome to Drupal, it's a steep learning curve and if your knowledge of PHP is poor then you stand no chance of being able to understand Drupal, perhaps you could edit your question or provide a comment of what you're trying to achieve? I'm always surprised that beginner Drupalers dive straight into coding their way round a problem before investigating whether there is a non-code solution.

Finally, who cares whether an image style is going to be used anywhere else or not? It's not they are hard to set-up or cost anything.


Search API autocomplete group suggestions

One way to do this requires you to get a bit javaScript-ey

As normal Drupal autocomplete uses "https://jqueryui.com/autocomplete/"

or a wrapper of it see "core/misc/autocomplete.js"

You can do is take 100% control over it.
you can add JS to the view and optionally create a controller to handle better  "label" : "value"

$("#the-id-of-your-search").autocomplete({
      source: function (request, response) {
        var url = '/the-ajax-end-point';
       // or custom Controller returning JasonResponse() :)

       // or custom view with rest Response :)
        $.ajax({
          dataType: "json",
          type : 'Get',
          data: {
            q: request.term
          },
          url: url,
          success: function(data) {
            // play with grouping the data here.
            response( data );
          },
          error: function(data) {
            // do some thing here.
          }
        });
      },
      select: makeSelectAwesome,
      minLength: 3,
    });

   function makeSelectAwesome(e, ui) {
    if (ui && e) {
      if (ui.item) {
        // ui.item.value, ui.item.label
        $("#the-id-of-your-search").val(ui.item.label);
        // in the case of your own controller
        // you can return a whole crap load more stuff
        // Then just label / value
        // Example var data = JSON.parse(ui.item.value);
      }
    }
   }

       // php excerpt for controller ideas
       $request = $this->requestStack->getCurrentRequest();
       $query = $request->get('q');
       /// build a result.
       $value = [
         'type' => $node->getType(),
         'image_url' => $node->field_image ...
         'extra_data_to_make_ui_awesome' => []
       ];

       $results[] = [
         'value' => json_encode($value, TRUE),
         'label' => $node->getTitle(),
       ];
       return new JsonResponse($results, 200);

then i guess you just live the dream.


I'm afraid I've been short sighted: I've checked the existence of these modules through drush en MODULE assuming that Drush connect to the site basing on the site folder. It seems you now have to explicitly tell it to connect to a specific site: drush -l SITENAME en MODULE.


I've done this a couple ways.

First, you can you hook_ds_pre_render_alter (I can't find a better link to ds.api.php!) like hook_preprocess_node and just hide your title field if the image field is set. If you're using this option be sure to dig into the layout render array to the correct spot. For example if you have the ds node_title field within the ds_content region, hide it like

$layout_render_array['ds_content']['node_title']['#access'] = FALSE;

of if you have the same field within a title_wrapper field group, hide it like

$layout_render_array['ds_content']['group_title_wrapper']['node_title']['#access'] = FALSE;

Or you can create a custom ds field (yes, you have access to the whole entity). I usually enable the hidden region at /admin/structure/ds/settings, then I add both my title field and image field to the hidden region on my view mode and then just render whichever one I need in my ds field's build() method via the field's view method, in this case it would be like

$this->entity()->field_MY_IMAGE_FIELD->view('teaser');

or

$this->entity()->title->view('teaser');

Instead of passing a view mode's name, you can pass a display configuration array straight to the field's view method.


Where are the content types stored in the database?

It's configuration. Like any other config entity and simple configuration, it is stored in the {config} table.

But using the entity API is the only supported way to load that information, do not query that table directly.


Ubercart Node/Product Field access to Role and purchaser

I think the Field Permissions module may be able to handle all your needs.

Whilst you couldn't have a different permission for the teaser text of a node you could just separate this out into a separate field and then apply an individual permission there.