what's the difference between using js injector module and ['#attached']['js']

Technically the difference is very small.

Whatever js you add in $form['#attached']['js'] is added via drupal_add_js() when the form attachments are processed using drupal_process_attached() - just like the JS Injector Module adds js snippets using drupal_add_js().

The JS Injector page claims the js it serves is loaded last, so order is an aspect where the two approaches may differ, unless you do some manual adjusting of the loading order afterwards.

If you try to decide what to use - it really depends. If it is just a minor snippet you want to add, the injector has the advantage that you don't need to write an entire custom module just to add some minor js functionality. It might also be nice for front end designers who know js, but have little experience with php or writing modules. If the js to add is part of a larger module/functionality upgrade anyway though, there is little reason to make use of the JS Inspector Module.


Joomla to Drupal module - migrating issues

From the sounds of it, the module was not uninstalled correctly. You should first disable the module, then when the modules page reloads, uninstall it.  During the uninstall process is when hook_uninstall() is run and the database tables and any saved variables (from the variable table) should be deleted.

If you didn't uninstall the module correctly, Drupal never performed these actions, and therefore still believed the module was installed.  Since it believed the module was already installed, the database tables would not be created.

For more information regarding uninstalling modules see the article: Uninstalling Modules


From your question, I could understand that you're using views to show your events list with exposed filters and now you want to override the template of that exposed form.

To override the exposed form template for a particular view, you need to create a template in the following name pattern,

views-exposed-form--view_name.tpl.php

For example if your view name is event_list, then the overridden template will be views-exposed-form--event_list.tpl.php.

Once you added the template clear the cache, now view will use the overridden template for exposed form.

Take the views default exposed form template as base to theme your overridden template - Exposed form template

Note : To just override the template, you do not need any preprocess functions.


Thanks @clive for the hint

module_load_include('module','views','views');

does the trick!


How to programmatically set a file field to allow multiple uploads/values?

my example, see "cardinality" value:

$field = array(
  'field_name' => 'field_ws_file',
  'type' => 'file',
  'cardinality' => FIELD_CARDINALITY_UNLIMITED,
);
field_create_field($field);

Instead of FIELD_CARDINALITY_UNLIMITED you could also simply use -1.


For the session cookie options D8 uses container parameters instead of settings. Create a services.yml file in the same folder as settings.php. The default values are in default.services.yml. You can copy this file to services.yml and modify it:

/sites/default/services.yml:

parameters:
  session.storage.options:
    # Default ini options for sessions.
    #
    # Some distributions of Linux (most notably Debian) ship their PHP
    # installations with garbage collection (gc) disabled. Since Drupal depends
    # on PHP's garbage collection for clearing sessions, ensure that garbage
    # collection occurs by using the most common settings.
    # @default 1
    gc_probability: 1
    # @default 100
    gc_divisor: 100
    #
    # Set session lifetime (in seconds), i.e. the time from the user's last
    # visit to the active session may be deleted by the session garbage
    # collector. When a session is deleted, authenticated users are logged out,
    # and the contents of the user's $_SESSION variable is discarded.
    # @default 200000
    gc_maxlifetime: 200000
    #
    # Set session cookie lifetime (in seconds), i.e. the time from the session
    # is created to the cookie expires, i.e. when the browser is expected to
    # discard the cookie. The value 0 means "until the browser is closed".
    # @default 2000000
    cookie_lifetime: 2000000


View of organic groups name list with no activity

I suggest you to create a custom table with group id and access timestamp. Whenever you are adding a new content to OG, update the table with group id and current timestamp. Then list inactive groups (by calculating current time from your timestamp saved in table), using theme_table function.


You should try, i think it will work

format_date(time(), 'custom', 'm');
format_date(time(), 'custom', 'd');


How to create product bundle or similar to that?

For building a e-commerce website you should try the drupal commerce module or commerce_kickstart (If you are novice with drupal then commerce_kickstart is the option).
Drupal Commerce

  Core Features

  Create product types with custom attributes
  Dynamic product displays
  Order management, line item
  Payment method API, allowing many different payment gateways
  Tax calculation / VAT support
  Discount pricing rules
  Deep integration with systems like D7's Fields, Views,Rules and Entity API.

Commerce Kickstart

  Commerce Kickstart is the quickest way to get up and running with
  Drupal Commerce. It includes the latest versions of Drupal core,
  Drupal Commerce, and the other modules it depends on. It also gives
  you a set of options to create a fully-featured demo store out of the
  box complete with an attractive theme, catalog and search
  configuration, and a custom back office interface.
  Who should use Commerce Kickstart? Anyone who wants to skip weeks of
  configuration to build a commerce site on the Drupal Commerce
  framework.


From \Drupal\user\Form\UserPasswordResetForm::buildForm:

<?php
$form['#action'] = Url::fromRoute('user.reset.login', [
  'uid' => $user->id(),
  'timestamp' => $timestamp,
  'hash' => $hash,
])->toString();
?>

If you look at the form in your browser, you can see that it directly POSTS to that other route. as a result of that, your submit isn't called because for that, it would need to actually submit to itself again.

That then points to \Drupal\user\Controller\UserController::resetPassLogin(), which calls user_login_finalize(), which calls user_login().

Depending on what you want to do on submit, you can either do in hook_user_login() or by altering that route.


From a capabilities and code perspective, there is no practical limit to the number of entities in a system (blocks, nodes, users).  drupal.org is a good example of this; it has tons of users and nodes on it.

That doesn't preclude needing to properly scale out the rest of the system.  This is particularly important in a Drupal 8 system, where caching is used extensively.  One of the most overlooked aspects of this is properly tuning the database.

Out of the box, MySQL can have some bad default parameters.  MySQLTuner can provide some guidance on how to adjust your system, particularly the buffer size.  If your cache tables get large, I/O from them can slow down when they are hitting disk.

When you get to the point where you need to squeeze more performance out of a tuned site or if you are memory limited for proper tuning, you may want to consider a non-database caching solution like memcache or Redis.  These can really help with large systems.


What are my options to rename a (huge) cache_form table which takes way to long?

"Waiting for table metadata lock" will happen with a TRUNCATE or a RENAME and once this query is slated to run all other requests behind it will be stalled. There is no way to tell if a query will have a metadata lock unless you attempt to run it. So if the query does indeed cause a metadata lock you'll want to kill that query and use DELETE FROM instead as this is a DML statement where as TRUNCATE or RENAME are DDL statements.

I created a module that handles the above logic: APDQC

If you want to investigate this you self slides 104 - 113 of my 2015 DIY Drupal 7 Performance talk is a good start. How to create a stored procedure in order to auto kill stalled queries: http://mysqlblog.fivefarmers.com/2012/08/28/identifying-and-killing-blocking-transactions-in-innodb/


Setting the permission for editing block content with a specific role

Both of those modules look more like they are meant to simply display different blocks/content depending on user role.  You may be better off utilising Nodes In Block.   Create a content type, or use one of your existing content types and create a node that has the required block content.  Lastly, allow certain roles permissions to edit that particular node.  That will in turn update the block content!


The display suite module has a "region to block" in its extras. This lets you put any of the fields displayed into its own block which can then be put where you want but I believe that editing will still take you to the full node edit page anyway.

For editing on the fly you should look into the jeditable module and/or editablefields module.


You can uncheck "Display processing result" in the VBO settings (in the edit view UI).

VBO for D7 stopped generating that many messages in latest -devs (after beta1). It now only shows one message: "Performed $operation on $count items."

That is something that should be backported to D6, there's an open issue for it.
In general, you can't affect those, the module is just calling drupal_set_message (usually in _views_bulk_operations_execute_finished()).


TB Mega Menu module has a CSS folder. Use that as your reference. It also has a styles sub-folder that IMO would be of greatest benefit. Just copy one of the whole styles/*.css files over and adapt it. No need to hunt it down.

To target a menu on a specific page you will need to inject a CSS class into that page via a preprocess_page hook or Context or some other preferred method. You need to set it closer to root level (ie html or body tag) than that of .tb-megamenu class occurence in the html. Having done that all you need do is prepend your injected class to every single selector that you use, as in:

.tb-megamenu.style-black .nav > li > a:focus,
.tb-megamenu.style-black .nav > li > a:hover {
  background-color: #222;
  color: #7bb9e0;
}

becomes:

.my-page-class .tb-megamenu.style-black .nav > li > a:focus,
.my-page-class .tb-megamenu.style-black .nav > li > a:hover {
  background-color: #222;
  color: #7bb9e0;
}


How to get value properly from form field?

If  you need to get the value of the array you can use below method.

 $values = $form_state->getValue(array('name_of the array', 'key'));


commerce product display showing only one product when multiples selected

Check the Display settings for the Product Display type in Structure -> Content -> Product Types, and make sure that the Product field is set to be visible on all view modes.

Set it to "Add to Cart form" and it will display a choice of all applicable products.

Note - I had a duplicate "product" reference field on products which confused the issue, and this was what was displaying the single "add to cart" button.


Why is the token in my custom module not replaced?

Translatable strings don't use tokens, but placeholders, see for example https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Render%21FormattableMarkup.php/function/FormattableMarkup%3A%3AplaceholderFormat/8 for some documentation, or https://www.drupal.org/node/322729 (more 7.x, but conceptually still mostly OK).

Tokens are when you have user configurable text like the user register/confirmation mails. It doesn't make sense to have token in a text that is hardcoded since tokens are only useful if that text can be customized by the user. For documentation on how to use the token API, see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21Token.php/class/Token/8


What is the equivalent of module_load_include()?

The answer is that the load method isn't the correct method, and there's a specific loadInclude() method.

\Drupal::moduleHandler()->loadInclude('ilib_connect', 'module');


How to define event listener in the service?

If I understood correctly, I think you are asking about implementing minimalistic single responsibility event listeners declared in the YML config file, like in this Java example:

class MyListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    myTextArea.append('Hello from MyListener');
  }
}

That is not possible since this is this what the EventDispatcher actually does:

    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
            if (is_string($params)) {
                $this->addListener($eventName, array($subscriber, $params));
            } elseif (is_string($params[0])) {
                $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
            } else {
                foreach ($params as $listener) {
                    $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
                }
            }
        }
    }

You can still have your separate ActionListener's, but you would have to write some code to call them from your implementation of EventSubscriberInterface.


Well, I have experienced a similar problem when manipulating with more language versions. In the config database table, I had two rows with the name system.site - one of them had a collection = "language.sk" and the other (full record) had an empty collection and in the data column langcode SK. So, I think the interface was confused, because there were two rows for one language. However, I do not know how the database got into this state.

So I have deleted the row with collection = "language.sk", cleared the cache and now you can change source site name and also create translations - it started to work. Please try this and let me now, if that works.


Link a field in content types to the user profile

First, you should make sure that the default author relationship isn't sufficient to satisfy your needs. Every content type has a creating user; this relationship can usually be used to create any necessary links between the content and the user in Views, Panels, or other modules.

However, sometimes you need to have multiple users associated with content. Your "photographed by:" example sounds like a good example of this use case. In that instance, I would use the User Relationships module to add a User Relationship field to the content type.


Install Drush on shared hosting with SSH access?

you can also install manually as long as you have ssh access
# get drush latest 8 version
# drush 8 works with D8, D7 and D6
# https://github.com/drush-ops/drush/releases
wget https://github.com/drush-ops/drush/releases/download/8.4.2/drush.phar

# make it executable
chmod +x drush.phar;

# move it to home directory or any other directory
mv drush.phar ~/drush;

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bashrc
# or
# nano .bash_profile

# add this the end of the file
alias drush='/home/your_user/drush';

# use the alias you just setup
source ~/.bashrc;


how to delete the nodes having a specific entity reference but not the parent

If this a one-time need, you could build a custom query DB query if you wanted to go the developer route. However, if this is an ongoing need you're better off with the site builder route you've hinted at in your question.

In your case, you want to a create a node view filtered by content type Students. Add a Entity Reference: Referenced Entity for the field that contains your references to Courses. The last step is to add an exposed filter for the same Courses field making sure enable relationship that you added; that will present a select list of referenced Courses from which you can filter down the Students and present your VBO delete widget.


It's funny how some times after you ask someone or a community for some solution you actually see the problem more clearly.

I was able to complete all of the mentioned tasks and I will summarize here just in case someone bizarrely stumbles upon a similar scenario in the future - although I really doubt it.

So, the views linking to each other dynamically was accomplished using the [tid] argument from the URL and passing it accordingly:

<a href="/Cakes/AllCakes/<?php echo arg(2);?>">
<a href="/Cakes/AllCakesList/<?php echo arg(2);?>">

The jump menu itself is set to Link to the thumbnail view by default unless the url is that of the 'catalogue' view. If so, via theming:

<?php if (arg(1) == 'AllCakesList'){
  $output=  str_replace("/AllCakes/" , "/AllCakesList/",$output);
}?>
<?php print $output; ?>

It leads to the 'catalogue' view.

And if the user is on none of those pages, the jump menu will lead him to the thumbnail view thus also fulfilling the 4th task in my question. That's all folks, sorry for the monstrous post!


Using hook_js_alter to change localsettings variable in the autologout module drupal

The structure of the $javascript array passed to hook_js_alter() is similar to the following one. (I reported only the relevant part of the array.)

array(
  'settings' => array(
    'data' => array(
      0 => array('basePath' => '/'),
      1 => array ('pathPrefix' => ''),
      2 => array('ajaxPageState' => array ('theme' => 'bartik', 'theme_token' => 'oFpiDA70-NnnvSdIL6bFt1oLccvTT5SZeOp3G34cOfs')),
      3 => array ('overlay' => array('paths' => array('admin' => 'node/*/edit node/*/delete node/*/revisions node/*/revisions/*/revert node/*/revisions/*/delete node/add node/add/* overlay/dismiss-message user/*/shortcuts admin admin/* batch taxonomy/term/*/edit user/*/cancel user/*/edit user/*/edit/*', 'non_admin' => 'admin/structure/block/demo/* admin/reports/status/php'))),
      4 => array('overlay' => array('pathPrefixes' => array())),
      5 => array('overlay' => array('ajaxCallback' => 'overlay-ajax'))
    ),
    'type' => 'setting',
    'scope' => 'header',
    'group' => -100,
    'every_page' => true,
    'weight' => 0
  )
  // ...
);

I would use the following code for hook_js_alter().

if (isset($javascript['settings']['data']) && is_array($javascript['settings']['data'])) {
  foreach ($javascript['settings']['data'] as $index => $settings) {
    if (isset($settings['autologout']['title']) && is_array($settings['autologout'])) {
      $javascript['settings']['data'][$index]['autologout']['title'] = 'Your value';
      break;
    }
  }
}


How can I remove 0 & negative values(-1 to -100) in weight module section?

Display weights 1 to 100 only case below code working good.
  path:sites/all/modules/weight/weight.module file 751 line

/**
 * Get an array of options to for selecting a weight.
 */
function _weight_get_options($range) {
  $max = $range;

  $options = array();

  for ($i =1; $i <= $max; $i++) {
    $options[$i] = $i;
  }

  return $options;
}

Before code:

/**
 * Get an array of options to for selecting a weight.
 */
function _weight_get_options($range) {
  $max = $range;
  $min = $max * -1;
  $options = array();

  for ($i =0; $i <= $max; $i++) {
    $options[$i] = $i;
  }

  return $options;


How to disable breadcrumbs by default and enable only particular ones with Path Breadcrumbs module?

There is a patch for the Path Breadcrumbs module that adds a setting to disable other breadcrumbs: https://www.drupal.org/node/2483091

The patch allows an easy one click disabling of other breadcrumbs.

Here is a screenshot of the setting on the patch breadcrumbs settings page (admin/structure/path-breadcrumbs/settings) as it is in the current version of the patch:


Here is a configuration that should do what you need:

Hope this helps!


Module for sidebar menu which appears in open atrium


Exporting a feature to a specific directory using drush

Use the command drush fe my_feature views_view:my_cool_view --destination=sites/all/modules/custom

https://drushcommands.com/drush-7x/features/features-export/
http://dirtystylus.com/2016/02/18/setting-a-destination-directory-for-drush-features-export/

Bonus: To change the name of the feature, and other info, edit the name= section of: sites/all/modules/custom/my_feature/my_feature.info


How to change drupal commerce status message?

You need to find the rule called 'Display an Add to Cart message' and edit it.

You'll see there is a related action in there called 'Display a translatable Add to Cart message'.  In mine, I've even added a second action that takes folks to my cart immediately after adding an item:

In any case, what I would do is delete that specific action and then Add a new action instead.  From the 'System' section, choose 'Show a message on the site'.

Then, in the 'Value' field of that action, you can add whatever message you want and you can add html in it as well.  So you can add something like:

Ready to checkout?

Let us know if this worked for you...


Programatically updating node immediately after creation causes PDOException

Drupal provides a Lock API for this purpose - to handle when multiple processes are competing for a resource.

In your case, you need to acquire a lock and release it when finished, checking if that lock is available prior to processing from the other component.

i.e:

lock_acquire
lock_release
lock_wait

Although not directly related, you may also be interested in the Queue API for other queue based processing tasks.


How does the views page style options work?

It is a CSS question, not Drupal.

I understand that using the Open Outreach theme you probably run a non-profit organization of some kind, so I'll try to help you.

You already said that you don't want to learn HTML/CSS in other questions so I will try to be straightforward: you can't.

What you might do is change from Unformatted List to HTML List and hope that the basic CSS don't change it. And yes, the preview will be different from the final view because templates. The closed admin part uses a template different than the open part.


How to check if a basic page is published?

If you look in the core theme file core/themes/stable/templates/content/node.html.twig under "Available variables:" you'll find

  node.isPublished() will return whether the node is published or not.

Can also be found here.

Which means you can do:

{% if node.isPublished() %}
  {# content for published nodes #}
{% endif %}

Edit by OP: (17/08/2017)

The above was a partial answer, but I also had the problem that the twig file I needed do this check in wasn't associated with the node I needed to check the published state of. So, using something like menu_get_object wouldn't work.

Since Drupal doesn't seem to have any easy function to get a node by ID/Alias, I created the following function to get a node by URL alias:

public static function getPublishedStateByPageAlias($pageAlias)
{
  $nodeIsPublished = false;

  // Get node path from alias
  $path = \Drupal::service('path.alias_manager')->getPathByAlias($pageAlias);

  // If there is a valid path
  if(preg_match('/node\/(\d+)/', $path, $matches)) {
    // Get the node from the path
    $node = \Drupal\node\Entity\Node::load($matches[1]);
    // Start an entity manager
    $node_storage = \Drupal::entityManager()->getStorage('node');
    // Get the relevant node by its ID using the entity manager
    $chosenNode = $node_storage->load($node->id());

    // Is it published?
    $nodeIsPublished = $chosenNode->isPublished();
  }

  return $nodeIsPublished;
}

I could then call this function in my site's custom module, pass the result to the relevant twig file as a boolean variable, and conduct the necessary check.


including javascript via theme.info doesn't work.

Do you have aggregation on in configuration > development > performance?

If so, this causes the problem. Clear all caches, and the problem should be solved.


How to use flags to pass variables to users?

Consider using the Profile 2 module. Excerpt from its project page:

  Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity - leverage the power of fields.

That project page contains a lot more interesting info, such as these Features which might help for addressing this question:

  Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated permissions for those.
  Optionally, profile forms are shown during user account registration.
  Similar to the deprecated core profile module, fields may be configured to be private - thus visible only to the profile owner and administrators.
  By default the UI behaves similar to the deprecated core profile module, thus showing each profile type in each own tab below user//edit. Via the included "Profile pages" module profiles can be viewed and edited at their own page and get their own menu link, e.g. "My profile".
  Thanks to the foundational entity API the module integrates well with Rules as well as Features - thus profile types and the associated fields can be exported into feature modules. Once the Entity tokens module (part of the Entity API) is turned on, there are also token replacements available.
  You may use Views and/or the Search API to provide listings or searches for profiles.

Refer to its community documentation also for more details about this module.


How do I a use a template file to theme a mulit-step form?

The first thing to do is to save the current step to an element in your form:

$form['step'] = array
(
  '#type' => 'value',
  '#value' => $form_state['step'], // or however you are storing the step
);

Then, in the preprocess function form your template, you can turn this into a variable that can be used:

function THEME_preprocess_THEMEKEY(&$vars)
{
  $form = $vars['form'];
  // This sets up the variable
  $vars['step'] = $form['step']['#value'];
}

Now, in your template you will have a $step variable available that you can use for choosing which elements to output:

<?php if ($step == 1): ?>
  // output step 1 fields here
<?php elseif ($step == 2): ?>
  // output step 2 fields here
<?php endif; ?>


Query condition on entity reference field count

Try to use the delta. This is explained here: QueryInterface:

$query = Drupal::entityQuery('node')
            ->condition('type', 'article')
            ->condition('field_tags.%delta', 1, '>');
dd($query->execute());


You can extract the tid used in the view in a preprocess hook, and use it to get the description and render it where you want.

Another solution would be to create an area handler that displays the description. This could then be used to render the term description in the header or footer section of the view.

To create an area handler you need to subclass views_handler_area and add your area handler to the term using hook_views_data_alter

hook_views_data_alter(&$data) {
  $data['taxonomy_term_data']['your_area_handler'] = array(
    'title' => t('Title'),
    'help' => t('Help text.'),
    'area' => array(
      'handler' => 'your_views_area_handler_class',
    ),
  );
}

The area handler doesn't need much more than a render function which acts as it's theming function, so it's not that tricky.


Limit the number of levels (depth) of a taxonomy vocabulary

After a lot of Googling and trial and error I came up with the following means of limiting a vocab's depth. You can make it as specific as you like:

Limit the depth of Parents on the term edit page:

function MY_MODULE_form_taxonomy_form_term_alter(&$form, &$form_state) {
  if ($form['#bundle'] == 'MY_VOCAB') {
    // Limit parents to none or only top level items
    foreach ($form['relations']['parent']['#options'] as $tid => $option) {
      if (substr($option, 0, 1) == '-') {
        unset($form['relations']['parent']['#options'][ $tid ]);
      }
    }
  }
}

Limit the depth of Tabledrag on the taxonomy terms listing page:

I could not re-implement theme_taxonomy_overview_terms() as another module had already done this and it made no sense to do that.

function MY_MODULE_preprocess_page(&$variables) {
  if (current_path() == 'admin/structure/taxonomy/MY_VOCAB') {
    // Prevent tabledrag from allowing more than two levels in this hierarchy
    $settings['tableDrag']['taxonomy']['term-depth'][0] = array(
      'target' => 'term-depth',
      'source' => 'term-depth',
      'relationship' => 'group',
      'action' => 'depth',
      'hidden' => false,
      'limit' => 1,
    );
    drupal_add_js($settings, 'setting');
  }
}


space character in url is coming up as '%20'

%20 is a standard replacement for the space character in URLs.

If you're using pathauto for clean urls ( presumably ), it should remove those from the URL, and replace with hyphens.

/admin/config/search/path/settings

  SEPARATOR

  Character used to separate words in titles. This will replace any
  spaces and punctuation characters. Using a space or + character can
  cause unexpected results.

Check that a hyphen "-" character is being used there.

The regular product title can have spaces, but pathauto should replace those with the separator character in the URL.


How do I limit a particular search result from being indexed

I wanted to thank everyone for their input. In the end we created a small module that will alter the query instead of trying to alter the index of the site. To do this we utilized hook_query_alter() to add a subquery to the search. Below is the final version of our hook for reference should someone else have a similar issue.

function product_view_display_query_alter(QueryAlterableInterface &$query) {
  $is_search = FALSE;
  $tables =& $query->getTables();
  foreach($tables as $table) {
    if ($table['table'] == 'search_index') {
      $is_search = TRUE;
    }
  }
  if ($is_search) {
    $subquery = db_select('field_data_product_web_catalog','pwc')->fields('pwc',array('entity_id'))->condition('product_web_catalog_value',1);
    $query->condition('n.nid',$subquery,'IN');
  }
}


Error: Class 'DOMDocument' not found in Drupal\Component\Utility\Html::load() (line 286 of core/lib/Drupal/Component/Utility/Html.php)

That sound like it can't find php Dom extension, to get that try sudo apt-get install php-xml, it should solve your problem


How to act based on a styled image is generated?

I believe this is what you are looking for.
http://happypixels.com/blog/triggering-creation-imagecache-derivatives-programmatically

Also see the trigger module.
http://drupal.org/documentation/modules/trigger

You can add your desired action to trigged.


How to add image field to main navigation menu item

Here's how I added a custom image field to my main menu link items. I added this to my custom module.

function my_custom_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['menu_link_image'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Menu link image'))
      ->setDescription(t('Upload the image related to this menu item'))
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

Flush the caches and the field should appear in the Menu Item form.

The only issue I had was that I was getting a MySQL error Column not found: 1054 Unknown column 'menu_link_image' when submitting the form. One solution to that was to add the column menu_link_content to the menu_link_content_data table but this is not a very good solution since you are altering a core Drupal db table.

I am still working on finding a better solution (e.g. using hook_form_alter to save that field to a different/custom db table). Any feedback/comment is appreciated.


How to prevent my site to crash when adding video content using the Media Colorbox module?

Might there be an incorrect link to a video player library or something? Maybe it's the setup of the player and not colorbox, media colorbox, or file entity. Just guessing....


Changing Global: Text Area based on an exposed filter in views?

You could use

hook_views_pre_render(&$view){
    $view->attachment_before = $view['exposed_input']['your_desired_field'];
}

Hope it works


What is the best method to allow a user to attach dynamic, custom content sections to a node?

looks like you need to use comments module for it, you will modify comments by adding more fields to it (for rating etc), then you can attach unlimited such content to your node. if you're in D6 you need to convert your comments to node (using some module) and then add more fields to it by CCK, and if you're using D7 you can attach fields directly (i guess - b/c its entity now)


Views PHP Filter - Filter Results by Role

I would take the ORDER BY out of your last query and let views sort things itself. After all, you may want to sort the nids by date or something later on, so why do things twice?

And also change your query style to use the drupal syntax, like:

SELECT nid FROM {node}...


How to display certain links in a menu only if a precondition is met?

First of all you need to store value of 'For Test User' checkbox as variable OR as separate column in menu_links table.

like variable_set(url, checkbox_value);

By using hook_menu_alter you can check the variable is set for that url. and if its not set you can set $items['url']['access callback'] = FALSE, By setting this menu will not be visible.

Let me know if anything different required.


Grouping by day + events spanning several days

Make 2 or 3 computed view fields (which will require some php):

1field for day of event
1 or 2 fields for start time and end time dates.

You can group the View output by the first field. Then create the event time range by inlining the 2 other fields.

With these 3 pieces of info the calendar should be able to see the start and end datetimes and make a line representing the event duration.


Drupal Rule to Clear a Field But Still Retain Data?

Use hook_form_FORM_ID_alter() with FORM_ID = node_form.

Example:

function your_module_name_form_node_form_alter(&$form, $form_state) {
  $form['field_a']['#default_value'] = '';
}

For the second portion of your question, look into Node revisions.


It's entirely dependent on your business needs. The advantage of Commerce Recurring is that as part of the Drupal Commerce ecosystem, it gives you a complete toolset for building a subscription management interface in Drupal 8. This will let you completely customize the checkout flow, order receipts, other user interfaces and more, but it does require experience with Drupal 8 to build and maintain. For more information, review the documentation at:

https://docs.drupalcommerce.org/commerce2/developer-guide/recurring

If you just want to embed a Stripe widget, I recommend MoonClerk.


Is there any way to connect to a second (MySQL) database in a Kernel Base test?

I have figured it out. The setUp() method in my Kernel Base Test must look like that:

/**
 * {@inheritdoc}
 */
protected function setUp() {
    parent::setUp();

    $databases['second-database']['default'] = array(
        'database' => 'second-database',
        'username' => 'second-database',
        'password' => 'second-database',
        'prefix' => '',
        'host' => 'localhost',
        'port' => '3306',
        'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
        'driver' => 'mysql',
    );
    Database::setMultipleConnectionInfo(
        $databases
    );
}


Display message on initial login only once without a module

I propose you to have a look at this: hook_user_login, it fires exact on user log-in. A sample code is provided on its documentation page ready to be configured and used.


Checking if a field is empty fails, on a node template file

$content['field_myfield'] is an array containing some keys; if you pass that array to empty(), you would not get back TRUE as result.
For example, I added a three fields to a content type (their types are "taxonomy term reference," "decimal," and "list of float values"); what you see in content['field_name'] is the following:

$content['field_name']['#items'] contains the content of the field; it's an array, as in Drupal 7 fields can contain multiple values.

The generic code that allows to check if the field is empty, which works for any field, without to know details about how the field values are stored, is similar to the following one:

// $field_name contains the name of the field.

$field = file_info_field($field_name);
$function = $field['module'] . '_field_is_empty';

foreach ((array) $content[$field_name]['#items'] as $item) {
  if (!$function($item, $field)) {
    $result = TRUE;
  }
}

$is_empty = empty($result);

$is_empty is equal to TRUE when all the items of the field are empty, giving to empty the meaning given to the word from the module implementing the field. For example, the module could consider the field empty when its value is "none" or any similar value (e.g. "empty" or "<none>").


if you end up getting stuck, you could create a Rule that populates a node when a user is created, and essentially create a node-based profile that the user can edit, then use Rate. Look at Node Limit to limit the profile count to 1 node per user, and set permissions on the content type to restrict the user being able to only edit (and not delete) their own content.

Rules:

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

Rate:

  This module provides flexible voting widgets for nodes and comments.

Node Limit:

  The Node Limit module allows administrators to restrict the number of
  nodes of a specific type that roles or users may create. For example,
  if a site has an "Advertiser" role that can create "advertisement"
  nodes, then the node limit administrator can restrict all users in
  that role to a specific number of nodes. He may also restrict users on
  a per-user basis.


Batch API in Drupal 6 serializes everything into one row, causing the problem you've seen.
You need to do manually what Batch API does for you automatically in Drupal 7: use a queue.
The Drupal Queue module is a Drupal 6 backport of the Queue API that is in core for Drupal 7.

Basically, queue the items you want to process, and then only pass the queue ID to Batch API.
Batch API then fetches the queue and processes the queue part by part until it's done.
See batch_example_batch_2 from the Examples project for reference.

The Examples project also has an example module for queue usage, see:
http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x:/queue_example


How to hide a field in a comment in hook_comment_view programatically?

hook_comment_view(), along with most of the other entity view hooks, are typically used to add properties onto the entity object.

If you read the source for comment_build_comment(), $comment->content[] has already been built up by the time the view hook gets invoked.  So, messing with the field directly has no effect at this point.

You want to implement a template_process_comment() in your theme, or you can implement a module (which technically makes it an instance of hook_preprocess_comment().

Implement this, and then dpm($variables) inside it.  Figure out what you don't want, and then unset() it.  If the variable is printed directly from the comments template, this is is directly in $variables.  If it is in the content section, then unset the proper key in $variables['content'], which is a render tree.


How do I get the product ID when I submit the form?

Hi guys finally i got the solution to it, all that I need it was the following:

$product_id = \Drupal::routeMatch()->getParameter('commerce_product')->id();

then I got the product id of the product i am checking it


Default Field Value based on another referenced field

You can use a hook_ENTITY_TYPE_create() to prepopulate comment fields with data from the parent entity:

  function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
    $node = $comment->getCommentedEntity();
    if ($node && $node instanceof \Drupal\node\NodeInterface) {
      if ($node->hasField('field_example')) {
        $comment->subject->value = $node->field_example->value;
      }
    }
  }


According the Twig If documentation, you would do it like this:

{% if content.field_boolean == true %}

   {{ content.body }}

{% else %}

   {{ content.field_image }}

{% endif %}

You need to use content.[machine name] you can find the machine name of you fields in Manage Display of your content type.

From my example. change content.field_boolean to the machine name of your boolean field. If your boolean field is called "cool" then replace it with content.field_cool

Remember to clear/flush the cache to see changes.


Views PHP: Getting "Available Variables"

The variables (or field) that you need to use as Available Variables must be before the Views PHP variable. Besides that install Devel module and use kpr($row) or kpr($view) or kpr($data) to get the available properties of these variables.
Also in "Output" section you can use var_dump or print_r to print available variables.


How to run custom command running drush cron via sudo?

OK, I've finally solved my own problem.

In summary, it wasn't actually a Drush thing in the end.

In detail, my custom drush command was also fixing file permissions and ownership, as per https://drupal.org/node/244924 (because cron can sometimes create a file, and then the file may have the wrong owner/perms).  This sets the ctime on all files, and it turns out that Drupal update checking relies on the ctime.

With hindsight of course I should have done a test with the permissions line removed from my custom command, but it hadn't occurred to me it could be relevant.


How do i configure admin email on a shared host? where is that email going?

Go to Configuration > Site information (admin/config/system/site-information)

and change the "E-mail address" in Site details.

Greetings.


How to use 2 twig template for for one field (or how to add a variable to a template from a template)

How to add a variable to the field template from the node template?

What you see in the node template from the field is before the field preprocess is run.

The global preprocess for fields starts like this:

function template_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];

  // Creating variables for the template.
  $variables['entity_type'] = $element['#entity_type'];
  $variables['field_name'] = $element['#field_name'];
  $variables['field_type'] = $element['#field_type'];
  $variables['label_display'] = $element['#label_display'];

Here can see, how the variables for the field template are built.

Example:

To add a variable in node set the variable with a '#' prefix:

function mytheme_preprocess_node(&$variables) {
  if (isset($variables['content']['my_field'])) {
    $variables['content']['my_field']['#var1'] = 'a value';
  }
}

And then in the field template:

function mytheme_preprocess_field(&$variables) {
  if (isset($variables['element']['#var1'])) {
    $variables['var1'] = $variables['element']['#var1'];
  }
}

The variable is then available in the field twig:

{{ var1 }}

To solve your specific problem I would suggest you copy the field in node preprocess and then set for both copies different variables.


You can also create a new template for how the Views row style works for your View: Views 2 theming.


You can find it here "admin/config/regional/translate/translate"


Menu unserialized warning when using autocomplete in a custom module

There are three functions calling menu_unserialize(), the function for which the error is reported:

menu_get_item() uses it in the following code

  if ($router_item['access']) {
    $router_item['map'] = $map;
    $router_item['page_arguments'] = array_merge(menu_unserialize($router_item['page_arguments'], $map), array_slice($map, $router_item['number_parts']));
    $router_item['theme_arguments'] = array_merge(menu_unserialize($router_item['theme_arguments'], $map), array_slice($map, $router_item['number_parts']));
  }

_menu_check_access() uses it in the following code

$arguments = menu_unserialize($item['access_arguments'], $map);

_menu_item_localize() uses it in the following code

$item['title'] = t($item['title'], menu_unserialize($item['title_arguments'], $map));

The Invalid argument supplied for foreach() error simply means that foreach() is getting a value that is not an array. With the code you are showing, that is happening only for $arguments = menu_unserialize($item['access_arguments'], $map); since you are setting $item['suggest_feature/autocomplete']['access arguments'] to TRUE when it should be an array.

In your case, the code should be the following one.

/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

For Drupal that code would be equivalent to the following one.

/**
 * Implementation of hook_menu()
 */
function suggest_feature_menu() {
  $item['suggest_feature/autocomplete'] = array(
    'page callback' => '_suggest_feature_autocomplete',
    'access callback' => 'user_access',
    'access arguments' => array('access example autocomplete'),
    'type' => MENU_CALLBACK
  );

  return $item;
}

You can understand now why your code is wrong.

It's not the access arguments that you can set to a boolean value, but the access callback. See what the documentation for hook_menu() says. (Emphasis is mine.)

  "access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments' (see below).

And for the access arguments, it says:

  "access arguments": An array of arguments to pass to the access callback function, with path component substitution as described above. If the access callback is inherited (see above), the access arguments will be inherited with it, unless overridden in the child menu item.


Apache solr with rules module, on refresh, rule viewing node triggers it in search page

I struggled with a similar question ... The "clue" about what "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

So in your case, it'd be interesting to find out what result you'd get by using (system) event Drupal is initializing instead ... definitely worth a try I think ...

Be aware: this applies to D7 ... and D6 is another story.


You are correct. You could perfectly accomplish this with Views. A simple guide, just for illustration purposes, since we don't have the specifics in your question:

Create a View
In the FILTER CRITERIA section, add the desired filters (make sure to check the "Expose this filter to visitors..." checkbox) by doing that, you are indicating that you want it to be visible in the search page, so your users can change them.
In the OTHER area, mark "Use ajax" as "Yes" to submit the form asynchronously.
In the EXPOSED FORM area, go to "Exposed Form Style" > "Settings" and check the
"Autosubmit" checkbox (if you wish to automatically submit the form once an element is changed).

Additionally, you could use the Better Exposed Filters module for advanced cool stuff (E.g. hiding the "Send" button, showing filters as checkboxes, etc).


Passing theme suggestions to radio and checkbox children

A possible way is to alter the form in which the radio is used if you know its id, or, for a broader solution, check for each form whether the radio is used.
Then you can call this function:

    function MY_CUSOMT_FUNCTION(&$form, $theme_suggestion) {
     foreach (Element::children($form) as $child) {
     if (!isset($form[$child]['#theme_suggestion'])) {
       $form[$child]['#theme_suggestion'] = $theme_suggestion;
     }
     MY_CUSOMT_FUNCTION(&$form, $theme_suggestion)
    }
   }

You can fine tune it to include only the children of your radio though


How to change taxonomy term path for table and grid view

In Pathauto, for taxonomy term paths, put

[term:vocabulary]/[term:name]/[term:tid]/list

Then click on the Bulk Update tab and check mark Taxonomy term paths and then click Update.


how to resolve ubercart checkout IE Issue?

I fixed this issue by blocking java-script (some java-script file) on page.tpl for this page and found this is working.
the issue was i am using fancy box for my site which was loaded on all pages, and ubercart already have this so there was conflict in java-script.


use

$load = $data->field_field_date_loading[0]['raw']['value'];
echo $load;

if you are using an end date as well you can get it with:

$data->field_field_date_loading[1]['raw']['value'];


There might be a couple of method to do this.

Using Views: you can add a "Custom Text" global field and add view content to it and wrap it on the link or you can "Rewrite results" on the same file and output the field as a link.

Using a template file: view let you have a custom template file for your view, so you can use it to wrap your view content with the link.

Using jQuery: you can do something like this:

$('div.VIEW-CLASS').click(function(){document.location.href='URL.COM';});

And that will wrap the view on a link.

See the images below to see how to add a "Custom text" field and how to make it a link:

Select custom text field

Add views fields into the custom text field and make it all a link


Try to change it using hook_form_FORM_ID_alter().

// Replace FORM_ID with commerce checkout form id
function hook_form_FORM_ID_alter($form, &$form_state, $form_id) {
  $form['fieldset_item']['mymarkup'] = array(
    '#type' => 'item',
    '#markup' => 'My Markup Here.',
  );
}


How to display an individual list of user created nodes?

The simple "non-coding" version would be:

install Views Field View module
create a separate node view with a contextual filter that filters by node author
in your first/initial view, add the "uid" as a hidden field
in the same first/initial view, add a "views field" that is displaying the view created at point 2
in this "views filed" settings add the uid field as an argument


$query = \Drupal::entityQuery('node')
            ->condition('status', 1)
            ->condition('type', 'my_content_type')
            ->condition('field_ref_au', $nid, '=')
            ->range(0,1)
            ->sort('created', 'DESC')
        ;


The drush rsync command does not bootstrap your site, so it cannot find your alias files.  Move your alias files to a global location (e.g. $HOME/.drush).

Also, since @dev and @stage are multisites with the same document root, it does not make any sense to rsync from one to the other, because they share the same files.  You might want to drush rsync @stage:%files @dev:%files.


Unset email address requirement on User Form not taking

The email field is one of the entity fields added by User::baseFieldDefinitions(), which sets it with a constraint.
$fields['mail'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Email'))
  ->setDescription(t('The email of this user.'))
  ->setDefaultValue('')
  ->addConstraint('UserMailUnique')
  ->addConstraint('UserMailRequired')
  ->addConstraint('ProtectedUserField');

The UserMailRequired constraint does what its name suggest: It checks if the user's email address is provided if required. It isn't required if the account originally had no mail set and the user editing the account has the administer users permission.
That constraint needs to be removed from the entity field, to allow the email field to be empty. (It still necessary to mark the email form field as not required, though.)
use \Drupal\Core\Entity\EntityTypeInterface;

function mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'user' && !empty($fields['mail'])) {
    $constraints = $fields['mail']->getConstraints();
    unset($constraints['UserMailRequired']);
    $fields['mail']->setConstraints($constraints);
  }
}


How to create a views filter for users who have never accessed a site?

You can achieve this using following simple steps:

Add filter criteria User: Last access or User: Last login is equal to 1970-01-01

You could see the users.access = 0 in query

  Note: Drupal uses Unix time. The unix time stamp is a way to track
  time as a running total of seconds. This count starts at the Unix
  Epoch on January 1st, 1970 at UTC. Therefore, the unix time stamp is
  merely the number of seconds between a particular date and the Unix
  Epoch.


There are couple of things you can do,

install labjs module: it is a JavaScript loader, used by Twitter, Vimeo, examiner.com... which loads (and executes) all scripts in parallel as fast as the browser will allow.
Enable gzip compression: It reduces the size of files sent from server to increase the speed. You have to enable it in .htaccess file, for more information visit this page.
As @2pha said Advanced CSS/JS Aggregation is very effective effort.
Install optimize_db module: it handles the issue with fast-growing table cache_form.

Anyway, gtmetrix  suggests many techniques to improve your website performance.


drupal 7: How do I add individual css elements to an existing module css

You don't. You are supposed add your individual CSS files in your custom themes (possibly sub-themes of existing ones) or in your custom module.

In both cases, do it using stylesheets[all][] = your.css clausule in module's .info file or theme's .info file.


comment pager not showing in bootsrap theme

Adapted from this post on putting pagers above and below comments:

function mytemplate_comment_wrapper($content) {
  $comments_per_page = _comment_get_display_setting('comments_per_page');
  $content .= theme('pager', NULL, $comments_per_page, 0);
  return theme_comment_wrapper($content);
}

should render a pager for you if placed in comment-wrapper.tpl.php


Likely a different module is being used to control block display: Context or Panels would be the most likely options.  It's possible someone wrote a custom module to disable blocks in the standard blocks interface to force you away from it.

Note: Drupal 6 is no longer officially supported by the community. While there are some places that are offering long term support for Drupal 6, you should plan to move to Drupal 7 or 8 soon.


How to use hook_block_view_MODULE_DELTA_alter on Views-exposed form?

I think this is an issue with block module and may be you get your answer here. Please check the url

https://www.drupal.org/node/1076132
https://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_view_MODULE_DELTA_alter/7


How can I tell Drush in which folder should a module be copied?

You can default this to, for example, sites/all/modules/contrib, in your .drush/drushrc.php file.

$command_specific['dl'] = array('destination' => 'sites/all/modules/contrib');

Also note that you won't be able to exclude the 'modules' part of the path, as Drupal uses this to scan for modules.

There are 6 places this file can live:

  Drupal site folder (e.g. sites/{default|example.com}/drushrc.php).
  Drupal /drush and sites/all/drush folders, or the /drush folder in the directory above the Drupal root.
  In any location, as specified by the --config (-c) option.
  User's .drush folder (i.e. ~/.drush/drushrc.php).
  System wide configuration folder (e.g. /etc/drush/drushrc.php).
  Drush installation folder.


This import is empty and if applied would delete all of your configurations

Do double check the directory where the config files are located. The directory is set in settings.php like:

$config_directories['sync'] = 'sites/default/files/[...]/sync';

I had the same issue but moving the config directory to the correct place solved it.


CCK Date field not showing stored values in node edit form

I'll assume you have the latest Date module version installed, 6.x-2.10. There is a similar issue in the module's queue here. Run phpinfo() and see if Memcached is installed on your new server. Uninstalling the extension could possibly solve your problem.


Show oldest to newest of a date range field

1) Split your taxonomy values by (-).

2) Store all the values into an array.

3) Find minimum & maximum value from that array.

Ex:

  $date = array(1900, 1920, 1913, 1950, 1970, 1980);

  $result = min($date) . ' - ' . max($date);


Retrieve data from Field API programmatically

Use Field data extraction API module to accomplish your job of field data extraction.

As per the documentation, you have to write this in yourmodule

  $phonenumbers = field_extract_values('node', $node, 'phone_number');

  $result = someCustomFunction($phonenumbers);

  function someCustomFunction($user_phonenumbers){

   // Do something here and return value

   }


Why do my custom javascript modules not work anymore after updating bootstrap?


First off, you should create a basic custom module, containing an .info file and a .module file.

Call it for example "custom_wysiwyg"

[custom_wysiwyg.info]

name = My Custom Wysiwyg
core = 7.x
package = Custom
version = 7.x-1.0

[custom_wysiwyg.module]

/**
 * Implements hook_editor_settings_alter().
 */
function custom_wysiwyg_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'ckeditor') {
    $settings['allowedContent'] = TRUE;
    $settings['extraPlugins'] = 'lineutils,widget,quote_box';
    $settings['extraAllowedContent'] = array(
      'img[src,title,alt,style,width,height,class,hspace,vspace,view_mode,format,fid]',
      'a[type,length,href]',
    );
  }
}

/**
 * Register a directory containing Wysiwyg plugins.
 *
 * @param $type
 *   The type of objects being collected: either 'plugins' or 'editors'.
 * @return
 *   A sub-directory of the implementing module that contains the corresponding
 *   plugin files. This directory must only contain integration files for
 *   Wysiwyg module.
 */
function custom_wysiwyg_wysiwyg_include_directory($type) {
  switch ($type) {
    case 'plugins':
      // You can just return $type, if you place your Wysiwyg plugins into a
      // sub-directory named 'plugins'.
      return $type;
  }
}

function custom_wysiwyg_wysiwyg_plugin($editor, $version) {
  switch ($editor) {
    case 'ckeditor':
      $module_path = drupal_get_path('module', 'custom_wysiwyg');
      $plugins = array(
        'lineutils' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/lineutils',
          'load' => TRUE,
        ),
        'widget' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/widget',
          'buttons' => array(
            'widget' => 'widget'
          ),
          'load' => TRUE,
        ),
        // Quote box is an example widget based on the Samples Simplebox widget.
        'quote_box' => array(
          'filename' => 'plugin.js',
          'path' => $module_path . '/plugins/quote_box',
          'buttons' => array(
            'quote_box' => 'quote_box'
          ),
          'load' => TRUE,
        ),
      );

      return $plugins;
      break;
  }
}

The function "custom_wysiwyg_wysiwyg_editor_settings_alter" alters the wysiwyg profiles' settings when rendering a wysiwyg textfield. We add some extra allowed elements and their attributes (bugfix for media module), and we define our custom plugins.
The function "custom_wysiwyg_wysiwyg_include_directory" describes our custom module's CKeditor plugins path subfolder "plugins".

You can than place any custom plugin folders in your module's "plugins" directory as follows:

/
/custom_wysiwyg.info
/custom_wysiwyg.module
/plugins
/plugins/lineutils/plugin.js etc...
/plugins/widget/plugin.js etc...
/plugins/quote_box/plugin.js etc...

The function "custom_wysiwyg_wysiwyg_plugin" defines a list of our custom plugins which we have placed in our module's subfolder "plugins".

Note: The plugin "lineutils" is a dependency for the "widget" plugin and is not included in the Ckeditor Full download.

I hope this points you in the right direction.

greets,
Kim


Migration after server crash: maintenance mode and/or cache problem

Here is finally how I solved the problem with Yogesh help: when I tried to access the admin section while logged in as an administrator, I got an error. I therefore checked the watchdog table. The image_dimensions table was somehow missing:

[...] Undefined table: 7 ERROR: relation "image_dimensions" does not exist [...]

I created the missing table, and everyhting was then working (access to the admin section, access to the user section and so on).


How can I stop the cron tasks from being triggered by site visitors?

Drupal 7 incorporated in its modules the code that were in Poormanscron, whose purpose is exactly to run Drupal cron tasks on a site where it is not possible to set cron tasks, when a user visits your site, and every X hours (as set in the page you saw).

If you want to avoid that behavior, you just need to set "Run cron every" to "Never"; contrary to what it could seem, that just influences what happens when users visit your site.[1] You can still run Drupal cron tasks from outside Drupal, remembering that in Drupal 7 cron.php needs to be invoked, from outside Drupal, passing the value shown in "Administration > Reports > Status report."

[1]: In fact, neither cron.php, nor drupal_cron_run() checks the Drupal variable used in that settings page. The only Drupal variables used are:

"cron_key" that contains the cron key used to avoid the Drupal cron tasks are ran from unauthorized users
"maintenance_mode" that is set to TRUE when the site is in maintenance mode
"cron_last" that contains the timestamp of when cron tasks were ran last time


How to choose a CSS grid system for new theme?

Ok, there is no single best answer.  It really depends on your needs.

960.gs may be out of fashion, but you can use the Variable Grid System to make just about any grid you need (both fixed and fluid).

In my opinion, the difference between fixed with and fluid grid has more to do with the theme you want (and your art director).  Not all designs will work with fluid grids, especially ones that require pixel perfection.

That said, there are techniques that you can use to have a fixed grid, but have it adaptable for different screens.  Basically, you design a few grids with the link above, and then use CSS3 Media Queries to load the grid you want based on screen size.  This is precisely what the Omega Theme does.  I have good results with this approach (though with the Drupal 7 version), and highly recommend it rather than tacking on the grid to another base theme.  I used Zen 960 a few years ago, and ended up fighting some of the automatic grid reassignments that it did.

If you go with Omega, just note that the grid-24 that it includes is slightly different than the one from 960.gs.  This means that you can't use the 960.gs templates with Omega's grid-24.  You can hook_css_alter in the sheets from 960.gs without any side effects (Drupal 7), or use other shenanigans for Drupal 6 to change the sheets you need.

If you really do need to retrofit an existing Drupal 6 theme (and can't use Omega), then I think I would sledgehammer in the multiple-grid approach that Omega uses directly into page.tpl.php.


Paragraphs item doesn't load on node/add

This seems like it can be related to the Entityqueue module. The Draggable tables widget provided by the Entityqueue module doesn't take into account that their are other entity forms (like paragraphs in your case).

There is a patch to fix this currently but it needs some work: https://www.drupal.org/node/2460503


How to add multiple field groups to a node

Field collection Modules

Provides a field-collection field, to which any number of fields can be attached.

A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


How to programmatically set Webform field value with custom submit?

The solution with hook_ENTITY_TYPE_presave :

use Drupal\webform\WebformSubmissionInterface;

 function MODULE_webform_submission_presave(WebformSubmissionInterface $webform_submission){
    global $base_url;
    $user_id_created    = null;

    //Info account
    $account_name       = $webform_submission->getElementData('nom');
    $account_username   = $webform_submission->getElementData('username');
    $account_first_name = $webform_submission->getElementData('prenom');
    $account_mail       = $webform_submission->getElementData('email');
    $account_password   = $webform_submission->getElementData('mot_de_passe');
    $account_phone      = $webform_submission->getElementData('telephone');

    if (!empty($account_username) && !empty($account_password) && !empty($account_mail)) {

      $account_username   = strtolower(str_replace(' ', '', $account_username)).'_'.rand(0,1000);

      $user_created       = User::create([
        'name'                  => $account_username,
        'pass'                  => $account_password,
        'mail'                  => $account_mail,
        'field_user_nom'        => $account_name,
        'field_user_prenom'     => $account_first_name,
        'field_user_telephone'  => $account_phone['phone'],
        'status'                => 0,
        'init'                  => $account_mail,
        'created'               => time(),
        'changed'               => time(),
        'login'                 => 0,
        'access'                => 0,
      ]);
      $user_created->save();
      $user_id_created = $user_created->id();
      $token_uid       =  $base_url .'/user/' . $user_id_created;
      $webform_submission->setElementData('token_uid', $token_uid);
    }
  }


Javascript libraries not loading from block class

You don't have a "dexp.slide" defined in your libraries.yml file. Only "dexp.block".

You're trying to attach a library that doesn't exist.


Allow .svg logo uploading in theme settings

The logo field in the theme settings says it accepts .svg format but it actually does not.  As per the error message that comes up only png jpeg jpg jpe gif extensions are allowed at the moment. Its a bug that is being worked on Unnecessary restrictions on logo format: Can't upload replacement SVG logo. Try any of the patches mentioned in the issue and report there if your issue is resolved.

Alternatively, for your theme (or custom theme) you can just put the logo.svg in the theme folder and modify the page.html.twig template file to use the .svg extension.


Best way to approach users voting on and identifying content?

Have a look at Flag module. It supports adding fields to a flag, so a user could first flag a boat ("I can identify that design!") and then select one of the known designs on the flagging form.

Whatever you end up using, I'd like to read what you choose, and why!


I have to remove HTML code that shows up on each page, where is it coming from?

It's probably your theme files then, in /sites/all/themes/[selected theme]. You can also try to change the theme and check if it is gone.

Have a look at html.tpl.php and page.tpl.php files.


Call a drupal behavior method from inside another behavior

Working example from https://web.archive.org/web/20150320092121/http://dropbucket.org/node/943:

1. ) Be sure you have included JS files in your Drupal module files.

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

2. ) module_A.js file

(function ($) {
  Drupal.behaviors.module_A = {};
  Drupal.behaviors.module_A.my_function = function(selector) {
    // Your code.
  }
})(jQuery);

3. ) Call the function in module_B.js file
(function ($) {
   Drupal.behaviors.module_B = {};
   Drupal.behaviors.module_B.attach = function(context) {

   // This is the main part here. You have to respect the namespace of module A.
   Drupal.behaviors.module_A.my_function('.my-selector');
  }
})(jQuery);


Why doesn't my form submission handler work?

Check your form id. I doubt your form id is not correct. Even you can try this also -

function my_module_form_submit($form, &$form_state) {
  // Do something here.
  echo "<pre>";
  print_r($form);
  exit;
}


How to modify Drupal 8 Views "Rewrite..." field values later in code?

After more time and effort poking around, I found one possible solution, but perhaps not the best or most efficient.

What didn't work:

My original approach of changing the field path links in theme_preprocess_views_view() didn't work because this function is too late in the page build. ("Preprocess" is apparently contextual to the target function. In this case it comes before the final View, not the View's fields.)

I also tried using template_preprocess_views_view(), which was called before other View preprocess functions. While I was able to change the View rewrite values (e.g., $view -> field['name'] -> options['alter']['path'] = 'my new path'), this changed the links for all the fields, not allowing each field to be individually customized.

I was able to change the Views rewrite path value inside hook_preprocess_views_view_field(&$variables), but this affected the following field in the results array, not the current field.

My Solution:

I ended up using hook_preprocess_views_view_field(&$variables), and rendering my own custom links and saving them to $variables['output'].

$variables['view'] and $variables['row'] were available for finding data for the logic, as well as additional objects depending on what the View is displaying.

I also used template_preprocess_views_view() to re-organize all the Views rows before they were rendered in the twig template, but as mentioned before, I couldn't change the content of the rows inside this function because they were already rendered before this function was called.

I hope this saves time for someone. Feel free to post more eloquent solutions.


Using a taxonomy select field as a contextual filter for an Entity Reference View powered select box

I was able to find a workaround to this and display the market (taxonomy) and park (parent) in a select list from a view. Then wrote some javascript to disable the options that are irrelevant (parks from other markets) once the user selects the market of the property.


you can do this with using hook_form_alter

You can do something like this:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'your_form_name') {
        //do what ever you want
        //$form is an array of form elements, to delete some of them you can just do:
        unset($form['your-element-name']);
        //or and I think it is more "drupal way" to do things you can hide an element using hide function, e.g.:
        hide($form['account']);
    }
}


How do I change the default country on the billing address form in Commerce 2?

You need to edit the form display for the Customer Profile Type.

You can find it in the Admin menu under "Users", or go directly there by this path:

/admin/config/people/profiles/manage/customer/form-display

Then, on the widget for the address field, click the gear to set the default country.


How to disable links for anonymous users for SOME, but not all link items?

I would create a view of the videos and control access by role.  if you need control at the field level, I'm sure there is a module for that or you can use a field template.


How to group view by field and display row results below?

What you're trying to achieve isn't grouping by a field, it is displaying the same node list twice, showing different node information in the two instances.

You can achieve it by creating two Displays in your Views where one is showing only Page Type field, and the other is showing Title and field_description while sharing the same Filters.

If your original View is a Page Display, it makes sense to use Attachment Display for the other. You adjust the Attachment to appear Before or After the other Display results, depending on which you created first. You could also make one or both of them Block Displays and place them one below the other in the Content region of your theme.

You could also render one View Display into another Display Header, with the help of an additional module Views Field View.

Your HTML won't be exactly the same as in your question, but it will be close enough, and you can override the templates in your theme for those particular views displays to achieve exactly the output you want. Attachment views usually show with their own class and view-rows outside the .views-content of the Display they're attached to, but if you really need to you can override them and set your own classes.

Drawing from Drupal 7 solution

I posted an answer to a similar question for Drupal 7: Filter a view by clicking on a link on another view. It doesn't completely mirror to D8 but with Better Exposed filters you can make an exposed filter behave similar to tabs, if you use Autosubmit optin and hide the Submit button.

Taxonomy summary through a Contextual filter

One additional way of listing only the terms used on nodes in Views results is by creating a Summary through a Contextual filter.

On your Content Views Page add a Relationship to the Page Type field, you may require it since none of your results will have it empty.
Then add a Contextual filter Term ID from Taxonomy term Category and set it to use the Relationship from above, and these options:
When the filter value is NOT in the URL
Display a summary
Descending
Number of records
Base path (if this is not the first Page Display in your Views)
Add Attachment View Display to this Page, keep all the options the same as in Page, only override the Contextual filter and remove it from Attachment.

This way you get the original list of nodes, after the terms relevant to the results.

The terms are already sorted by the number of results tagged with it. To make the nodes in the Attachment sort the same way use Aggregation on it.


How can I build a redirect from submitted form values?

Okay I have figured it out by myself.

Here is what I needed:

function form_findYourCity_submit($form, &$form_state) {

  $city = $form_state['values']['city_name'];

  $form_state['redirect'] = [
    'showCity',
    [
      'query' => [
        'city' => $city,
      ],
    ],
  ];

}


Drupal 7 custom module menu hook is not working

You need to change access arguments with access callback.

Replace following code:

$items['mydesk'] =  array(
  'title' => 'My Desk' ,
  'page callback' => 'show_mydesk',
  'access arguments' => TRUE,
);

With:

$items['mydesk'] =  array(
  'title' => 'My Desk' ,
  'page callback' => 'show_mydesk',
  'access callback' => TRUE,
);


How do I integrate the Color module in my theme?

There's actually a video on YouTube about how to do this in Bootstrap.  There's also a more general video for other themes by the same person.

You'll need to use a LESS or SASS subtheme; the most basic subtheme that just uses regular CSS will not work because the Color module will change the values of the variables.

You will also need a way to compile the LESS/SASS on the server that you use the Color module on, so if you plan to make adjustments on your production server, you will need something like the LESS module, which does not yet have an official release for Drupal 8 (might still work, needs testing).

You can also find a feature request on drupal.org for putting this directly into Bootstrap, but it hasn't made any progress in the past couple years.


While relation can handle multiple entity types in a single relation type it can't reference Views. It's a challenging problem for two reasons: the view_id is a string unlike say nid so a database schema made to refer numeric IDs won't be able to copy with views. Also, views is not stored in the database necessarily so the utility of such reference is limited.

It should be possible to maintain an entity in the database that has a numeric ID and all it contains is the Views ID. Your only problem becomes when someone changes the machine of a view that is maintained in code -- how do you plan to be notified of such a thing when it happens outside of Drupal?


Passing path arguments to a form builder

it's clearly impossible to add extra arguments to an inherited function signature

Not true - adding extra arguments to a function signature is one of the fundamental reasons that inheritance exists in OO.

You literally just need to add your arguments to the function signature to make this work:

public function buildForm(array $form, FormStateInterface $form_state, $arg1, $arg2) {
    // You have $arg1 and $arg2 available
}

You could do something more fancy and get typed data by using parameter upcasting, otherwise you'll get the args as strings.

Examples here.


You can maintain a weight field with list option enabled for your content type and sort your view from your weight(an integer). In views sort criteria section put the weight criteria top if there are any others. Same answer I gave here


how to use data of a text list field to draw a canvas image?

the answer is jQuery. The comment above written by burnsjeremy

'I guess you need to get the value in the browser on the client side so you would need to use jQuery (you can pass the value from the backend '

thanks, burnsjeremy


How do I keep the trail for the breadcrumbs till the specific nodes?

Breadcrumbs can sometimes be a bit confusing. In my experience the breadcrumb never behaves 100% as you would want it to behave, if you use it as it comes 'out of the box'.

Luckily also other people got annoyed be the standard breadcrumb (mis-)behaviour so over the years a sea of breadcrumb related modules found its way to drupals module collection. Here is an overview / comparison with some 10-15 modules listed. Maybe Breadcrumbs by Path could suit your needs…


A large amount of Tokens slows down everything - Placeholder Tokens

You can find some solutions for such a problem on Node references + Entity Tokens creates HUGE Token Tree UI table HTML.

Using the Token tweaks module also helps. I've tried and it works fine.

  Provides tweaks for tokens (mostly to improve performance)

  Disable token types or specific tokens.
  Modify the default depth limit for the token tree UI.


How to get Panels to pass a correct date to Views (D7, Views/Panels3)

After struggling for some time, I've still not found any way that works via context from Panels. Other people have said Panels values were determined by the "token" content display mode, but that isn't the case, at least with dates. Of course you can put the value in the URL and have Views grab it there, but for my use that wasn't appropriate. It also seems more fragile since it makes all content dependent on the path structure.

The best option I found was setting the "Argument Input" on the View to "Input on Pane Config". Then in the Panel Pane, use keyword/token substitution. I created a custom date & time formatter that is CCYY-MM-DD, called "date only", and set the Panel option to "%node:field-my-date-field:value:date_only". That grabs just the first value from a date range. For a field without range, "%node:field-my-date-field:date_only" works.


If this is a file field attached to an entity, and not (for example) a managed_file element type, then the actual <input> element is contained further down the render array. At the moment you're probably attaching the JS to the wrong element (a container rather than the input).

Try something like this instead:

/**
* Implements hook_form_alter()
*/
function my_module_form_alter(&$form, &$form_state, $form_id) {
  ...
  case 'my_form_node_form': {
    $form['my_file_field'][LANGUAGE_NONE][0]['fid']['#states'] = array(
      'visible' => array(
        ':input[id="my_id"]' => array('value' => 'my_value'),
      ),
    );
  }
}


How do I make a link to a flag edit page?

I'm not sure about any view field for an edit link, but you can link to the flag's edit screen, like most entities, in a number of ways.
Looking at the module's flag.routing.yml file, we see the edit route defined like:
entity.flag.edit_form:
  path: '/admin/structure/flags/manage/{flag}'
  defaults:
    _entity_form: flag.edit
    _title: 'Edit Flag'
  requirements:
    _entity_access: 'flag.update'

The flag argument here is for the flag's id.
You can build out the link to the flag manually, e.g.
Edit MY FLAG

Or if you're working with twig, e.g. rewriting a view's field, make sure you're also including the flag's id in the view then rewrite doing something like:
{{ "Edit"|t }}

Or you can use PHP to build the url directly from the route. It's recommended to use one of the following methods if you're working in PHP.
To get just the url text or object in PHP, use Url::fromRoute():
use \Drupal\Core\Url;

$my_flag_url_object = Url::fromRoute('entity.flag.edit_form', ['flag' => MY_FLAG_ID]);
// $my_flag_url_string returns something like "/admin/structure/flags/manage/123"
$my_flag_url_string = $my_flag_url_object->toString();

To build the whole link in PHP, use Link::createFromRoute():
use \Drupal\core\Link;

$my_flag_edit_link = Link::createFromRoute('MY FLAG EDIT TEXT', 'entity.flag.edit_form', ['flag' => MY_FLAG_ID]);


Anonymouse users can't see Openlayers Data Overlay

The pages were cached for anonymous users. I went into Performance -> Caching  and cleared the caches and it worked. I had cleared my own cache but not on the site.


A commerce fees rule works fine, but is giving the warnings in the log

You should add a data_exists to ensure that the delta/label you're trying to access actually exists. It looks like line-item-label is a custom property.


I don't know how comfortable you are with code. I would suggest writing an update hook in a custom module. Something like:

MYMODULE_update_8100(&$sandbox) {
  // On the initial run, set up the update.
  if (empty($sandbox)) {
    // Get all user ids.
    $sandbox['items'] = \Drupal::entityQuery('user')
      ->accessCheck(FALSE)
      ->execute();
    $sandbox['max'] = count($sandbox['items']);

    if (!$sandbox['max']) {
      // Prevent division by zero if there are no users.
      $sandbox['#finished'] = 1;
      return;
    }
  }

  $iteration = 0;
  while ($iteration < 25 && $sandbox['items']) {
    $iteration ++;

    // Resave each user.
    \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load(end($sandbox['items']))
      ->save();

    // Remove the end of the items list when the item has finished
    // processing.
    array_pop($sandbox['items']);
  }

  // Update the completion status as a number between 0 and 1.
  $sandbox['#finished'] = ($sandbox['max'] - count($sandbox['items']) / $sandbox['max'];
}

See hook_update_N for more information.


Use wget to mirror a site to a static site

It appears that the issue had to do with the fact that a "Logout" block was in the header of the main site. As a result, when wget went to pull things down, it would actually go to the logout link, and thus the rest of the files would either display a login screen or wouldn't be downloaded. By disabling the logout block OR adding --reject logout to my wget command, it seems to have fixed the issue and now the full directory structure is being downloaded. The command I ended up using was:

wget --mirror -w 2 -p --convert-links --load-cookies cookies.txt -e robots=off --reject logout https://url.org/user


Change frontpage pagination to use a more/previous style

You just need to use theme_pager()

Place this function in your template.php file and clear theme registry:

/**
 * Implementation of HOOK_pager().
 * $variables: An associative array containing:
 *  tags: An array of labels for the controls in the pager.
 *  element: An optional integer to distinguish between multiple pagers on one page.
 *  parameters: An associative array of query string parameters to append to the pager links.
 *  quantity: The number of pages in the list.
 */
function YOURTHEME_pager($variables) {
  $tags = $variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $quantity = $variables['quantity'];
  global $pager_page_array, $pager_total;

  $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹ Previous Posts')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
  $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('More Posts ›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));

  if ($pager_total[$element] > 1) {

    // PREVIOUS
    if ($li_previous) {
      $items[] = array(
        'class' => array('pager-previous'),
        'data' => $li_previous,
      );
    }

    // NEXT
    if ($li_next) {
      $items[] = array(
        'class' => array('pager-next'),
        'data' => $li_next,
      );
    }

    // OUTPUT
    return '
' . t('Pages') . '
' . theme('item_list', array(
      'items' => $items,
      'attributes' => array('class' => array('pager')),
    ));
  }
}


I found a solution for this case, sharing so that anyone who need similar solution can use it.

Anyone who has similar issue can use the solution below:

<?php
    $comment = comment_load($comment_id); // $comment_id = cid of comment whose edit form need to be open

    module_load_include('inc', 'comment', 'comment.pages');
    $form = drupal_get_form('comment_form', $comment);

    return drupal_render($form);
?>


You can use Entity view modes to create two displays for an entity.

  The Drupal 7 successor to Build modes which will allow administrators
  to define custom view modes for entities.

I'd probably then use Panels to output the product displays (but that's because I'd already be using Panels). Most likely two variants of the node_view page that both check user role. If a logged in user is discovered, then use a variant that uses view mode X, if the user is anonymous then use view mode Y.


You can use a the node or article URL as it's Unique and a lot of feeds use it with no issues at all


How to access field values from an entity reference field in a custom module?

$form['card_on_file' ] = array(
  '#type' => 'entityreference',
  '#title' => t ('Credit Card'),
  '#era_entity_type' => 'node', // Mandatory
  '#era_bundles' => array(credit_card ), // Optional (Any bundle by default).
  '#era_cardinality' => 5, // Optional (1 By default).
  '#required' => TRUE,
) ;

the warning corresponds to this replace this code:

'#era_bundles' => array(credit_card ), // Optional (Any bundle by default).

with

'#era_bundles' => array('credit_card'),

Link: https://api.drupal.org/api/drupal/includes!common.inc/function/entity_load/7

$ids = array();

get $ids from $form_state['values'] of submit handler function.

use entity_load('credit_card', $ids);


hook_ENTITY_TYPE_view() only fires once on cache rebuild?

Yes, it is. Entities are render cached. If your output is dynamic/depends on something, you need to provide the necessary cache contexts, use placeholders or something like that.

See https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays.

If it's just about debugging locally, there is an example.settings.local.php file that has a example lines to disable those caches, but make sure you always test it with enabled caches before deploying.


"Valid date is required for date_1" error while using drupal_form_submit()

I was facing similar kind of problem with drupal_form_submit.

After spending too much time following solution is working for me

    $datetime = $source_node->field_date_1['und'][0]['value'] ;
    $form_state['values']['field_date_1']['und'][0]['value'] = array(
      'date' => date('d/m/Y', strtotime($datetime)),
      'time' => date('h:ia', strtotime($datetime)),
    );

Hope it will help someone


Transfer (export/import) url aliases and menu links automatically

A good idea for solving this issue (at least until a more definite solution is implemented, with uuid etc.) is described in this article:
http://margotskapacs.com/2014/04/solving-menu-import-issue-when-featuring-sample-data-in-drupal/

This is a related issue: data export import module how to keep alias drupal


Set value to specific custom theme setting

Drupal 8 use configuration to store configuration settings. You can follow document. And snippet code to set new value for custom theme(replace theme_name with your theme name).

$config = \Drupal::service('config.factory')->getEditable('theme_name.settings');
$config->set('variable', 'value')->save();


How to make the content fills the space after the sidebar ends in a drupal site?

This really boils down to what theme your using, and how your content is laid out. But it should be doable with CSS if your theme is laid out correctly. Let's take Bartik for example (one of Drupal's default themes). Simply changing the sidebar-first class to float left and changing the float of the content to none will give you something like this:

And here's a really basic version the same idea running on JSfiddle.

The basic answer of it is, yes, it can be done, but you need to do it through the theme and css. Depending on where blocks are placed, the css already in place on your theme, how you go about doing it might change, but the answer is you need to use css.


Files attached to nodes are never deleted from server even after they're removed from the node (and that edit is saved), Drupal 7

I got it!  It's a revisions thing.  I guess it makes sense.  If you have revisions enabled for that content type, it keeps all your old files on the server (associated with old revisions), so replacing a file definitely is harder.  If you try to remove it and add it again to the node, the name/link is updated, as I mentioned in my question.  Since a file with that name is kept on the server and there is a name duplication, it adds those "_0", "_1" etc suffixes to future uploaded versions of that file's name.

I understand why this is happening though, since the whole point of revisioning is being able to revert to any past version of the page.

The work-around is that you can actually delete the old revision from the 'Revision' or 'Moderate' tab (if using Workbench Moderation) that contained the file you're trying to replace.  Then upload it again, and the name should then match without you having to go back and edit any links pointing to that file.

Hope that makes sense and that it helps somebody else too!


How do I re-arrange the $node->taxonomy array back into a hierarchical tree?

I don't know of an API function that can do this but the following code should help:

$tid = 4; // Your term id

// Grab all of the parents of this term (including the term itself)
// in reverse order.
$parents = array_reverse(taxonomy_get_parents_all($tid));

$tree = array();

// Get a reference to the root of the array. This reference will be updated
// in each iteration of the loop to refer to the array of children added to
// the term.
$ref = &$tree;
foreach ($parents as $term) {
  // Add the current term to the relevant root/children array.
  $ref[$term->tid] = $term;

  // If the current term is NOT the original child term, we add an array of
  // children to the term and update the array reference to point to it.
  if ($term->tid != $tid) {
    $term->children = array();
    $ref = &$term->children;
  }
}

By the time that loop has run the $tree variable will be a hierarchical representation of the original term's parents, with each child term in the children key of it's parent term object.

I've only tested this on terms that have a single parent; if you've got terms with multiple parents I think you'll struggle to get this to work.


Adding the button implemented from "Printer, e-mail and PDF versions" in node.tpl.php

In the administration area, disable the insertion of the link, then add the following (depending on which modules you use) to your node.tpl.php:

Print: <?php l('Print', 'print/'.$node->nid); ?>
Print to PDF: <?php l('PDF version', 'printpdf/'.$node->nid); ?>
Send by email: <?php l('Send by email', 'printmail/'.$node->nid); ?>

However given you have your own theme template, it could be better to just modify the CSS applied to the print link(s) to be in a different location on screen.


Using views_embed_views() to generate content for an email message. How can I get it to insert images and urls correctly for this purpose?

Use hook_mail and drupal_mail to send out e-mail. drupal_mail at the place you want to send to mail, eg. hook_cron. And hook_mail to set the content. Use drupal_mail to send parameters to hook_mail.

As for the images, make sure that you use absolute url's in views (setting on the image field).


xmlrpc() error: (-1001) unable to parse URL during Drush command

Turns out the issue was the APC module. After some testing I was able to isolate the issue during cache clear.

[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
xmlrpc() error: (-1001) unable to parse URL                                                                                [error]
[shawnconn@host www]$ drush dis apc
The following extensions will be disabled: apc
Do you really want to continue? (y/n): y
apc was disabled successfully.                                                                                [ok]
You need to enable the APC module for remote cache clearing to work. Run drush pm-enable apc.                                                                                [error]
[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
[shawnconn@host www]$


Organic Groups - How to view articles in the context of the group

You can adjust Group context detection at admin/config/group/context when you have Organic groups context enabled. This will add the appropriate css classes in the body element, which will allow you to theme the rest of the page.


How to use ctools_ajax_command_redirect with $_GET parameters

I finally figured it

Following is the sample usage with POST param param1 with value as value1

ctools_ajax_command_redirect('url_path_without_base_url',0,array('query'=>array('param1'=>'value1')));


If you can find the file field in question in your database.

Export it as csv.
Use find and replace with excel, save.
Import it back in.
Clear the cache.


Put dsm() to the end of code...

if ($form_id == "privatemsg_new") {
  $form['recipient']['#type'] = 'select';
  $form['recipient']['#title'] = 'Choose Recipient';
  unset($form['recipient']['#autocomplete_path']);
  dsm($form);
}


If I understand your scenario correctly, have a look at the Taxonomy Menu module.  This is what I use to create dynamic views, where the display is dependent on the menu item clicked.
(The menu passes in that value -- e.g., city name -- as an Argument/Contextual-Filter.)

Taxonomy Menu:

Custom Menu per vocabulary.
Uses the default taxonomy term path or custom paths.
Integrate with Views.
Integrate with Pathauto: use URL/path aliases.
Does not interfere with other menu modules.


"Fetch entity by property" for multi-value term reference field

At last, I solved this problem using Views Rules module, just set the Data type of the Rules parameters (providing to contextual filter) to Text. Then add a view loop in the rule action. A view's multi-value field contextual filter can have only one value.


Block defined in code not appearing in admin interface

I had exactly the same thing:  dpm() showing me my block on admin/structure/block, but no block actually appearing in the admin.  Disabling, uninstalling and re-enabling the module where I defined my block then clearing cache worked for me.


How to relate an image to an article when posting the article in REST API

See https://www.drupal.org/project/drupal/issues/1927648, this is not supported yet in core.

You can try using https://www.drupal.org/project/better_normalizers to send it base64 encoded instead.