How to send new content notifications based on taxonomy selection in user profiles?

You may want to give it a try to process the results of a VBO enabled view via Rules, as detailed below.

Step 1 - make it work for a single (1st) term

Remark: this is an intermediate step to prepare a prototype for Step 2 (if you have enough Rules experience, just start straight from Step 2).

Create a rule like so:

Rules Event: After saving a node of type "Opportunity"
Rules Condition: Check if the node was tagged with your 1st term, using "List contains item" (and the list to be checked being the field of the node that contains the interest categories).
Rules Actions:

Load the VBO list of users that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results. Within this Rules Action, you then send a notification to the user being processed.

Some more details about the VBO-view you'd have to create for this:

The view should list all users who have some specific term selected (which corresponds to the 1st term).
It should include an appropriate filter for the term ID to be processed.
It should have exactly 1 result (row) for each user to be notified.
One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

Step 2 - make it work for all terms (not just the 1st term)

Since the Opportunity may have been tagged with multiple terms, you need to improve the solution from Step 1 to handle all the terms (not just the 1st one). To do so, these are the steps to improve the rule from Step 1:

Add a "Rules Loop" as your very first Rules Action, to iterate over each term that the Opportunity was tagged with.
For each term in this iteration, perform these sub-items:

check which term you're actually processing. This check is similar to the Rules Condition from Step 1, but you should use the Conditional Rules module to be able to include such Rules Condition as part of a Rules Action. BTW you can either use IF/THEN constructs, or CASE/WHEN constructs.
If the check succeeds, then perform a Rules Action similar to the Rules Action from Step 1.

Remove the Rules Condition from Step 1 (it is now included via the previous check using Conditional Rules).


How to make Expose filter of Author Id from autocomplete to select list?

Add a custom module with the help of https://stackoverflow.com/a/16517124 on the same post and solved my issue.


How do I get the current path alias or path?

Some of the other answers were only correct during previous alpha/beta versions of Drupal 8, or seemed to be incomplete. As of beta7 (and hopefully permanently), the following rules should apply:

For the current raw path (the un-aliased Drupal path):

$current_path = \Drupal::service('path.current')->getPath();

For the current URI, which is pretty-much a direct representation of the request (it may even include a query string):

$current_uri = \Drupal::request()->getRequestUri();

There is of course no guarantee that this $current_uri value will give you an alias, even if one is available for the request, as it only represents what the user has requested. So to strictly do what you are asking about (get alias if available, and path if not) I think you could do:

$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

Of course depending on the type of processing you are doing it may be best to be working with routes instead of paths, but I suppose that's a whole other topic.


If your module doesn't need to implement any other hooks, then yep, hook_views_api() is all you need in your .module file.

As long as you provide the right path in hook_views_api(), Views will know where to look and will dynamically include the files when they're needed.

Usually you need to put files[] = mymodule.FILENAME.inc in your module's .info file for the dynamic code registry to pick it up, but from the looks of it that isn't the case for Views.

If you're looking for some code examples for this, take a look at the Administration Views module; it's .module file contains only hook_views_api() as well (and it works), so you can be confident you're doing the right thing.


How to get current path for user profile field?

One way to go about this is a theme override of the user profile page:

Copy over core/modules/user/templates/user.html.twig over to your theme's template directory.
Have your theme implement template_preprocess_user() in your MYTHEME.theme file to inject a custom URL variable.
Modify your theme's user.html.twig to contain the HTML for the link.

For example, in your MYTHEME.theme:

use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Drupal\Core\Url;

/**
 * Implements hook_preprocess_user() for user.html.twig.
 */
function MYTHEME_preprocess_user(&$variables) {
  if (\Drupal::request()->get(RouteObjectInterface::ROUTE_NAME) == 'entity.user.canonical') {
    $variables['view_page_path'] = Url::fromUri('base:' . \Drupal::service('path.current')->getPath())->toString() . '/view-page';
  }
}

In your user.html.twig:

{% if view_page_path %}
  MY VIEW PAGE
{% endif %}


How can I load a theme template to render $submitted

Well, what you're looking for is hook_theme. With hook_theme you can declare new theme implementations, which can be either functions or templates. I'll stick with templates for this answer. Just define it in YOURTHEME's template.php file:

function YOURTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'YTsubmitted' => array(
      'template' => 'YTsubmitted',
      'variables' => array('whom' => NULL, 'when' => NULL),
    ),
  )
};

I'm calling the theme hook YTsubmitted and the template file  YTsubmitted. Those names don't need to be the same, but I'm prefixing to avoid collisions. Now, whenever you call theme('YTsubmitted'), Drupal will look for YTsubmitted.tpl.php in your theme and use it for rendering. You can pass variables to it when calling, just like theme('YTsubmitted', array('whom' => 'Jake the dog')). Variables will default to values set when defining the theme hook in hook_theme (NULL in our example). But you can also preprocess variables:

function YOURTHEME_preprocess_ytsubmitted(&$vars, $hook) {
  $vars['extra'] = 'Mathematical!';
}

And now you can use it in your template file (YTsubmitted.tpl.php):

Submitted by <?php print $whom ?> right after <?php print $when ?>. <?php print $extra ?>!

That's precisely how Drupal sets several of the templates and its variables. For instance, node.tpl.php will print the $submitted variable, which can be redefined in your template.php file:

function YOURTHEME_preprocess_node(&$vars, $hook) {
  $vars['submitted'] = theme('YTsubmitted', array('whom' => 'Finn the human'));
}

AAAaaand you're done.


you could use string overrides module or use hook:

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


Views 3, 2 different node types, filtered by the same contextual filter

If field_nodea_taxonomy and field_nodeb_taxonomy use the same taxonomy vocabulary, this problem can be addressed differently with a shared field.

I generally define a single shared field for each taxonomy vocabulary, and use it in every content type where it's needed (e.g., nodea and nodeb). If your requirements permit you to use this approach, your problem goes away, since a term filter on that single field will work for all content types.


module_load_include fails on WebTestCase post

I figured it out for myself. This is an issue with SimpleTest. DrupalWebTestCase stores emails sent in the database, in a varialbe drupal_test_email_collector. If an email sent during a test case includes parameters, the parameters are saved. My parameters were classes. bootstrap.inc attempts to load and cache variables before modules are loaded. In restoring the emails with parameters, it was attempting to autoload the relevant class, and that was causing the crash.

This could happen, in principle, in other situations - any time a class got saved to a variable, though I have only encountered it with this test setup.


Create and use a custom Account Email Template

Specifically, your code is modifying the AccountSettingsForm, which is part of the core Drupal "user" module.
If you look at the source code for that form, you will see that like all forms in Drupal, it has both a buildForm() method and a submitForm() method. The problem with your code is that you've added form elements to the form array created by default in buildForm(), but you HAVEN'T added any code to process those new form elements and save the entered data, which is normally done in submitForm(). If you create new form elements in an existing form, you are responsible for processing the input and saving the entered values. Your custom module is the only thing that knows about those new elements, and your custom module is responsible for storing that data.
Let's look at one of the other elements defined in AccountSettingsForm, for example the email_admin_created details element which contains a user_mail_register_admin_created_subject and a user_mail_register_admin_created_body. It looks like you copied this code and changed the names for your own purpose, which is a good way to approach this. But if you search AccountSettingsForm, you will see that those form elements are also processed and saved in submitForm(), and you haven't added any new equivalent code for your new form elements.
The key then is to write your own function to execute on form submit, and in that function you need to save the values entered into your custom form elements. The way to tell Drupal about your custom submit function is to add the following at the end of your hook_form_alter():
$form['actions']['submit']['#submit'][] = 'my_module_email_course_link_submit';

Then add your function to my_module.module:
/**
 * Submit callback to  process and save email_course_link form elements.
 */
function my_module_email_course_link_submit(array $form, FormStateInterface $form_state) {
  $entered_body_value = $form_state->getValue('user_mail_course_link_body');
  $entered_subject_value = $form_state->getValue('user_mail_course_link_subject');

  // Save $entered_body_value and $entered_subject_value somewhere.
  // For example, in a database table created by your module, or
  // in a config object created by your module.
  // Where and how you save it is up to you.
}

You will also have to add use Drupal\Core\Form\FormStateInterface; at the top of my_module.module.
When you look at AccountSettingsForm you will see the user module saves form elements in the user.settings and user.mail configs. DON'T use those configs to store your custom data - define your own custom config if you want to store your own custom data in a configuration object.


Can I remove/hide the "Provide a Menu Link" checkbox when creating new content type?

In drupal 7, go to edit your content type and in the tabs at the bottom there should be 'menu settings'. If none of the checkboxes under 'Available menus' are checked, then the option of creating a menu item is not displayed when creating content of that type.


How to add some javascript in a form using form API?

drupal_add_js() is for adding script tags to the page.
It doesn't go in a form element.

 drupal_add_js('alert("Hello!")', 'inline');

would go by itself on a line. This would add that javascript to the page, so when the page loads you would get a pop-up that says "Hello".

and/or to add markup to the page you would do this:

$form['target'] = array(
  '#prefix' => '
',
  '#value' => t('Hello'),
  '#suffix' => '
'
);

Which would add the text "Hello" to the form in the newuser div.


How to make views slideshow, shows more items per page than one

In Views Slideshow 7.x-3.0, you can find this option by selecting slideshow as your format and then clicking on settings. From there, you need to find the Action section and check "View Action Advanced Options", there you can choose how many items to display.


The second parameter of _locale_import_read_po() is a Drupal file object, which in Drupal 7 is simply a stdClass object.

The quicker way to use that function and pass a file object as it expects is using code similar to the following one.

 $po_files = file_scan_directory('./', '^translation\.po$', array('recurse' => FALSE));
 if (count($po_files)) {
   require_once DRUPAL_ROOT . '/includes/locale.inc';
   $po_file = reset($po_files);
   _locale_import_read_po('db-store', $po_file);
 }

Notice that the second argument of file_scan_directory() is a preg_match() regular expression, not a filename.

Using that code, you don't need to save the file using the file API, which is essentially useless, since there is already a file in the file system.
file_save() stores the file in the database; for a file that is used for a single operation like that, it's not necessary.

I used st() as example for writing the code I shown in this answer.

You could also make the code I show more generic to accept a regular expression and a directory name, and use it to load more files.

function mymodule_import_translations($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern, array('recurse' => FALSE));
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';
    foreach ($po_files as $po_file) {
      _locale_import_read_po('db-store', $po_file);
    }
  }
}


This is still a view. The "Watchdog" view. Go to /admin/structure/views/view/watchdog and edit the date format. That's all.


How to change order currency in cart/checkout page?

You cannot directly manipulate the order total like this, as it gets recalculated based on its line items' prices each cart refresh. (That happens on every pageload in checkout and however you've configured it for other routes.)

You should look into the Commerce Multicurrency module instead or else configure your pricing rules / otherwise hook into product sell price calculation to change the currency on the order items (and shipping if present). If those are all the same target currency, the order total will use it, too.


Parse feed items into nodes, but also get full html from link by scraping the site

This doesn't seem possible at the moment, so I used Yahoo Pipes to create a new rss feed based on the original scraped the full page for each rss item and sustituted the description with the content of the full article.


How does the Drupal LDAP module manage passwords?

This is all explained in the documentation and help text provided in the admin screens of the module.

Drupal supports multiple login sources. When a user logs in an entry for the type of login used for the person is stored in user_auth as an example.

By default LDAP does not store for example the AD password of the user within Drupal. It stores a dummy password and passes login info to LDAP from the login form upon a login attempt.

If you configure LDAP to sync drupal account information to and from Drupal then Drupal may store the password your LDAP accounts -- but this depends on how you've configured your LDAP service, and how you want the drupal ldap module to interact with it.


How can I include user pictures in e-mail notifications sent by the privatemsg module?

One way you could do this (which is what I do on a couple sites), is to implement hook_privatemsg_message_insert() in a custom module. Turn off the privatemsg module emails or any rules-generated emails, and instead write a custom bit of code that sends the private message.

In my case, I needed to do a few other customizations, but at its simplest, you can get a profile picture URL by loading the user $account from $message->author->uid.

A quick example:

<?php
/**
 * Implements hook_privatemsg_message_insert().
 */
function custom_privatemsg_message_insert($message) {
  global $base_url;

  // Get the account from which message was sent.
  $account_from = user_load($message->author->uid);

  // Get the person to whom the message is being sent (I only handle one).
  foreach ($message->recipients as $key => $recipient) {
    $account_to = $recipient;
    continue;
  }

  // Set up variables for our message body.
  $variables = array(
    'from' => $account_from->realname,
    'link' => l('Click here to view/reply to this message', $base_url . '/messages/view/' . $message->thread_id, array('external' => TRUE)),
    'message' => check_markup($message->body, $message->format),
  );

  // Print the message body using a custom theme function. Because email clients
  // require obnoxious markup, it's best to use a theme function or template...
  $body = theme('custom_private_message', $variables);
  $body_plain = strip_tags($body);

  $subject = t('New Private Message: ') . $message->subject;
  $email_to = $account_to;
  $email_from = $account_from->realname . ' <' . $account_from->mail . '>';

  // Now, use whatever mechanism you want to send the actual email.
}
?>


How to force to upload a image with exact sizes?

This is mostly based on memory, so some details might be off.

The image field widget assumes that downsizing an image is a valid action in all cases, so you'll need to override it.

Implementing your own field widget requires a little bit of fiddling with the field api, but since your change is fairly small, you should be able to just wrap a number of image field function and add a single validation step.

Since image field already is mostly a wrapper around a file field, looking at the image field itself for how to implement the above is probably a good start.


I've tested the module and tested.It works. Seems you missed the pre-configured view provided by this module.

You can find it at http://www.example.com/jssor_jssor. Find the jssor views in the view list. You can do slider settings in the view itself.

Seems you've selected 'Content' instead of Jssor in view. If you select 'content' it display normal slider. So in order to display text on slider make sure to add Jssor in show under FORMAT options.


Warning: unlink() expects parameter 2 to be resource, string given in drupal_unlink() (line 2194 of /includes/file.inc)

probably a typo ',' -> '.'
drupal_unlink("public:///rackspace/" . $final_image_name_path);


Change max length of signature field to more than 255 characters

In a mysql database varchar can only store 255 characters.


You can't do this with CSS but you can do it without having to add another module.

If you want it exactly the same as default, but without the link, this would be it:

Just add this code to your template.php file in your theme (change YOURTHEME to be your theme name):

/**
 * Override or insert variables into the node template.
 */
function YOURTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->type == 'article') {
    // This will replace the user name link with the same text but without the
    // link.

    // Set the name to a formatted name that is safe for printing and
    // that won't break tables by being too long. Keep an unshortened,
    // unsanitized version, in case other preprocess functions want to implement
    // their own shortening logic or add markup. If they do so, they must ensure
    // that $variables['name'] is safe for printing.
    $name = format_username($node);
    if (drupal_strlen($name) > 20) {
      $name = drupal_substr($name, 0, 15) . '...';
    }
    $variables['name'] = $name;
    // Display post information only on certain node types.
    if (variable_get('node_submitted_' . $node->type, TRUE)) {
      $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    }
  }
}

if YOURTHEME_preprocess_node() already exists in your theme just add this to it:

  $node = $variables['node'];

  if ($node->type == 'article') {
    // This will replace the user name link with the same text but without the
    // link.

    // Set the name to a formatted name that is safe for printing and
    // that won't break tables by being too long. Keep an unshortened,
    // unsanitized version, in case other preprocess functions want to implement
    // their own shortening logic or add markup. If they do so, they must ensure
    // that $variables['name'] is safe for printing.
    $name = format_username($node);
    if (drupal_strlen($name) > 20) {
      $name = drupal_substr($name, 0, 15) . '...';
    }
    $variables['name'] = $name;
    // Display post information only on certain node types.
    if (variable_get('node_submitted_' . $node->type, TRUE)) {
      $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
    }
  }


How to display value in View global text field if another field has specific value

You can use views conditional module.

  Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
  with fields in views


Is it a way to get know if more than one user edit the same node?

This is already built-in in Drupal 6 (and 7), in the function node_validate.

The relevant piece of code is reproduced below:

if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}

It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done.

The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.


From hook_node_submit():

  This hook is intended for adjusting non-field-related properties

I think the proper place for this will be hook_node_presave() . To change field there you need to set, for example:

$node->some_field_name[LANGUAGE_NONE][0]['value'] = 'your value';

If you want to set reference field then:

$node->some_reference_field_name[LANGUAGE_NONE][0]['target_id'] = 'your value';

You may also want to consider using computed_field module for this.


programmatically add class name to fields

Alter the login form using hook_form_alter(). And use #attributes to add custom classes to fields.


The available variables differ between the page.tpl.php versus the node.tpl.php (see the top of each of those links for documentation of the default variables).

If the default variables in the templates don't meet your needs, you can customize them using preprocess functions. See the documentation for template_preprocess_page to get an idea of how the variables get added. NodeOne has a screencast on "Providing new template variables" that might also be helpful.


Full website translate in multilingual website

You need to enable the Content Translation module, and then, in the content type settings, set the content types to translatable. Then, you can translate content. You do that by creating translations though, in the ui, not in the interface translation ui. So, you translate content, not strings.

https://www.drupal.org/documentation/modules/translation


Drupal 6 - Build Menu "...not available at this time." Issue

Since you are saying ../admin/build/menu , I assume that you are using Drupal6.

Step 1: Navigate to example.com/admin/user/permissions

Step 2: Search for menu module and give permission for your user roles as required.


How can I add the full HTML format, and attach CKEditor to it?

Installation / Configuration

Unzip the module files to the "sites/all/modules" directory. It should now
      contain a "ckeditor" directory.
Download standalone CKEditor from http://ckeditor.com/download. Unzip the
      contents of the "ckeditor" directory from the installation package to the
      "sites/all/modules/ckeditor/ckeditor" (or "sites/all/libraries/ckeditor") directory.
      Note: you can skip uploading the "_samples" and "_source" folders.
Enable the module in the "Administration panel > Modules > User Interface" section.
Grant permissions for using CKEditor in the
      "Administration panel > People > Permissions" section.
      Note: In order to enable the file browser, refer to the
            "Installing CKFinder" section.
Adjust CKEditor profiles in the
      "Administration panel > Configuration > Content Authoring > CKEditor" section.
      Profiles determine which options are available to users based on the input format system.
For the Rich Text Editing to work you also need to configure your filters
      for the users that may access Rich Text Editing.
      Either grant those users Full HTML access or use the following tags:

  <map> <area>

          <quote>

 <address>
       <embed> <object> <param>

      To make copying the list easier, below all tags were placed in one line:

  <map> <area>

           <quote>

 <address>   <embed> <object> <param>

      If you are going to use CKEditor with the Filtered HTML input format,
      please refer to the "HTML Filters and Inline Styling" section.
To have better control over line breaks, you may disable the line break converter
      for a given text format in the "Administration panel > Configuration > Content authoring > Text formats" section (recommended).
Modify the ckeditor.config.js file to adjust it to your needs (optional).
      Configuration options are described here:
      http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
      Developer's documentation for CKEditor:
      http://docs.cksource.com/CKEditor_3.x/Developers_Guide
      WARNING: Remember to clear the browser cache after you have modified any of the JavaScript files. If you skip this step, you may notice that the browser is ignoring your changes.


What is the ID or class for the Wizard Page name?

Each wizard page is rendered as details element.

Below is the Entity Print markup from the webform_example.module's 'Example: Wizard'.

<details
 class="webform-container webform-container-type-details js-form-wrapper form-wrapper"
 data-webform-element-id="example_wizard--information"
 id="example_wizard--information"
 open="open">
   <summary
     role="button"
     aria-controls="example_wizard--information"
     aria-expanded="true"
     aria-pressed="true">
     Your Information
     </summary>
   <div class="details-wrapper">
   ...
   </div>
</details>


How to make custom blocks print unsanitized markup

TWO solutions:

1.-in text formats, disable WYSYWIG in full-html format, you are looking HTML tags because of this.

2.-write your code in plain-text format, select 'plain-text' write code, when done, do choose full-html and save your block.

in other words, do not write code inside WYSYWIG.


How do I add attibution links to 'teaser thumbnails' in Drupal blog posts?

For D6, use the ImageField Extended module. It provides a very simple admin interface to give you a way of adding textfields, textareas, WYSIWYG textareas and checkboxes.


Making drupal_goto Ignore ?destination=foo

It's actually quite simple, just unset $_REQUEST['destination'] before you invoke drupal_goto().


You can try this:

<?php
function THEMENAME_preprocess_page(&$vars, $hook) {
    unset($vars['page']['content']['system_main']['default_message']);
}
?>


Look at the body tag of your theme. Some themes add classes to it indicating whether or not you are logged in.  If yours does, then you can do this via css by:

.logged-in #header
{
   background-color: #fff;
}

.not-logged-in #header
{
   background-color: #000;
}

If you don't have a body class that indicates logged in status, then you modify your page.tpl as user4035 suggested. There is no is_user_logged_in function.  Instead, it's

<?php
global $user;

if ( $user->uid ) {
  // Logged in user
}
else {
  // Not logged in
}
?>

Code Source - https://drupal.org/node/92218#comment-167984


It looks like the Content Taxonomy modules provides the ability to do this.

Without this, you'd have to implement hook_nodeapi('presave') and remove terms that don't exist yet.

Not even Drupal 7 seems to allow this without a contrib module, even though it does have specific edit terms permission for each vocabulary. Strange.


In Commerce 2, is it possible to have the product variation automatically created during product creation?

Update to Commerce 2.10.

Then, edit your product type and uncheck the Allow each product to have multiple variations checkbox. This will give you a Product information fieldset on the product add/edit form with the variation fields.


How can I map multiple fields to one 'parent' field?

See this example post on Select lists for content types:
How to have CCK "Select list" field on my content type?

you would just make the values for the list option as (value | display text):

500 | $500 - 5br/4ba
400 | $400 - 4br/3ba
350 | $350 - 4br/2ba
... 6 more options of whatever conditions ...
 25 | $25 - you sleep in the closet

This price field could allow up to 10 values if that's your limit.

Since the keys (values) of the prices are integers. You could SUM or Aggregate the values using Views if needed.


How to select a view inside a custom module form

As Views is a CTools Export UI based module, the correct way to load all views is by using the CTools Export function: ctool_export_crud_load_all()

Example

ctools_include('export');
$views = ctools_export_crud_load_all('views_view');
$options = array();
foreach ($views as $view_id => $view) {
  $options[$view_id] = $view->human_name;
}


Zen theme: understanding the zen grids design in _responsive.scss?

*Note that this is also inside the .region-sidebar-second container

Also of note, is that zen-grids actually has nothing to do with Drupal apart from being created by John Albin. The documentation can be found here.

Quick and dirty explanation:

--FROM HERE--

@include zen-nested-container(); // Since we're making every block in this region be      a grid item.

Ensures that the element (in this case, .region-sidebar-second) does not have any guttering (margins outside of the declared columns).

@include zen-clear();

This means that the sidebar region will have a clearfix applied

/* Apply the shared properties of grid items in a single, efficient ruleset. */
.block {
  @include zen-grid-item-base();
}

This applies a set of base styles to all blocks that will be in the sidebar. Things such as gutter width and box sizing. It takes something of an OOCSS approach in that it encourages DRY CSS (i.e. you don't need to apply the same CS to each block individually).

/* Span 1 column, starting in the 1st column from left. */
.block:nth-child(3n+1) {
  @include zen-grid-item(1, 1);
  @include zen-clear();
}

For 1st block in a group of three (3n+1), make the block 1 column wide, and place it in the first "column". Then assign a clearfix. I tend to read @include zen-clear() as new line.

/* Span 1 column, starting in the 2nd column from left. */
.block:nth-child(3n+2) {
  @include zen-grid-item(1, 2);
}

For 2nd block in a group of three (3n+1), make the block 1 column wide, and put it in the second "column"

/* Span 1 column, starting in the 3rd column from left. */
.block:nth-child(3n) {
  @include zen-grid-item(1, 3);
}

For every third block, make it 1 grid item wide, and put it in the 3rd "column"

--- TO HERE ---

Useful links:

Note: As of August 13th 2013 these all work fine, but they might go over the next few years. If they do go and you notice, please be a darling and remove/update them from this answer ;-)

CSS Tricks nth-child tester
Zen grids documentation
Nicole Sullivan's OOCSS code standards (trust me, if you're using SASS then you're going to want to read this).
Harry Robert's fantastic CSS guidelines.
The obligatory link to CSSWizardy that I attach to almost every SASS/CSS question I answer.


Custom entity form submit handler not being invoked

As discussed in slack, you misunderstood my comment. You should add it to the form-level submit callbacks if and only if that form has no button-level submit callbacks.

If it has, then you need to add yours there as well.


You don't have to prevent anything.

The use is just alias information. It doesn't care if the class that you're aliasing doesn't exist. As long as you don't actually use it, it won't fail.


How to speed up Drupal 7 compiling PHP to C++?

Following the chain from a comment on this great Wordpress tutorial on the new HHVM, I was led to Nick Veenhof's blog where he posted very recently about his unsuccessful efforts to get hiphop-php working with Drupal.

For what it's worth, the awesome maintainer of hiphop, Sara Goleman, said in the comments that she was interested in supporting Drupal and was going to try to reproduce the issue.

I'm working at building a vagrant VM to help reproduce the error and get everyone on the same page as easily as possible. The plan is to [use a patch that supposedly worked against Drupal 7.4, and hopefully move forward from that working state :)

https://github.com/patcon/vagrant-hiphop-drupal


How to display inbox messages and sent messages order by date - private message module

Have a look at the following issue: http://drupal.org/node/850932


hook_node_view() is not really suitable for loading anymore data. There is a hook_node_load() hook, which you'll receive an array of all nodes that site is about to load.
Note that this is only for loading, and that doesn't mean the user is on a node/XYZ page. You will probably need to add a URL argument match to make sure you load only the data related to the given node. Otherwise, pull all the information at once, and store them in each $node variable, which is passed by reference (all PHP 5 objects are).

The reason to use node_load hook over node_view hooks is that all modules implementing preprocess and view hooks now have access to this new piece of node. Otherwise, a hook_node_view is OK.

Secondly, you do not need to load them again in hook_preprocess_page at all. For Drupal 7 and later, hook_page_alter() is recommended. Since you store the data in hook_node_view/load hook, simply place the content in the regions you need. If this is theme specific, hook_preprocess_page() is better, but most of the contribs that take over entire page contents tend to use hook_preprocess_page(). Besides, you will have access to the renderable array because other preprocess functions are not executed at that moment.

You can get the current node like below (make sure you add arg() conditions to check the page router is node/%node)

$node = menu_get_object();

This $node object will contain the data you stored in the load/view hook. Make sure you pass the first argument to hook_page_alter(&$build) by reference, and place the content anywhere you want like god.


Programming a custom redirect in a Drupal Site

You could do something along the lines of this:

function MYMODULE_menu() {

  $items['MYMODULE/whattodo'] = array(
    'title' => 'Where should I go now, George',
    'page callback' => 'MYMODULE_whattodo',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function MYMODULE_whattodo() {

  $foo= // code to get the current time of day in whatever form you want that matches the switch cases below

  switch($foo) {
     case // morning:
        drupal_goto(// page for the morning);
        break;
     case // afternoon:
        drupal_goto(// page for the afternoon);
        break;
     case // evening:
        drupal_goto(// page for the evening);
        break;
  }
}

which means when a user went to www.mysite.com/MYMODULE/whattodo, they would be redirected to whatever page you set up via drupal_goto()


This seems like a perfect usecase for the Forena module. Forena is built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports (and/or charts). Various DBMSs are supported, such as Oracle, MS Sql, Postgress, SQLite, MySQL, any PDO compliant DBMS ... And there are quite some reasons for considering Forena.

Visit the Forena HowTos page for some links (near the bottom) to some live demo / showcase links, and experiment a bit with some of its demo samples.

Some of its features that I think will help to answer this question (and which only is a matter of minutes to deliver the features you're looking for):

Create a report about "products/services sold during last month, quantity and the price." Have a look at the "Northwind database" demo videos, which I tink are pretty close to what you're looking for. Such as these videos:

How to create a report/graph about Shipping summary (fast forward to about 4:15 if you're not interested in the SQL query prototyping part of it).
How to create Crosstab Tables and (related) charts (fast forward to about 2:15 if you're not interested in the SQL query prototyping part of it).
Various other Video demos and tutorials created in an earlier (7.x-3.x) release of Forena (which are mostly still accurate, but only using outdated Forena screens that have been enhanced in the 7.x-4.x version).

If you don't want to implement some validation about "... that the quantities for all products are set?" ... (or cannot do so for whatever reason), then you could create a report to find all cases that violate (as an alternative).
To create a report about "identify which users have entered the report and which users didn't do it?"

Disclosure: I'm a co-maintainer of Forena.


Considering entity reference fields in the following manner:

Program having an entity reference field pointing to the terms of program type vocabulary.
Registration having an entity reference field pointing to nodes of type Program.

To achieve what you want:

Create a view of content. Of type "Registration". Add required fields from registration content type
Add a relationship of type "Entity reference: referring entity" with field from #2 above.
This will enable you to add attributes/fields from the "Program" content type.
Add a relationship of "Entity reference: referring entity" with the field from #1 above (pointing to terms). Important: Use the earlier relationship in this new relationship (i.e. nested relationship).
This will let you add attributes/fields from the taxonomy terms.


Programatically create user that needs admin aproval

Step1

Not need to follow it compulsary

You don't need any third-party modules. Drupal core has the option to verify the email the user enters, and the option for the administrator user to approve the accounts users create. In Drupal 7, those settings are on /admin/config/people/accounts.

Step2

Once you prepare your $user object and use it on user_save function you have to follow below steps to send the mail.

$userData = user_save($user);
$account = user_load($userData->uid);
$op = 'register_pending_approval';
$status = _user_mail_notify($op, $account);


Thanks a lot @J.Reynolds for pointing me in the right direction!

/**
 * Helper function to get current question's NID.
 * @return string node ID
 */
function _current_question_nid() {

  // Presume a URL node/1234/take/2 meaning we are at the second question
  // of a quiz, where arg(1) is the quiz NID

  // Now let's look inside SESSION. There's our current quiz NID.
  if (array_key_exists(arg(1), $_SESSION['quiz'])) {

    // Inside there is the current result ID.
    $result_id = $_SESSION['quiz'][arg(1)]['result_id'];

  } else {

    // A little bit different to get the current result ID at last question.
    $result_id = $_SESSION['quiz']['temp']['result_id'];

  }

  // Now we can load the quiz results from that result ID.
  $result = quiz_result_load($result_id);
  // There all question NIDs are inside, nicely ordered, yay!

  // Finally let's take the question number and get its NID.
  $current = $result->layout[arg(3)];
  return $question_nid = $current['nid'];
}


How to filter 1 view with two fields based on 1 contextual filter?

Try Views Argument Substitutions. It lets you use contextual filter values in the regular filters.

Add a Global: Null contextual filter to get your default value. It's very important to use Global: Null so the view isn't filtered.
In your regular filters, you can add that value with * * * 1 * * * (no spaces) so that you can add AND / OR stuff. Use a different number if your Global: Null isn't at the top of the contextual filter list.


There's a number of ways you can accomplish this, here's a few off the top of my head (in no particular order):

Create a normal page node and use Node Privacy by Role, a module which allows you fine-grain access control on a per-node basis using roles.
Use Views to create an admin page and limit the access using Views's "Access Restrictions."
Use Panels to create an admin panel and limit the access using Panel's "Access Restrictions" (very similar to Views).
Use Contexts, create an admin Context and display the content conditionally.

Basically, there is no best or worst way, it all depends on how your current site is set up.  For example if you are already using Panels, it might make sense to go that route, etc.

Personally, I would use a mixture of Contexts and Views!


How can I allow more file extensions with file uploads?

You actually have to check for the return values of the file_validate_extensions() function in order to detect if any errors have occurred.

so your code would be something like this:

$fid = $form_state['values']['attachment'];
$file = file_load($fid);

if ($file != null) {
  $extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");
  if (!$extension_errors) {
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  } else form_set_error('attachment',$extension_errors[0]);
}


Any way of not to render the pane in panel using custom module?

What you're looking for is called a access plugin, those are how Page manager (and by extension Panels) control both access and visibility settings.

This question: What are Ctools plugin (content type, access, etc), and how does one create them? has a lot more details and implementation examples.


When you recreate a Feature, do you need to uninstall and re-install it?

Instead of deleting the folder just download the tar.gz file and extract it in the folder where the features folder is there. I would automatically merge the changes.


If you have language fallback enabled, then the fallback order is the order of the languages you have set at admin/config/regional/language


How to implement apple-touch-icon to a site

I enhanced @willtate code a little.
Note: If you need to create the icons quickly use this online generator: http://iconifier.net/

Add the default icon

$apple_icon =  array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => path_to_theme() .'/apple-touch-icon.png',
    'rel' => 'apple-touch-icon-precomposed',
  ),
);

drupal_add_html_head($apple_icon, 'apple-touch-icon');

Loop through to add various sizes

$apple_icon_sizes = array(57,72,114,144);

foreach($apple_icon_sizes as $size){
  $apple = array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => path_to_theme().'/apple-touch-icon-'.$size.'x'.$size.'.png',
      'rel' => 'apple-touch-icon-precomposed',
      'sizes' => $size . 'x' . $size,
    ),
  );
  drupal_add_html_head($apple, 'apple-touch-icon-'.$size);
}

HTML Output

<link sizes="57x57" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-57x57.png"></link>
<link sizes="72x72" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-72x72.png"></link>
<link sizes="114x114" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-114x114.png"></link>
<link sizes="144x144" rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon-144x144.png"></link>
<link rel="apple-touch-icon-precomposed" href="sites/all/themes/yourtheme/apple-touch-icon.png"></link>


Drupal admin links broken for site when using WAMP (e.g. localhost/test2/admin/content)

Thank you to @kenorb for supplying the answer that resolved the issue involving WAMP, Drupal 8.0.0 and having the admin menu links break when clicking on them.

The solution is to uncomment RewriteBase line in .htaccess file and setting it to /test2 which is used as my base URL.


Multiple user-selected front page layouts

You could add a checkbox in the theme settings and adjust the page template accordingly in a page preprocess.

Something similar to this would go in the theme-settings.php file in your theme...

function THEMENAME_system_theme_settings_alter(&$form, $form_state) {
    $form['front_layout'] = array(
      '#type'          => 'radios',
      '#title'         => t('Front Page Layout'),
      '#options'       => array(
        'layout_1' => t('Layout 1'),
        'layout_2' => t('Layout 2'),
        'layout_3' => t('Layout 3'),
      ),
      '#default_value' => theme_get_setting('front_layout'),
    );
}

Add new page template suggestions in a page preprocess ...

function THEMENAME_preprocess_page(&$variables) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['theme_hook_suggestions'][] =  'page__' . $layout_setting;
  }
}

This would allow you to have separate page templates for each layout. An example being page--layout-3.tpl.php.

If it's merely css changes you need, you could add a body class in an html preprocess ...

function THEMENAME_preprocess_html(&$variables, $hook) {
  if ($is_front) {
    $layout_setting = theme_get_setting('front_layout');
    $variables['classes_array'][] = drupal_html_class($layout_setting);
  }
}

In this example you would have a "layout-1", "layout-2" or "layout-3" class on the body element.


Instead of moving cron, you need to look into what parts of cron are so CPU itensive and why it takes such a long time to complete.

You can start by logging executed tasks, how when they start, finish and a comment about what they do.


Add preprocess to content within body field

There's a couple different ways one could go about this; I think the most elegant solution could be a text filter.

/**
 * Implements hook_filter_info().
 */
function MODULE_filter_info() {
  $filters = array();

  $filters['shadowbox'] = array(
    'title' => t('Image Shadowbox'),
    'description' => t('Wraps images in anchor tags.'),
    'process callback' => 'MODULE_shadowbox_cb',
  );

  return $filters;
}

Then, the callback:

/**
 * Image shadowbox callback.
 *
 * @param string $text
 *   The text to be parsed.
 * @param object $filter
 *   The filter, which includes context about which format is being used.
 *
 * @return string
 *   The replaced content.
 */
function MODULE_shadowbox_cb($text, $filter) {
  $ret_val = $text;
  // Logic goes here.
  return $ret_val;
}

You'll need to enable the filter:

/admin/config/content/formats/full_html
/admin/config/content/formats/filtered_html

Now, for the content of the callback; you could use a regular expression. https://stackoverflow.com/a/4456866/4619035 is an example for exactly this use case. The downside of regular expressions with HTML is that they're fragile, especially with potentially malformed code. A workaround would be to sequence the filter after anything that cleans up HTML.

Alternatively, use DOM to manipulate the content - https://stackoverflow.com/questions/18316527/php-dom-wrap-image-in-link-and-add-span-before-image-tag describes this approach well.


How do I display the last person that edited content instead of the original author?

Adding a relationship of user (content revision) & Content (Content revision) proved to be fruitless.

Ok, time for plan B

Using Views field view we'll create a revision view, add revision user as field and then insert this view as field on the content view.

1) Create a new view

Show: Content Revision
Checkmark Create a block
Items per block: 1

2) Add a contextual filter

Originally I tried with Revision ID, but there is a bug, this contextual filter does not work.
So instead use ID (which is the node id)

When filter not available, hide view

3)

Remove the changed & title fields
Add Revision User

4) Add a Sort of Changed

Select Descending sort

5) Save your view

Now go to the Content View (/admin/structure/views/view/content)

1) Add field of ID

Checkmark, exclude from display

2) Add field View

Select the view you just created and for contextual filter use {{ fields.nid }}

and that's it!


Update Drupal Core from 6.26 to 6.36 using update.php gave no errors, but Drupal still reports that it is on version 6.26

Have you manually brought your codebase up to version 6.36 by overlaying 6.24 with 6.36?

The update.php will only update the database to the latest version of Drupal installed.  So if it's still 6.24, it makes sense to me that it is applying 0 of 0.

https://www.drupal.org/node/1223018


Unexpected error when trying to view revisions

You need to add a check and also no need to $node_info = Node::load as the node is already loaded. The first two lines inside the function are not even getting used, so I removed them.

function themename_preprocess_page(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) { // check it's a node
    if($node->hasField('field_component')) {
      $paragraph = $node->field_component->getValue();
      if($paragraph) {
        foreach ( $paragraph as $element ) {
          $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
        }
        $variables['hero_banner'] = $p;
      }
    }
  }
}


How to make CSS and JS both load in the footer

You can just add 'scope' option and pass either 'header' or 'footer' as the value.

slick_carousel:
  css:
    theme:
      slick.min.css: { type: external, attributes: { aysnc: true }, scope:footer }
  js:
    slick.min.js: { type: external, minified: true, scope: footer }
  dependencies:
    - core/jquery


How to grep Rules to search for a deprecated function?

Consider a rule, actually a rules component, as in this (random) sample (in Rules export format):

{ "rules_grant_access_to_a_node" : {
    "LABEL" : "Grant access to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_containing_classified_ad" : { "label" : "Node containing classified ad", "type" : "node" } },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node-containing-classified-ad" ],
          "type" : { "value" : { "article" : "article" } }
        }
      }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "node",
            "id" : [ "node-containing-classified-ad:field-free-format-nr" ]
          },
          "PROVIDE" : { "entity_fetched" : { "fetched_classified_complete" : "Fetched classified complete" } }
        }
      },
      { "drupal_message" : { "message" : "Trying to grant access to node with Id = [fetched-classified-complete:field_free_format_nr]" } },
      { "content_access_action_user_grant" : [] },
      { "redirect" : { "url" : [ "fetched-classified-complete:url" ] } }
    ]
  }
}

The above rule (Rules Component) has a Rules Action content_access_action_user_grant (= machine name) which is available if (a) you have the Content Access module enabled and (b) the ACL module is enabled also. So ACL is a weak module dependency of the Content Access module.

However, that content_access_action_user_grant Rules Action is only available if, and for as long as, ACL is enabled (if you disable the ACL module, then any rule that refers to that Rules Action content_access_action_user_grant will show a "... fails the integrity check").

With the above example (and Rules Action) in mind, execute an SQL query on the Drupal database which looks like so:

SELECT id,plugin,name,label
FROM `rules_config`
WHERE `data` LIKE '%content_access_action_user_grant%'

The results I get by using this query looks like so:

id  plugin   name                             label

216 rule     rules_grant_access_to_a_node     Grant access to a node

Obviously, this result with id=216 matches with my (random) sample rule.

To execute the above query, you can use whatever SQL query tool, such as PhpMyAdmin.

Replace the machine name of the Rules Action in my example by whatever fits with your "function name" (as in your question), and a similar SQL query should list all "rules in your site" (as in your question) that reference your custom module.

Note: another approach (if you can afford to do so), is to simply disable your custom module, and then use the Rules UI to find out which Rules / Rules Components show a similar message containing such "... fails the integrity check".


How to correctly check the value of boolean in D7?

The error you're getting simply means that

$content['field_hide_1st_line_of_the_addre']['und']

hasn't been set. It might be that the 'und' key is missing, or it might be that $content['field_hide_1st_line_of_the_addre'] simply hasn't been set at all. This can happen if you've added a new field to a content type that already has existing nodes (and probably in other situations too).

To remove the notice, you can just wrap your code in another condition that ensures the array element you're accessing exists. For example:

<?php
  if (isset($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'])) :
    if ($content['field_hide_1st_line_of_the_addre'][LANGUAGE_NONE][0]['value'] == 0) :
      print render($content['field_images']['#object']->field_location['und'][0]['street']) . t(', ');
    endif;
  endif;
?>

I've taken the liberty of replacing 'und' with the constant equivalent (and cleared up a couple of other very minor issues), it's better practice. Even better practice would be to extract this logic out of the template file completely, and instead implement it in a preprocess function.


Passing product info to PayPal using Comment1 and Comment2

I've been researching this very issue myself. I spoke with PayPal and they told me the following.

First, they recommend you use the PayFlow Pro Module.

Second, to add $comment1 and $comment2 variables to your code you need to:

Create the form fields for COMMENT1 and COMMENT2 to add to the Return Array at lines 293 (of commerce_payflow.module):

‘comment1’ => $_POST[‘your_form_field_here’],
‘comment2’ => $_POST[‘your_form_field_here’],

Note: You may need to build the form fields in the function starting at line 336.

This is really a half-solution, because:

Now, I'm still trying to parse out exactly how to do this myself but I'm pretty sure it involves a custom module that uses a hook to alter a function in that module (possibly commerce_payflow_link_settings_form or commerce_payflow_link_default_settings).


How to import a template file with HTML markup to use for sending email notifications?

If the module doesn't allow importing it, just copy the markup and put it in your relevant Email template, inside your module.

Otherwise, add such importing option by customizing to module, or try another.


In the classic HTTP model, the server is passive and can only return information to the client when it request it. So, in this model, to alert the users when a node is updated, you have to periodically poll the server the ask it if the node has been updated. If you have a lot of clients waiting for the update of a lot of nodes, this can quickly overload your web server with too much request to handle.

Today, the best solution for this kind of requirements is to use WebSockets or a similar full-duplex technologies. Drupal and PHP are not designed to serve a WebSockets. Technologies like node.js and Socket.IO,  or APE are more suited.

The Node.js integration module integrates node.js and Socket.IO in a easy to use solution. It provides an API to easily implements your need.


How to expose the node creation form in the front page?

To display content type form you can use formblock module as it description explains:

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

Enable the module
Go to Project admin/structure/types/manage/project
On the bottom left vertical tabs there'd be a Form Block, check Enable data entry from a block and save
Go to admin/structure/block and enable Project form block

I hope this'd help you.


How do I calculate field_1 + field_2 in Twig?

In {{ content }} are render arrays which produce the output "2" and "5", but you can't do arithmetics with these render arrays.

You can try to do this with the database values from the node (if it is a node template):

{{ node.field_1.value * node.field_2.value }}


Delete permissions not working with Domain Access instaled

For some unknown reasons, I had this option checked under Permissions: Delete any content on assigned domains. Obviously, it overrided every other permission filtered by content type. Unchecking it, the "Delete" link only appeared on the Admin role, which is what I wanted.


How can you identify all nodes that use a certain paragraph type or template?

As @runwithscissors stated in the comments, you can use views to to this.

I’m not super experienced with views in Drupal 7, but It should be as easy as:

Create a view that lists the nodes .
Add a relationship to the referenced paragraphs.
Add a filter on the paragraphs bundle.

That should be all. Once you have added the relationship, the bundle field will be made available as a filter.

I hope this is as easy in Drupal 7 as it is in Drupal 8.

You can read more about views here.


Services 3 JSON format [null] at end of all result

I dont know why do you need to convert the data to JSON format. My idea is that you just return an array. The returned data of your custom service will be based on how we call it.

function gymcam_sendemail($data) {
  $data = array('status' => 'error', 'msg' => 'Mail not sent');
  return $data;
}

If you want to use JSON for returned data, just call /gymcam/sendmail.json


How do I run a site from a sub-directory?

I just had the same problem. I have solved it with htaccess file(ie. not nginx) in the root directory with the following code(although I have tested it only with simple index file, not with fully installed Drupal):

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_URI} !drupal/
  RewriteRule (.*) /drupal/$1 [L]
</IfModule>


Form inputs being disabed during the Ajax request

That functionality is built-in so you'll need to monkey-patch Drupal.ajax.prototype.beforeSend (found in misc/ajax.js).

Copy the entire code, but remove/modify this line:

$(this.element).addClass('progress-disabled').attr('disabled', true);

So in your module or theme's JS file:

Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
  // Place all code from the original function here, except the line above.
}

YMMV, you may unwittingly introduce unexpected behaviour by not waiting for each request to complete.


Avoid repetitive API calling in form rebuild while submitting

You can test whether the form is currently rebuilding using the FormStateInterface::isRebuilding method:

if (!$form_state->isRebuilding()) {
  // Contact the API
}


getting error when clear cache in drupal

Consider using db_merge if you want to write when the record doesn't exist and update if the record exists. In fact at the business logic level you should check if a record exists or not before making an insert or update. That way you will have more control.

And regarding the problem you are facing only when you clear cache, it can be that somewhere in your code when you have an entry in cache you are not making an insert. But when there is no entry in the cache, you are making an insert. So every time you clear the cache an insert is being attempted with the same key which might be causing the problem.


jQuery.js not loading after enabling custom module

Your custom JS should be wrapped in:

(function($) {
  // custom Drupal behaviors here
})(jQuery);

Give that a shot.


Can we fire database query while flagging the node?

According to The Flag 3.x API (PHP)

mymodule_flag_flag($flag, $content_id, $account, $flagging) {
  // Do something in response to the flagging.
}

mymodule_flag_unflag($flag, $content_id, $account, $flagging) {
  // Do something in response to the unflagging.
}

In your case

mymodule_flag_flag($flag, $content_id, $account, $flagging) {

  if ($flag->name == 'pick_this_bid'){

     $nid = $content_id;
     db_update('my_table')
       ->expression('status', '0')
       ->condition('nid', $nid)
       ->execute();
  }

}


How can I control the order of Drupal.behaviors?

The JavaScript code used by Drupal 7 is the following:

Drupal.attachBehaviors = function (context, settings) {
  context = context || document;
  settings = settings || Drupal.settings;
  // Execute all of them.
  $.each(Drupal.behaviors, function () {
    if ($.isFunction(this.attach)) {
      this.attach(context, settings);
    }
  });
};

Drupal 6 uses similar code:

Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
    jQuery.each(Drupal.behaviors, function() {
      this(context);
    });
  }
};

If JavaScript would guarantee that object/array properties are always traversed in the same order they are added, then the values would be passed from jQuery.each() to the function used as its second parameter in the same order they are inserted in the array passed as first parameter.
This would mean that the first behavior inserted in Drupal.behaviorsis executed first.
In this case, to allow the behaviors defined by your module to be executed first you could use a lighter weight for it. If you want they are executed before the other ones, the module weight should be set to -50; other values can work too.
If you are using Drupal 7, drupal_add_js() allows to associate a weight to the JavaScript code; JavaScript code with a lighter weight appears first in the HTML output. This is not possible with Drupal 6, thought.

JavaScript doesn't guarantee that properties are traversed in the same order they are added. This means that different JavaScript implementations would present the same properties using a different order; it also means that the same order could change in different versions of the same browser.


How do I restore the comment body field I deleted from a content type?

Create a random content type
Restore the comment_body field from existing field`s, because it's existing now
Delete the random content type


You can navigate to this url admin/config/people/force_password_change
and check Force password change on first-time login option or you can configure based on roles too.

In that case you will get a option in both create and edit user as shown in screenshort.


How to programmatically create new user with custom fields?

Using user_save Drupal function you can create new users like so:

$new_user = array(
  'name' => 'JohnDoe',
  'mail' => 'john.doe@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))), // This becomes $account->field_custom_first_name[LANGUAGE_NONE][0]['value']
  'field_custom_last_name' => array(LANGUAGE_NONE => array(array('value' => 'Doe'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
  //'roles' => array('10' => '10', '11' => '11'), // If you want to specify additional roles, the numbers are role_id's
);
user_save(NULL, $new_user);


How do add a condition to check if created node is language source (in a multilingual site)?

Check your created node if it has a $node->tnid. The tnid (translation id) would be not null if its a translation from another node.


Put the D7 site under the root web directory. You should be able to go the site and see the D7 site. Then, put the D6 site under the root web directory in a new directory called 'd6' or whatever you want. Then, in the settings for the D6 site, put the root path as webdirectory/d6.

Then you can reference the d6 site from the d7 by directing users to the link "something.com/d6/someNode"

Otherwise, you really can't have both running under the same web root. It has to choose one or the other.


Is it safe to purge the /files/styles directory?

Yes, it's perfectly safe to delete the files/styles directory: Drupal will regenerate the images the next time someone attempts to access it.

The image module defines a menu router item, $directory_path . '/styles/%image_style', that maps to the callback image_style_deliver().

In turn, image_style_deliver() checks to see if the generated derivative image exists: if it does, it serves it. Otherwise, it calls image_style_create_derivative().


How do I automatically add links on the right sidebar in drupal 7?

I've just implemented related content using views following this tutorial. If you prefer using a module you got even more choices.


Alter a select form using preprocess function

In your foreach loop, $option_term is a copy of the current variable returned from the iteration. If you want to change the original variable (i.e. what's in $vars['form']['field_categorie_tid']['#options'][index]) then you need to pass it by reference:

foreach($vars['form']['field_categorie_tid']["#options"] as &$option_term){
    $option_term .= 'test';
}

Or refer to the array member explicitly like so:

foreach($vars['form']['field_categorie_tid']["#options"] as $key => $option_term){
    $vars['form']['field_categorie_tid']["#options"][$key] .= 'test';
}

I generally prefer the second method as passing variables by reference in this way can sometimes cause some strange behaviour.

You also had a slight code error, the variable is called $option_term in your loop declaration but $optionterm in the loop body.

Just FYI, template preprocess functions are really not the best place for this sort of code. You would be far better off using hook_form_alter().


How do I load classes using the ctools plugin class loader?

mymodule.module:

<?php
/**
 * Implements hook_ctools_plugin_api().
 */
function mymodule_ctools_plugin_api() {
    list($module, $api) = func_get_args();

    if ($module == 'mymodule' && ($api == 'plugins')) {
        return array('version' => 1.0);
    }
}

/**
 * Implements hook_ctools_plugin_type().
 */
function mymodule_ctools_plugin_type() {
    return array(
        'plugin_type' => array(
            'classes' => array('handler'),
        ),
    );
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function mymodule_ctools_plugin_directory($owner, $plugin_type) {
    if ($owner == 'mymodule') {
        return "plugins/$plugin_type";
    }
}

plugins/plugin_type/example.inc:

<?php
$plugin = array(
    'title' => t('Example'),
    'handler' => array(
        'class' => 'ExamplePlugin',
    ),
);

plugins/plugin_type/ExamplePlugin.class.inc:

<?php
class ExamplePlugin {
function __construct($plugin){

}
}

Anywhere:

<?php
// Get all available plugins
$plugins = ctools_get_plugins('mymodule', 'plugin_type');

// Load a specific plugin
ctools_include('plugins');
$plugin = ctools_get_plugins('mymodule', 'plugin_type', 'example');
$class_name = ctools_plugin_get_class($plugin, 'handler');
$example = new ExamplePlugin($plugin);


Drupal 6 term based view not translating vocabulary terms

I think what you are trying to do is something along these lines:

Which here gives me:

And when I change the language, eg:

it then gives me:

I've set my vocabulary here up like so:

with translations (quickly done just for this so pardon the potential sloppiness)

and nodes translated like this (pardon the silly titles):

so if you are getting different results, check to make sure all of the various places you can set a language are similar.


Check Content Type in Paragraph Preprocess

The correct way of getting the entity data referencing to your paragraph is to use Paragraph's entity API.

/**
 * Implements template_preprocess_paragraph().
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - paragraph: The paragraph object.
 *   - view_mode: View mode; e.g., 'full', 'teaser'...
 */

function mytheme_preprocess_paragraph(&$variables) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];
  // Get the parent bundle.
  $parentBundle = $paragraph->getParentEntity()->bundle();
}


For HTML emails, you have to use the inline style attribute.

The Mimemail module might be able to inline your external CSS.


Why authenticate request returned 403 after successful login?

Try to be specific with the ACAO header, like
Access-Control-Allow-Origin: admin.example.com

The wildcard is not really appreciated, browsers may treat this as high security risk and block the request.


LogicException : The controller must return a response (success ! given)

A controller must provide a response, but drupal has extended the response handling to look for render arrays, that are then used the generate a response with the rendered html. If you don't provide a render array, then there is no response and then this error message will come up.


If you want to filter by taxonomy term in your view you can do this by adding a contextual filter (arguments in D6).

If you can pass the term id then you can do the following:

When adding a contextual filter choose "Content:Has taxonomy term ID".
Under "MORE" there is an option "Allow multiple values".

You can play around with these options as I never get it right on the first go.


You can always just create a field in the UI and extract the settings from there. Or look at the defaultSettings() method in the plugin class, where you can find this:

/**
 * {@inheritdoc}
 */
public static function defaultSettings() {
  return array(
    'display_label' => FALSE,
  ) + parent::defaultSettings();
}

So, add 'settings' => ['display_label' => TRUE] to your form display definition and you have what you want.


Drush site-upgrade : "Unknown option: --uninstall"

My Drush configuration file was simply misplaced, I had to put it in Drupal's directory (sites/all/drush/drushrc.php) rather than ~/.drush/

When running drush status from your Drupal source site directory, make sure there is a Drush configuration loaded.

Drush version                   :  6.2.0
Drush configuration             :  /var/www/html/drupal/sites/all/drush/drushrc.php
Drush alias files               :  /root/.drush/my.alias.drushrc.php

And here is the content of file sites/all/drush/drushrc.php

<?php
$options['strict'] = FALSE;


I have also faced same situation where favicon is serving from http whereas all images including logo are serving from https. I am using Metatag module, in the module configuration default favicon path is given as http://example.com/sites.default/files/, so favicon is serving from http. I have changed the path to https://example.com/sites/default/files/favicon.ico. This fixes the problem, this may also the reason in your case.

If this is the case you can change the favicon default path, go to  https://example.com/admin/config/search/metatags/config/global Under favicon and touch icon tab change the path.


How to create and add a page to a book programmatically?

You can use the saveBookLink(array $link, $new) method of the BookManager service (book.manager).  See Drupal\book\BookManagerInterface.php

After you create the node programmatically, create a new array $link with the following key/value components:

Each book entry consists of the following keys:
 - bid: The node ID of the main book.
 - nid: The node ID of the book entry itself.
 - pid: The parent node ID of the book.
 - has_children: A boolean to indicate whether the book has children.
 - weight: The weight of the book entry to order siblings.
 - depth: The depth in the menu hierarchy the entry is placed into.

(See Drupal/book/BookOutlineStorageInterface::loadMultiple()).

So, your code will look something like this:

protected $bookManager;

public function __construct(BookManager $bookManager) {
  $this->bookManager = $bookManager;
}

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

/** Method that creates your node here... **/
  $link = [
    'nid' => $nid,
    'bid' => $bid,
    'pid' => $pid,
    'weight' => $weight,
  ];

  $this->bookManager->saveBookLink($link, TRUE);


Is there a module that allows users to post content in steps?

Try Multistep Nodeform

  Multistep Nodeform" is a module to split the node creation and node
  editing form into several steps. This may be usefull for you if you
  have lots of fields in your content type and would like to provide a
  wizard-like UI for content creation/editing.


Best way to modify views output with a custom function?

I would much prefer a solution that I would allow Views to the render the text you want directly, so technically, I'm not going to answer your question here.

My suggestion is that you add a new formatter, that you use to directly render the user points as a text string instead. This allows your level to work correctly with all of core, not just one particular block. You can then just add user points twice to the View, with different formatters.

I haven't given the particular code below a proper test, as I don't use user points anywhere, but it's copied and cleaned up from live project where I use do something similar, so I know that it works.

/**
 * Implements hook_field_formatter_info().
 */
function user_level_field_formatter_info() {
  return array(
  'user_level' => array (
      'label' => t('User level'),
      'field types' => array('user_points'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function user_level_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $user_level = 'green';

  switch ($items[0]) {
    case > 5000:
      $user_level = 'veteran';
    case > 2500:
      $user_level = 'experienced';
  }

  return array(0 => array('#markup' => $user_level));
}

The code above assumes that user points is a real field on the user. If that is not the case, then you can add a new text field on the user, set 'field types' to array('text') instead, and in the formatter grab the number of user points directly from user points, with say a user_load($uid), instead of from $items[0] as I do. You will probably also hide the textfield from user_edit with a hook_form_alter.


Display thumbnailPhoto from Active Directory - Open atrium and LDAP modelude

You need to configure your ldap server

  Go to admin/config/people/ldap/servers
  Click edit
  Go to "LDAP User to Drupal User Relationship" tab
  Under "Thumbnail attribute" add "thumbnailphoto" (without quotes)
  Save your settings

Now your ldap server is configured to automatically copy user thumbnail from ldap (Active Directory) to Drupal.


You can use hook_form_alter to alter the menu link edit form.
This way you can add a extra field to the form, in your case:

$form['subtitle'] = array(
 '#type'=>'textfield',
 '#title'=> t('Subtitle'),
);

Then add an extra submit hanlder to the form:

$form['#submit'][] = '_my_submit_handler';

In your submit handler you can access your custom value by using $form_state['values']['subtitle'].

You will have to store this value in an extra sql table or a variable_set,together with the menu-item ID.

Once you have done that, in your theme function you can access your subtitle by menu id.
Or you can use  MYTHEME_preprocess_menu_link to add extra info to $variables, which you then can access in your theme function.

Hopes this helpes you out.


How do I redirect users from the registration page to Paypal?

Use the Drupal Commerce module.

Add the Paypal payment method module; hook the login/register form to provide a different redirect page, or use the Rules module.
You can look at the generated transaction.
I would create the account anyway; set a flag, or something, for payed accounts.


One possible option to create a view page (/about-us) and under filter option make it available on this domain and content type (create a content type for about us and place all about us content under it).


Node Clone operation/tab missing for webform

Besides simply enabling the Node Clone module and checking the permissions associated with it, you'll need to select which content types can be cloned.

To do so, go to /admin/config/content/clone

After enabling for the "webform" content type, you should see the clone link available near the contextual link / action tabs at the top of a webform page when signed in as an admin and viewing the page.


CSS in the theme (or in the module that provides the View) is the best way to do this.


How do I dynamically change an autocomplete route for a field depending on another field's value?

If I understand your question correctly, you may want to include one term reference field for each taxonomy you want included on the form. You could then create a template for the page and use Javascript to control which fields are visible. So if the user chooses Option A  it gives them one set of choices for the Taxonomy and if they choose B it gives them another..

You may also have luck with https://www.drupal.org/project/conditional_fields


How do I correctly add jQuery UI widgets?

jQuery UI Accordion is included in core, use drupal_add_library('system', 'ui.accordion'); to add it.


how to enable workflow submodules in Modules administration page

This page has suggested you the reason. You didn't install Entity module, you can get this module on Entity cache module.
This module has no user interface, if you enable it, entities will start being cached, if you disable it, they'll stop.


How to display "About the author" tab in article display page?

There is Author Pane

  Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.

For the tabbed view you cold try Quick Tabs

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*.


Drupal uses a function called _system_rebuild_theme_data() to help determine the list of themes (both enabled and disabled) to show on that page. That function does a number of things, but the first thing it does is to look for any .info files within the "themes" directories, which can include /themes, /sites/all/themes, sites/anydirectory/themes.

So, based on the screenshot, it appears that you have some modules placed in a themes directory. I would go through your themes directories to make sure that that isn't the case.


Add only one input filter to a textarea using form api

There are several  way to  achieve this, you can use the Hide Formats module:

  Hide Formats allows you to collapse the "text format" or "input
  format" dropdowns to clean up the UI.

or Better Formats module:

  Better formats is a module to add more flexibility to Drupal's core input format system. Features 8.x & 7.x (needs more testing for a stable release)

  Set allowed text formats per field.
  Set default order of text formats per field.
  Hide format tips per role. Hide more format tips link per role.
  Hide format selection per role per entity.
  Currently only works on Field API fields on fieldable entities implementing core style text processing. The good thing is that is
  most things in core and contrib.

Or, use the FormAPI to disable it with something like:

// hook_form_alter function
function CUSTOM_MODULE_form_alter(&$form, &$form_state, $form_id) {
    // We want this on a specific node type
    if ($form_id == 'NODE_TYPE_node_form') {
        $form['#after_build'][] = 'CUSTOM_MODULE_NODE_TYPE_node_form_after_build';
    }
}

// afterbuild function
function CUSTOM_MODULE_NODE_TYPE_node_form_after_build($form) {
    // We want this on a specific field
    $form['YOUR_FIELD']['und']['0']['format']['#access'] = FALSE;
    return $form;
}

Also you can try this (I didn't test it but it may work):

$form['text'] = array(
    '#type' => 'text_format',
    '#default_value' => variable_get('text'),
    '#title' => t('text'),
    '#format' => "full_html",
    'format'=>array('#access'=> false),
  );


How to test an alter hook in your .module with ModuleHandler service?

For alter hooks, there is ModuleHandler::alter(). That is what, for example, the AlterTest class uses.

// Verify alteration of a single argument.
$array_copy = $array;
$array_expected = [
  'foo' => 'Drupal theme',
];
\Drupal::moduleHandler()->alter('drupal_alter', $array_copy);
\Drupal::theme()->alter('drupal_alter', $array_copy);
$this->assertEqual($array_copy, $array_expected, 'Single array was altered.');
$entity_copy = clone $entity;
$entity_expected = clone $entity;
$entity_expected->foo = 'Drupal theme';
\Drupal::moduleHandler()->alter('drupal_alter', $entity_copy);
\Drupal::theme()->alter('drupal_alter', $entity_copy);
$this->assertEqual($entity_copy, $entity_expected, 'Single object was altered.');

The Drupal 7 documentation for module_invoke() is more explicit in suggesting to use drupal_alter() for arguments passed by reference.

  All arguments are passed by value. Use drupal_alter() if you need to pass arguments by reference.

If the hook you are testing is also implemented from one of the modules from which your module depends, ModuleHandler::alter() would invoke the hook implemented from those modules (if those modules are installed from the test), but I take that testing an alter hook means also testing it works together the same hook implemented by the module dependencies. (In this way, the module can also test if its alter hook implementation needs to be executed earlier or later, respect other implementations of the same hook.)

if you really need to invoke a single alter hook, and other modules installed from the test implement it, you could use the following method to add in the test class.

function protected invokeAlterHook($module, $type, &$data, &$context1 = NULL, &$context2 = NULL) {
  $function = "$module_$type";
  $function($data, $context1, $context2);
}

If you look at the code in ModuleHandler::alter(), that is simply the way it invokes the hook implementations.

  foreach ($this->alterFunctions[$cid] as $function) {
    $function($data, $context1, $context2);
  }

ModuleHandler::invoke() doesn't work with parameters expected to be passed as reference because it uses the following code to invoke the hook.

$function = $module . '_' . $hook;
return call_user_func_array($function, $args);

To pass an argument by reference, call_user_func_array() should be called, for example, as call_user_func_array($function, [&$data]).


Pass a webform value to a node via Rules?

Create Hidden inputs in webform.
Assign to this hidden inputs values (prepopulated in url, tokens, webform rules or programmatically).
Assign these inputs to content fields using Rules.


Only a view filters in exposed filter block

You could copy the view for your second use case and only make the 2 needed filters exposed and expose that as a block.


Confirmation popup before delete file/image

After long time I managed to find the solution. I didn't manage to make it work server side with modals so I managed to solve it using jQuery.

So I created a javascript file:

    Drupal.behaviors.confirm = {
        attach: function(context, settings) {

            $.each($('.form-submit'), function(){
                var str = $(this).attr('id');
                //find the id for each button
                var remove_btn_id = '#' + $(this).attr('id');

                //apply only to remove buttons and only to those that the functionality is not applied yet.
                if (str.indexOf("-remove-button") >= 0 && !$(remove_btn_id).hasClass('custom-handler')){

                    //Drupal.behaviours are triggered every time my ajax was submitted and I ended up with multiple events to each button.
                    //In order to avoid it, add a class to check if the button already has that functionality.
                    $(remove_btn_id).addClass('custom-handler');
                    $(remove_btn_id).bindFirst('mousedown', function(e, next) {

                       //Display popup and get user's decision.
                        var choice = confirm('Are you sure you want to delete that?');
                        if(!choice){
                            //if user clicks cancel then do nothing
                            e.stopImmediatePropagation();
                        }
                    });
                }
            });
        }
    }

I'm not sure if this the right way to implement that functionality (I guess is not the Drupal way) but at leat it works!


You need to go to "Admin > Configuration > People > Account Settings > Manage display". You will be able to reorder the fields from there. If you want to remove some of them from the display, you can select "Hidden" from the menu in the "Format" column.

EDIT:
The profile picture, however, is managed separately by Drupal, not as a field. If you want to be able to manage it, a workaround might be to disable the default Drupal profile picture (Admin > Configuration > People > Accounts > Personalization) and to create a new Image field to display the picture, which you can treat as any other regular field. There are even some modules that create the field for you, like user picture field.


Webform in block allowing clicking on send button and redirecting to page view, without validation the fields even when they are empty

This is because you somehow missed making the E-mail field mandatory.
You can do so by following the steps given below:

Edit the existing webform content at : yourhost.com/admin/content and selecting edit for your webform.
Click the "Webform" tab, and check the "MANDATORY" option for the required field.
Click "Save". Thats it!


How to cleanup Wordpress media tags after migration?

Ah found the answer after some digging:

  You have the Media module enabled, so the migration renders image references as media tags - you need to change your filter to interpret the tags

http://drupal.org/node/1859458#comment-6819442

  You have the Media module enabled, correct? And you're saying when you view (not edit) the nodes you're seeing the media embeds ([[{"type":"media"," etc.) instead of the image itself? Please go to /admin/config/content/formats and make sure that the text format you've chosen for the imported bodies has "Convert Media tags to markup" enabled.

http://drupal.org/node/1642352#comment-6136596

http://drupal.org/project/media


Feeds: solution with most frequent/real time/push notification update of feeds (e.g. for twitter tweets)?

It looks like Twitter's "Streaming API" is your solution. However, I would look closely at their Pre-Launch Checklist before going down that route. They have 10+ things that you should comply with before becoming a stream or push consumer of their API.

Maybe a solution that would fit you is to develop a twitter stream client (that would be your server), and then to have your application users connect to your server via node.js, since node.js provides a "persistent" connection suitable for chat rooms and push-like notifications.

This is an interesting (and probably doable) suggestion, but not something that you would find pre-packaged in a Drupal module.


Which alias do I use to run it with another PHP version?

This is possible by setting the environment variable DRUSH_PHP as described in the documentation.
https://www.drupal.org/node/1302418

Also you can make use of "php" global otpion which allows to specify the absolute path to PHP interpreter.


When should I use hook_field_attach_presave(), and when hook_entity_presave()?

It depends on what type of data you are trying to modify.  Some entities are not fieldable. Those entities would never call hook_field_attach_presave() where as they would call hook_entity_presave().

If you are modifying an entity's base properties such as 'title', you should use hook_entity_presave(). If you are modifying the fields attached to an entity, you should use hook_field_attach_presave().

Keep in mind that other modules might be using these hooks as well. They would expect you to be making your modifications to the type of data in its respective hooks.


Theming custom entity created with Entity API: accessing entity's fields in template file

This can be easily solved by including this snippet at the beginning of your template file:

// my_template.tpl.php
<?php
$keys = array_keys($element['my_entity_type']);
$my_entity_name = $keys[0];
$my_entity = $element['my_entity_type'][$my_entity_name];
?>

Now you can easily print values like so:

<?php print render($my_entity['address']['#markup']); ?>


Force Field Required based on Widget Type

you can group them together with field group,
and then mark that group as required.

but the manual work in the Field UI is neede here ..


Drupal fboauth module - how to get the friendlist of a user

You need to know $access_token.

$result = fboauth_graph_query('me/friends', $access_token);

See the Facebook API for a list of commands: http://developers.facebook.com/docs/reference/api/


drupal 7 Ubercart recurring fee settings tab is blank

You may have to enable the module "Recurring - Hosted Gateways". This should be available under section "UBERCART - RECURRING" in the path admin/modules. In my case this is Paypal WPS.

Once the module is enabled you can see the option at admin/store/settings/recurring. You may also need to enable the required payment methods at admin/store/settings/payment.


When to use mapping or sequence to define an array in a schema file?

A sequence is an unlimited list of identically structured elements. A mapping is a limited set of keys, each key has a possibly different structure.

Your key has node types, so you're storing a list of node type ids, which means a sequence with an inner type string. Exactly what you have.

If you'd use a mapping, you could only store book and test, but test could be an integer (or mapping, or sequence, ...) while book is a string.

The note has nothing to do with sequence vs mapping, it just refers to an old way of defining the type in the sequence and would look like this:

onlyone_node_types:
  type: sequence
  label: 'Configured content types to have Only One node'
  sequence:
    -  type: string
       label: 'Content type machine name'

PS: I'd would convert that to a numbered list, which will then be stored like this:

onlyone_node_types:
  - book
  - test


Print view header using the "Twig Tweak" module

I have create simple extension for that:

add the following to MYMODULE.services.yml

    services:
      MYMODULE.twig.render_view_header:
        class: Drupal\MYMODULE\Twig\HeaderView
        tags:
          - { name: twig.extension }

Create HeaderView class inside MYMODULE/src/Twig.
Copy the code from HeaderView.php
Clear cache.
In your twig call the extension like:

{{ render_view_header('VIEW_NAME', 'PAGE_NAME') }}


On Drupal 6, as per your question, you most likely do NOT need to keep node_export around after your content import/export is done.  It doesn't create any database tables and will only remove config settings variables when you uninstall.

As for UUID it is (depending on  your settings) probably a good idea to keep it around.  It adds/alters some db tables adding its UUID to your content, etc. It would probably be less trouble to keep it rather than remove it and it shouldn't have an impact on the performance of your site.


I definitely don't recommend hacking the module - it's not good Drupal form, and it limits your ability to get module updates in the future.

I think the answer depends on how the module creates the link in question. That is, how is the link HTML being generated? If it's being generated and printed directly to the screen, then you'd have to do some CSS/JS work to intercept the HTML being generated and alter it. We have done this when necessary on our site to bend certain modules and functionality to suit our display needs. If the link has a specific ID, just alter it with JS in a custom module or custom theme. If not, you may have to get at it via jQuery based on what elements it's contained within, but it can be done.

If you're lucky and the module is well-written, the link will be part of content that's passed through Drupal's theming engine first through a theme() call. In this case, you can write your own function to grab anything being themed, inspect it for whatever markers indicate that it should become a button, and then alter the link code as need be. If you're not familiar with the theme() functionality in Drupal, you'll want to read up on it on Drupal.org first. Hope this helps!


After adding info an entity via hook_ENTITY_TYPE_storage_load, how do I access that data in hook_ENTITY_TYPE_view?

You access the property the same way you write it, as $node->i18nfiles. This goes through __set()/__get() which also supports non-fields.

That said, I'm a bit confused about what exactly you're doing. Your table name is node__field_attachments, so it looks like a managed field table, which would load the data automatically and making it available in $node->get('field_attachments')?

And since it's a field, you could then write a custom formatter for that field to display the data and get rid of those hooks.

It is also kind of a deprecated approach, if what I said is for some reason not possible, I'd recommend to either just load the data when you need it in hook_node_view() (with both node load being cached as well as rendered nodes being cached it's hard to compare what is more performant) or make it a computed field, but those are currently still quite painful to implement, see PathItem in Drupal 8.4.x.


How to programmatically enable/disable Quantity text widget on cart/checkout page?

It seems the Quantity widget is a matter of configuring the views.

If you'll edit one of the commerce views e.g. commerce_cart_form or commerce_cart_summary, Quantity can be found in the field list.

By default Commerce Cart module has Quantity set to text field (File: commerce_cart.views_default.inc), so to change the widget from text field to numeric and vice versa you need to edit your view and replace the Quantity field with other one.

There are two fields available for these views:

Commerce Line Item: Quantity

The quantity of the line item.

Machine name: quantity

Handler: views_handler_field_numeric
Commerce Line Item: Quantity text field

Adds a text field to edit the line item quantity in the View.)

Machine name: edit_quantity

Handler: commerce_line_item_handler_field_edit_quantity

If you need to switch between numeric and text widget on certain conditions, you'll have to alter the view by using hook_views_pre_view() and change the handler on the fly.

Here is a simple example:

/**
 * Implements hook_views_pre_view().
 */
function MODULENAME_views_pre_view(&$view) {
  switch ($view->name) {
    case 'commerce_cart_form':
    case 'commerce_cart_summary':
      $view->display['default']->handler->options['fields']['quantity']['field'] = 'edit_quantity'; // 'quantity' for numeric, 'edit_quantity' for text field
      break;
  }
}

Other method is to create TPL view template file i.e. views-view-field--commerce-cart-summary--default--quantity.tpl.php and change the widget from there. Check 'Theme:Information' in view edit page for more info.

Here is example for restricting Quantity field based on the product type:

You need at least one TPL file created in your template directory (sites/all/themes/foo)

for cart page:

views-view-field--commerce-cart-form--default--quantity.tpl.php
for summary page:

views-view-field--commerce-cart-summary--default--quantity.tpl.php

with the following PHP code:

print foo_quantity_available_for_row($row) ? $output : 1; // Hardcoded '1'.

Note: If Quantity is numeric, it'll always display 1, so extend it based on your needs.
And the following two functions:

/**
 * Implements hook_views_pre_view().
 */
function foo_views_pre_view(&$view) {
  switch ($view->name) {
    case 'commerce_cart_form': // On cart page
    // case 'commerce_cart_summary': // On summary page
      $view->display['default']->handler->options['fields']['quantity']['field'] = 'edit_quantity'; // Enforce Quantity field from numeric to text field for further changes.
      // $view->display['default']->handler->options['fields']['text_quantity'] = $view->display['default']->handler->options['fields']['quantity']; // Create clone.
      break;
  }
}

/**
 * Restrict edit of Quantity field based on the product type.
 *
 * Callback from views-view-field--commerce-cart-summary--default--quantity.tpl.php.
 *
 */
function foo_quantity_available_for_row($row) {
  ($line_item = $row->commerce_line_item_field_data_commerce_line_items_line_item_) &&
    ($line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item)) &&
      ($product = $line_item_wrapper->commerce_product->value());

  if ($product) {
    switch ($product->type) {
      case 'product_type_1':
      case 'product_type_2':
        return TRUE; // Allow users to edit Quantity field.
        break;
    }
  }
  return FALSE; // Disallow users to edit Quantity field.
}

It could not work in all cases, so modify based on your needs.

Other method, as suggested by MarcElbichon would be to use hook_form_alter:

<?php
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, 'views_form_commerce_cart_form_') === 0 ) {
        $form["edit_quantity"][0]["#attributes"]["readonly"] = "readonly";
        $form["edit_quantity"][0]["#attributes"]["disabled"] = TRUE;
    }
}
?>


Load the value of an entity field type in another form

Use the method FieldDefinitionInterface::getType:

  Returns the field type.

  Return value

  (string) The field type, i.e. the id of a field type
  plugin. For example 'text'.

In your case for example:

foreach ($field_definitions as $name => $definition) {
  if ($definition->getType() == 'field_custom_example') {
    // found field $name
  }
}