Use different indexes for Solr searches on local dev environment

Sadly, Solr servers and their settings are not variables. They're not entities, nor anything else Drupal would know about, and subsequently be able to effect.

The settings for the server host/path are stored in a serialised PHP string in the search_api_server table. (the options column).

The best I think you'll be able to do is to add a step to your pull-from-pantheon process to run a script after the database has been updated. The script would perhaps delete all existing servers and add a new record with only the known good configuration for your local host.

Or you could have a module enabled locally only that checks for the host on each request, something like that. I don't think there's a way to do it without altering the database manually, or at least by using one of the API functions provided by search_api_solr.


How would I override misc/ui/jquery.ui.theme.css

I don't have enough rep to add comments, but here is my two cents. In addition to Clive's comment, take a look at the weight and group option being used in drupal_add_css, in views_accordion.module. You can implement your own stylesheet here and assign a CSS_THEME for its group and a larger weight number than that of views_accordion, which I'm pretty sure would have used CSS_DEFAULT instead. Here are the docs page. drupal_add_css


Drupal 7 and CSS - How to have a default style for links without affecting other css styles?

First, I would expect that the styling of menu links by Bootstrap would be more specific than the (general) CSS rules you provide for styling links. But a workaround would be to reapply the styling on the menu links in your sub-theme (with more specific CSS rules).


How to Bi-directional link two nodes from different content type?

While still new and with rough edges, the Relation module will be the right module for that job.


After using Drupal.t(), clear the cache once, and search text to translate from admin/build/translate/search.


Yes, with the combination of profile2 and og (organic group)  you can achieve your job.


I am actually a bit puzzled by your View result, because the default settings for fields should give you:

CoAuthor: Person X, Person Y

when there is more than one author (and this I presume, is what you want?)
And since Views also have a setting: "Hide if empty" under *No results behavior", it should be trivial to get this right using fields.
Anyway, this is how I've set this up using Views:
First, I click on Format - Show: Content and switch that to Fields.
Second, I tick Provide default field wrapper elements and Hide empty fields.
Third, under Fields I click Add and add the "CoAuthor" field. I tick Create a label, and Place a colon after the label. Under Multiple field settings, I tick Display all values in the same line.  I also tick Simple separator and make sure it is ,  (comma followed by space, which is the default).Then under No results behavior, I leave No results text blank, and tick Hide if empty and Hide rewriting if empty.
Fourth, I navigate to Format - Show: Settings and tick to make sure CoAuthor is an inline field.
After doing all this, the output should be nothing if there are no CoAuthor, and for the other two cases:

CoAuthor: Person X
CoAuthor: Person X, Person Y

As for using a template, you should be able to wrap the PHP generating the output in a test that checks for a non-empty field, e.g.:
if (!empty(print $fields['field_coauthor']->content)) {

I not sure where the template fragment you post come from, so I haven't posted the full code, but I hope you get the idea.


Date token to use user timezone instead of site timezone

You can try date token with custom date formatting

[entity:field-event-date:custom:m/d/y T]

replace entity with appropriate token (node, etc.), and insert the name of your date field.

Refer to PHP:date - Manual for custom date formats.


Where are the result and facet summaries for a search api view?

What I was looking for was the Current Search Block which is a module that comes with facet api.  It wasn't showing up for me because I needed to go into the block configuration, and update what search page it should appear on.


Set a condition for one field to be unique in all the content types.

You can implement a custom validation constraint and a hook_entity_bundle_field_info_alter to set the new constraint to your field.

Check: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint


How to show users who have not flagged a node with any flag?

It's always tricky when trying to display "things that aren't" because Views rely on things that are, even when querying out empty fields.

I haven't tried to recreate your example, but here are some comments that might help start you up:

Do it for one flag first

Once you have a working example related to only one flag it's easy to repeat the steps adding conditions for other flags. This is difficult enough to figure out for one flag alone.

List NOT flagged

To display content that isn't flagged, you must untick the option Include only flagged content in the Flags: flagname Relationship, and then use the Filter Flags: Flagged set to Not flagged:

How to list content that is not flagged.

Users who aren't here please identify yourselves!

It's impossible to list users who "aren't". You can only list all of them and then filter out the ones who "are".

If you start with Content Views, you can list content that hasn't been flagged, and you can show which users flagged it, but you can't list which users haven't flagged it, because there is no relationship between nodes and users who haven't flagged it!

A better option might be to go with User View. You can add Relationhip to the relevant flag, don't limit only to users who flagged, and adjust to Any user. Add Contextual filter Flags: Entity ID and set the default value to Content ID from URL, but don't forget to Exlude under More. Add a Filter Flags:Flagged and set to Not Flagged, but this way you only get users that haven't done any flags on any nodes.

You need some additional module to combine and help with showing things that aren't. With Content Views you can't list usernames of people who haven't flagged, while with User views you can only show people who haven't used the flag at all, you can't show a user who hasn't flagged a node if that user flagged another node with that same flag.

Views Reference Filter module

This module has a cryptic explanation on its project page, but could be useful in your case to pass one views results to the main views display to combine the results so you get something meaningful.

Views Reference filter module can be used to filter a View with the results of another (Entity Reference) Views Display. It can pass arguments to the embedded view:

You can probably create one View listing all Users who are allowed to flag Content, create another view that shows the users that have flagged it, then filter the first view with the negative second one. Just remember that the Field type of the Views Reference Filter must match the type of ER Views Display type (uid-user).

Introduce Flags Relationship

You need to add a Relationship that contains information about the node flag status. I doubt you can do that with User's flaggings without another Relationship before it that connects to the user who flagged, which is a roundabout way.

Just use the Flags: flagname, don't limit to Include only flagged content, and do set it to Any user.

Later you can add more Relationships to display users names etc, first you need to focus on making the filtering work.


extracting data from specific content type

You can create a custom migration for that node type - see https://www.drupaleasy.com/blogs/ultimike/2016/04/drupal-6-drupal-81x-custom-content-migration (more than you need for just the one migration, but it should help).


Yes, it is possible.

Go to "Home » Administration » People » Permissions"
Select the roles shown at the top right
Add a new role using the input textbox at the bottom

Your role will be created.


After researching more examples out there in the Web, I've finally managed to make this work, however I'm still not sure why it was not working before...

Working code:

<?php

/**
 * @file
 * Implementation of hook_entity_view_alter();
 */

function test_module_entity_view_alter($entity, $type, $view_mode) {
    drupal_set_message(t('Hello world!'));
}

Moving on to further modifications. Thanks everyone!


From main_ one would think you have a prefix set up on your production site or the development site and perhaps not or werent at the time of upgrade. It's quite confusing what you see, but one thing for sure: compare prefix settings and check MySQL for SHOW TABLES LIKE '%semaphore%' and go from there.


You could try this:

function my_module_home_index(){
  $sections = array();

  $home_livre = db_query("SELECT tax.name as section,field_categorie_tid as tid,field_title_value as titre ,field_prix_value as prix ,t.entity_id FROM {field_data_field_title} as t
    join {field_data_field_prix} as pr on pr.entity_id = t.entity_id
    join {field_data_field_categorie} as cat on cat.entity_id = t.entity_id
    left join {taxonomy_term_data} as tax on tax.tid = cat.field_categorie_tid
    ")->fetchAll();

  foreach($home_livre as $book){
    if (!isset($sections[$book->section])) {
      $sections[$book->section] = array(
        'categorie' => $book->section,
      );
    }

    $sections[$book->section]['livre'][] = array(
      'id_livre' => $book->entity_id,
      'titre' => $book->titre,
      'prix' => $book->prix,
    );
  }

  // The above will set up $sections as an associative array, but you need
  // to return an indexed array, so run it though array_values()
  return array_values($sections);
}

Basically, The first book that comes along with category "A" will create a new child the in $sections array with a key of "A". The book will then be nested in that child. If another book is found with category "A" then instead of creating a new category child, the book is nested inside of the same "A" category.

Note that I've not tested this code live so might need some tweaking


How to set the "Read More" link (in Rewrite Rules for Body field) to point to the node url instead of the title?

Just change the More link path to the node/[nid]

Add field nid to the views field and exclude from display. Make sure nid is above body field. Re-arrange the fields by clicking on select list next to field label and drag nid field to top of body field. It works !

Drupal l function while generating links will convert automatically to path alias blog/blog-title !


How to print the Views title in page.tpl.php?

You can aptly use this function views_embed_view(). This will help you to print out the view, passing arguments.


I ended up using this code:

chdir('/path/to/drupal/sites/example.com/');
define('DRUPAL_ROOT', '/path/to/drupal/core');
require_once('/path/to/drupal/includes/bootstrap.inc');
drupal_override_server_variables(array('url' => 'http://example.com/'));
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

It could perhaps be more efficient but it works from crontab.


How to show/hide the prefix/suffix of fields in node templates?

On node level you can configure the content of prefix and suffix in the field settings and you can show/hide them for each view mode separately.

So you rarely need to override this programmatically and this is not easy, because the prefix and suffix is not added as extra render elements, but to the markup string of the formatted field value. So you need string manipulation to subtract the prefix and suffix again.

A simple solution could be to display the database value, and so bypassing the field template altogether, by using the node object:

{{ node.field_example.value }}

But then you lose all formatting options, not only prefix/suffix.


How do I run cron as an authenticated user?

I don't think this is possible w/o some shenanigans.  If you look at drupal_cron_run(), you will see that it changes the user to anonymous (around line 5337 in includes/common.inc):

// Force the current user to anonymous to ensure consistent permissions on
// cron runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user();

The only way around this would be to implement a hook_cron() and alter its weight so that it gets called first, and have it swap in the user that you want (which can be a little tricky in some cases.  This may also cause problems with some cron hooks, like search_cron(), which assume the anonymous user, and end up with weird results (in this case, there may be a security problem where privileged information is revealed to the anonymous user).


How to make search on all fields (title and tags as well as body)?

One thing you can do to control which fields are included in your search index is to go to your specific content type's 'Manage Display' page.

So go to Structure --> Content types --> Your content type --> Manage display.

On that screen, you'll see a collapsed section called 'Custom Display Settings'.  Just click on it to expand it.  You should see that you can check to enable the 'Search index' display to be customized (Usually only the teaser or summary is included for customization by default).  Check the 'Search index' box and save:

That will provide you with a brand new "Search index" tab on this screen.  Click on it and start customizing which fields you want to be included for this content type's search index:


How to load Ubercart orders for certain user ID?

Find the following function in Drupal 7:

/**
 * Custom function to return list of orders for certain user
 */
function foo_get_user_orders($user, $order_status = 'completed') {
  $query = db_select('uc_orders', 'uo');
  $query->addField('uo', 'order_id');
  $query->addField('uo', 'order_total');
  $query->addField('uo', 'order_status'); // optional: $query->addField('uo', 'product_count');
  $query->addJoin('LEFT', 'uc_order_products', 'p', 'p.order_id = uo.order_id');
  $query->addField('p', 'nid');
  $query->condition('order_status', $order_status);
  $query->condition('uid', $user->uid);
  $result = $query->execute()->fetchAll();
  return $result;
}

For Drupal 6, please install dbtng module and it should work as well.


Strange PDOException Error With Computed Field

Try moving the WHERE clause to before the GROUP BY statement:

$entity_field[0]['value'] = db_query('
  SELECT COUNT(field_review_payment_value) AS `Rows`
  FROM (field_data_field_review_payment)
  WHERE entity_id IN (:nids)
  GROUP BY (field_review_payment_value)
  ORDER BY `Rows` DESC
  LIMIT 1',
  array(':nids' => $nids)
)->fetchField();

MySQL queries have to follow a certain format and the WHERE clause needs to be before GROUP BY, ORDER BY, LIMIT, etc.


How to make direct editing of cck imagefield?

Is it possible: Yes.
Is there a module for it: I don't think so.

What you need to do, is to display the form for the CCK field. Since much of the CCK logic is wired into the node form, the easiest thing to do, would be to display the entire form, and hide everything but the field you want to let users change.


how to show more information in user's profile

For things like last 10 posted content, I believe you can use contextual filters in Views. With that you can create pages like /user/somebody/posts where Views will show you the last contents of user for example, also I believe you can make a block out of such a view that you can place on profile pages.

Also it may worth for you to check out the Profile2 module, you can create multiple types of profile pages with it for example.

http://drupal.org/project/profile2


Display two products as two radio buttons with a single Add to Cart Form

Drupal commerce was designed to do exactly this without going through lots of hoops, but it might be a bit tricky to get into.

Instead of making one an argument of another I'd create one product display with two different attached products, for which you can set an attribute field and a price. You can do so by having a node content type to act as a 'product display'. To do so you require inline_entity_form and commerce_product_reference (part of the commerce package).

On the product-type add a field the distinguish 'premium' product and make sure to hit the 'Enable this field to function as an attribute' checkbox.
Add a product reference field to a (new) content type you call 'product display' (or if you plan on selling more different kinds of products you can use a more specific name line 'event ticket' or something).
For the field widget choose 'inline entity form (multiple)'.
Create a node of the 'product'-type and add the two different products and their properties; for the 'premium' product make sure to change the price and the attibute field we created earlier.
Save the node.

If all went well you should end up with a selection box on the 'product display' node, allowing the users to select which version of the product they want to buy.

If you find this too vague, there is a detailed explanation (with pictures) on it here: Product Attributes & Variations. It does not use inline entity form so the 'attach products' involves a drop down on the images, whereas inline entity form will allow you to create and edit the entities directly on the node.


Exporting from Field Collections and Importing to New Content Type

Some time ago I did something similar, but with normal fields. I used Views Bulk Operations.

First I've created a view which listed all the nodes of the particular node type and added the VBO checkbox to execute arbitrary PHP code.

On the view's page I've checked all the nodes and pasted in the PHP textbox the code which updated field B values based on the field A values. In your case you should create a new node based on the field collection.

Finally, when VBO finished executing the code for all my nodes, I went to the content type fields page and deleted field A (in you case the field collection).

Done!


DB API: How to get a list of nodes ordered by highest comment creation date?

The best place to query for that is the node_comment_statistics table.

It contains the relevant comment statistics such as comment count and last comment timestamp for a node.

e.g: Query for article nodes ordered by last_comment_timestamp DESC

$query = db_select('node_comment_statistics', 'c');
$query->join('node', 'n', 'n.nid = c.nid');
$query->fields('c', array('cid', 'last_comment_timestamp')); // fields
$query->fields('n', array('nid', 'title'));
$query->condition('n.type', 'article'); // e.g filter for articles only
$query->condition('n.status', 0, '>');
$query->orderBy('c.last_comment_timestamp', 'DESC'); // Order by last commented
$results = $query->execute();

foreach($results as $row) {
  drupal_set_message('<pre>'.print_r($row,1).'</pre>'); // debug
}

node_comment_statistics table schema:

mysql> desc node_comment_statistics;
+------------------------+------------------+------+-----+---------+-------+
| Field                  | Type             | Null | Key | Default | Extra |
+------------------------+------------------+------+-----+---------+-------+
| nid                    | int(10) unsigned | NO   | PRI | 0       |       |
| cid                    | int(11)          | NO   |     | 0       |       |
| last_comment_timestamp | int(11)          | NO   | MUL | 0       |       |
| last_comment_name      | varchar(60)      | YES  |     | NULL    |       |
| last_comment_uid       | int(11)          | NO   | MUL | 0       |       |
| comment_count          | int(10) unsigned | NO   | MUL | 0       |       |
+------------------------+------------------+------+-----+---------+-------+


How to access a custom field in a field twig loop?

As you are creating the twig template for a field and try to access the fields / data that is not available, you can write your custom code in preprocess function and you should use the template_preproces_field and create custom variable with desired data and use that variable in custom twig template.

In preprocess function

$variables['myVariable'] = 'My Desired Data';

In Twig use the variable which will print 'My Desired Data'

{{ myVariable }}


Is there a way I can set access to specific form elements?

You can use the FAPI #access property:

$form['some_element']['#access'] = user_access('some permission');


How to get custom line item's custom attribute's value after order complete

You can use the entity_metadata_wrapper on commerce_order

/**
 * Implements hook_commerce_checkout_complete
 */
function package_designer_commerce_checkout_complete($order) {

  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    if(isset($line_item_wrapper->field_package_configuration)){
      $package_configuration = $line_item_wrapper->field_package_configuration->value();
      // You can also get the raw value like this:
      // $package_configuration = $line_item_wrapper->field_package_configuration->raw();
    }
  }

}


hook_views_pre_render - how to print field x after each loop

This isn't the answer I was looking for, but it solves the issue until a better method is found.

Basically, the problem is that a specific field - a custom text 'find out more' field was showing three times (for example) when a row had three authors (entity ref. fields)

Since the 'find out more' field was the last item in each row, I overrode the "views-view-unformatted" twig template and, inside of the 'for' loop I added an extra bit, to change the class of the last item. Then, with CSS, I could hide the fields with 'views-row' class, and display 'views-row-last'

Here's what I added to that twig file:

    {% if loop.last %}
        {%
        set row_classes = [
          default_row_class ? 'views-row-last',
        ]
       %}

    {% endif %}


My "easier way" was simply to copy all of the core css and js as well as the all of the modules css and js up into my CloudFiles container and then configure the CDN module to automatically rewrite the URLs of any .css or .js file.


The answer (that worked for me) is to use FormattableMarkup:

use Drupal\Component\Render\FormattableMarkup;

$row[] = new FormattableMarkup('<span>@somevalue</span>', ['@somevalue' => 'some value']);


How to decrease the width of the sidebar for a specific page?

You could use drupal_add_css() to conditionally include a custom CSS file on particular pages.

You could also add a custom template in your themes templates folder. If you clear caches after including it, it will automatically be included as long as it follows the Drupal template naming conventions.


Drupal.behaviors js code executes mutiple times (depends on active modules)

once() may work in many cases. I've also used a flag like:

(function ($, Drupal) {
  let flag = false;

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      if (flag === false) {
        flag = true;
        console.log('This should only display one time.');
      }
    }
  };

})(jQuery, Drupal);

Please note that I only wrote this in this comment box from memory and didn't actually test this code.

Also FYI, the Drupal.behaviors is correctly running many times, since it is supposed to update every time some kind of state changes that would require it to update (like an AJAX call). So you do have to take extra steps on your side to ensure that certain code only runs once.


voting in all fields before submit results

The only way I can think of to do this is to override the javascript function Drupal.rateVote which is declared in the file rate.js. It would require considerable work to achieve what you want.

You can have a look at this question where someone else had to override a javascript function from a contrib module.


How used function drupal_render_children in file twig?

Well, for one, it is deprecated. Two, you cannot use PHP functions directly within the Twig template.

You can implement the appropriate preprocess hook to do this, to pass to Twig as a variable.


What are the major differences between solr modules

I would recommend using Search Api Solr. Search Api Solr is a little bit more complex; however, it is more powerful.  In addition there are many sub-modules that allow you to extended the search funcionality.

You should consider reading the article Battleplan for Search & Solr in Drupal 8.

According to this post.

  The two maintainers of Search API and Apache Solr have meet in person and have determined a way forward for advanced searches with Drupal and they both have agreed that Search API is it.


How to substitute a value of an exposed filter for views?

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


How to hide header and footer from 404 page?

I do this by overriding the template used by the theme. In the template.php:

/**
 * Set path to page-error.tpl if http error is returned.
 */
function yourtheme_preprocess_page(&$vars) {
  // Set custom error template:
  $http_status = drupal_get_http_header("status");

  if (isset($http_status)) {

    switch ($http_status) {
      case "403 Forbidden":
      case "404 Not Found":
      case "500 Internal Server Error":
        $vars['theme_hook_suggestions'][] = 'page__error';
        $vars['http_status'] = "Error: " . $http_status;
        $vars['error_message'] = drupal_get_messages();
        break;
    }
  }
}

Then you can create page--error.tpl.php in your templates directory using whatever regions you want to display. This has added the benefit of automating error pages, so you don't have to set a path in the site config.


why don't set the placeholder attribute for contact field?

edit

$form['name']['#attributes']['placeholder'] = array(t('Enter your name'));

to

$form['name']['#attributes']['placeholder'] = t('Enter your name');

then execute "flush all caches"


Redirect on Custom page after one time login link

Since the form builder for user/reset/%/%/% (user_pass_reset()) is using the following code to redirect the user, you can only replace the form builder with one that redirects the users where you want.

      $token = drupal_hash_base64(drupal_random_bytes(55));
      $_SESSION['pass_reset_' . $user->uid] = $token;
      drupal_goto('user/' . $user->uid . '/edit', array('query' => array('pass-reset-token' => $token)));

If you do that (which means implementing hook_menu_alter()), be careful of how the workflow is modified. If you need to change that radically, and you want to be sure not to introduce security risks, I would rather:

Alter the URL returned from user_pass_reset_url(), so that users are redirected to your page
Implement a form builder for your page using the code used by user_pass_reset() as guideline


devel themer will help you understand what you can over ride and what variables are available.

hook_form_alter() can be used to trim fields that you don't want and to re order the form, put things into groups etc.


How to change link in a view depending on state of a certain field

You can use the field token of the field which is used to picks whether a conference is supported or unsupported. Then you can link it to a node or external link,


How to define an intermediate admin user as the default install profile on fresh drupal 7?

You need to create a new role

$admin_role = new stdClass();
$admin_role->name = 'myadminwithoutmenuaccess';
user_role_save($admin_role);

//This will give them all perms
user_role_grant_permissions($admin_role->rid, array_keys(module_invoke_all('permission')));

Then you just revoke administration menu

 user_role_revoke_permissions($admin_role->rid, array $permissions = array('administration menu'))

if you need to get the $rid at a later time you can do
user_role_load_by_name()


There are two things which govern access to views and their results.

The access settings for the view. These are found on the view page and can be based on permissions or roles. This is a base rule for who can see this view.
The access settings for the content being displayed by the view. This is definitely where things get a bit funky. Essentially, views doesn't collaborate with Drupal permissions or hook_node_access(). It will show content users might not have the permission to see or content that has been safeguarded by hook_node_access(). That makes these two methods pretty useless for protecting content.

What actually happens is that views queries the {node}, {user} or other entity table and retrieves nid's, uid's or other entity id's. At no stage does it check permissions or hook_node_access(). However, when checking nodes it does join with the {node_access} table to determine if that system has any rules about the content. Note that hook_node_access() doesn't really have anything to do with the node_access system.

By default you probably aren't using the node_access() system, but if you are using a module like content_access then you are using this system and it may be restricting views results.

If you have devel module installed, you can use the block with the title Devel node access and place it on a node page. Now when you visit that page, it will show the roles and their access level. Note that you need to access that nodes page with a user with that role before it will show in the block. This is the access record which will determine if the node can show in a views result.


Get interface translation LID (Locale Id?) using source string value

OK: Figured it out through trial and error. Here's the code:

$db = \Drupal::database();

$query = $db->select('locales_source', 'ls')->
    condition('source', $source_string)->
    fields('ls', ['lid'])->
    range(0, 1);

$lid = $query->execute()->fetchField();

UPDATE: Found a cleaner way. Here's the code:

$storage = \Drupal::service('locale.storage');
$string = $storage->findString(['source' => $source_string]);

if (!is_null($string)) {
  $lid = $string->lid;
}

I'm using this now in a custom module. Seems to be working well.


My guess is that you're using the general drupal roles and permissions rather than the organic_groups ones.  Start by reading https://www.drupal.org/node/2340349, and then if you are still stuck, clarify exactly roles and permissions you've been modifying.


How we can generate Latitude/Longitude at the time of import while using Feed module

I use the location module in tandem with the location feeds module (http://drupal.org/project/location_feeds).  It can be configured to geocode the the addresses at the time of import.

I had to adjust some timeout settings as its possible to try to geocode addresses faster than the geocoding api allows.


Disable click event on Next button on checkout form's first step if all cart products are removed

What module are you using for the cart?

you can also use preventDefault() function to stop the page from loading to the next page.


How to render a field above the node title using omega sub-theme

You might get a bit more luck using the field_view_field function:

function MYTHEME_preprocess_region(&$vars) {
  $theme = alpha_get_theme();
  if ($vars['elements']['#region'] == 'content') {
    $node = $theme->page['node'];

    $vars['slideshow'] = field_view_field('node', $node, 'field_slideshow_images');
  }
}

And then use print render($slideshow); in your template file.

You might need to play with the 4th parameter to field_view_field() ($display) a bit if you have custom settings on your display for that field, but it should be a good place to start.


Building a non-config, programmatically-created, semi-dynamic, semi-manual menu

Without delving too much into the specifics of your complex configuration management, I'd venture to say that you should use Drupal 8's built-in configuration sync to export config to YAML and commit it to your version control repository (git or what-have-you) so that you can deploy your config along with your code.

Then, you can use the Config Filter, Config Split, and Config Ignore contrib modules to split off certain configuration from the sync directory into separate directories that can be used or ignored in different environments.

NOTE: If your users are all adding content in the production environment, you'll need to make sure your lower environments always have the latest config before deploying to a higher environment. This would be the case even if you didn't use config sync; it will just be a different workflow (i.e., you'll need to drush cex the latest config from Prod and drush cim it into your Dev environment, rather than grabbing a fresh sqldump from Prod.)

More info:
https://www.o8.agency/blog/tips-dev-team-using-config-split-and-config-ignore-fine-tune-your-configuration-management

There's work underway to integrate some of the functionality provided by Config Filter and Config Split into Drupal 8 core. This is the way things are headed, so there's really no downside to config export anymore if you do it correctly.

Admittedly, setting it up can be a pain, but it's a different pain (and, I think, a less painful pain) than keeping all your config in the database and trying to keep that in sync across your local, dev, stage, and prod environments.


Disable creating new taxonomy terms in term reference field

The content taxonomy module adds additional functionality to prevent new terms with the autocomplete widget.

  D7 and Content Taxonomy

  The module provides extensions to Drupal's
  core Taxonomy Term Reference Fields. At the moment, following
  extensions are available:

  Parent term selector in the field settings (for options lists)
  Options for new terms in autocomplete (Autocomplete Deluxe widget supported as
  well):

  Allow and insert new terms (default behaviour)
  Allow and insert new terms into a separate vocabulary
  Deny any new terms


Submit to external url via Ajax & get return

Sounds like it's spinning forever because of the js error.

Where is the error occurring? In jQuery library?

If so use an uncompressed version of jQuery and it may be easier to debug.

Maybe even temporarily hack jQuery core to remove error and see if that fixed your problem before spending time figuring out how to fix it properly...


Why did my site crash when I moved module and theme folders?

Drupal keeps an extensive cache of all functions in (contrib) modules and the files in which those functions can be found. Since you moved the files, Drupal is probably attempting to call a function from a file that is no longer there. (It should have thrown a more detailed error in your webserver log.)

Steps to repair could be to move the files back to their original position (Drupal works fine without contrib and custom folders, but it might be easier for yourself). Or enter the database and attempt to empty all tables that end in _cache. That should make Drupal reïndex the functions.


This is what your looking for.

The Drupal 8 code is the following one.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $suggestions[] = 'page__' . $node->getType();
  }
  return $suggestions;
}


How to connect database in UnitTestCase subclass?

See https://www.drupal.org/phpunit for better documentation.

There are 4 test base classes:

UnitTestBase, pure unit tests where everything but your code has to be mocked and only supports classes
KernelTestBase, which provide a basic in-memory drupal environment. Much faster than browser tests but more tedious to set up, you have to explicitly install tables you need and depend on all modules you need explicitly
BrowserTestBase, the replacement for WebTestBase, better apis (uses mink and so on) but just as slow.
JavaScriptTestBase, phantomjs based JS tests, even slower but can actually execute JS.


what is the equivalent for category in wordpress in drupal websites?

Everything you mention in your question is a Taxonomy, a way to sort your content into meaningful groups. This mostly helps to improve site navigation, discoverability and consequently clarifies what the website it about (boosting a keyword ranking might be too strong of a claim).

In WordPress, it's custom to name the main Taxonomy Vocabulary as Categories (they can be hierarchical) and to have additional Taxonomy Vocabulary tags that are optional and sort the content into categories that aren't necessarily closely related to the website main topics.

In Drupal, Taxonomy module allows you to create your own Vocabularies and use them as you see fit. You get the Vocabulary named Tags out of the box, but don't let that name confuse you. You can use Tags as your main Categories Vocabulary. You can also rename the label "Tags" into "Categories" (machine name will remain tags but that isn't user-facing).

Or simply don't use Tags Vocabulary anywhere, delete the field from Articles content type that references it. Create all new Vocabularies, name them as you like (Categories, and Tags, with different machine name) and use them the same way as you did in WordPress.

There are no technical differences between terms coming from different Vocabularies. A term from Categories, and a term from Tags is linked to an article in the same way technically.

The SEO value of using Taxonomy is in how smart you are about categorizing your content, knowing your visitors and offering them what they expect/want/value.


Does using Views & Panels on every page will effect site performance (speed)?

Panels is actually sometimes faster than core is on it's own.

http://www.codeenigma.com/en/blog/performance-panels

And that's without utilizing caching, something Panels can do much better than core, because it allows you to do it from on a page by page basis, down to on a block by block basis.


You can get all nodes, then with a foreach create a translation for each node.

$nodes = \Drupal::entityQuery("node")
//->condition('type', 'my_custom_type') //use this for specific content types
->execute();

$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

foreach ($nodes as $node) {
  //Creating the translation Spanish in this case
  $node_es = $node->addTranslation('es');
  $node_es->title = 'Mi prueba!';
  $node_es->body->value = '
El cuerpo de mi nodo.
';
  $node_es->body->format = 'full_html';
  //Saving the node
  $node_es->save();
}

You can add some fields like title and body, or just save.


The values in $form_state['values'] are all sanitized.

The values in $form_state['input'] are the raw unsanitized form values.

$form_state['storage'] is usually only used on multistep forms to keep data for other form steps.

Where possible always use the values from $form_state['values'].

See this post for more information: Avoid using data from $form_state['input']

To quote that linked article:

  The Form API's drupal_validate_form() and _form_validate() functions
  take care of populating a safe set of data in $form_state['values'],
  using sanitized data from $form_state['input'].


How to override links in each Views feeds?

I found the url_alter module: http://drupal.org/project/url_alter,
Some details from the module's project page:

URL alter is a utility module that adds two new hooks for other modules to implement: hook_url_inbound_alter() and hook_url_outbound_alter(). These hooks also replace the need for the special, silly custom_url_rewrite_inbound() and custom_url_rewrite_outbound() functions commonly found in settings.php.
It also provides an interface for administrators to enter in their own hook_url_alter code without needing to create a custom module.

It has some usable hooks:
hook_url_inbound_alter() and hook_url_outbound_alter()


How do I execute a view in a custom module and print the output (as HTML markup)?

Views implements its own render element type (Drupal\views\Element\View), which you can use like so:

return [
  '#title' => 'Hello world',
  'view' => [
    '#type' => 'view',
    '#name' => 'myfirstview',
    '#display_id' => 'page_1',
    '#arguments' => ['foo', 'bar'],
    '#embed' => TRUE,
  ],
];

If you need to manipulate the View before rendering it, (you mentioned exposed filters), you can do that first and pass along the object:

$view = Views::getView('myfirstview');
$view->setFoo('bar');

return [
  '#type' => 'view',
  '#name' => 'myfirstview',
  '#view' => $view,
  '#display_id' => 'page_1',
  '#embed' => TRUE,
];


The function file_create_url() in D7 needs a uri (see this useful article). You can typically access the uri of a file this way:

$user_object->field_name[LANGUAGE_NONE][0]['uri'].

In your case, since $user_profile seems to be an array of fields, try:

file_create_url($user_profile['field_cover'][LANGUAGE_NONE][0]['uri']).

This should return the full URL of the image.

Further information in your question may help me fine tune this answer.


how to give relative path in drupal for setting an image

Try this code.

$path = drupal_get_path('module', 'myModule') . 'image/projectsetup.jpg';

now set src = '$path' into your .module file where you set image src.


Instantiate Controller with Interface not concrete class

In the BaseController file, you have a typo in the interface classname. Fix that and clear the cache. Your module namespace seems to be inconsistent too. Your custom classes should be namespaces under the same module name they are defined in.

use Drupal\my_api\Services\HttpRequest\HttpRequestInterace;

to

use Drupal\my_api\Services\HttpRequest\HttpRequestInterface;

PHP can’t figure out where the class is due to the typo, and expects it to be defined locally in the Controller class file, hence why your error message lists an incorrect namespace to the interface.


Is there a module or easy way to break up nodes into multiple pages?

The paging module will help you with that


How do I change the Default Query of a Views Exposed Filter with hook_form_alter()?

Try this out with hook_views_pre_build

/**
 * Implements hook_views_pre_build().
 */
function MODULE_NAME_views_pre_build(&$view) {
    if ($view->name == 'VIEW_MACHINE_NAME') {
        //- Set the exposed filter to new value
        $view->filter['EXPOSED_FILTER_NAME']->value = '0';
    }
}


Create a Views Block to show all Node 'Attached Files' as a File list.

Based on the discussion above, create a new view, and configure and filter it however you need. the main part is to have the file display as link for download. For this, when you add the relevant field to views, in the settings form, there will be a drop down option for "Link this field to". Choose "File" from there and the field value will be linked to it. Clicking on it will allow the user to download the file. Hope this helps.


Customizing the Tag page shown by default in Drupal 7

The ideal way to customize the tags pages(www.mysite.com/tags/mytag_1) is to enable the view "Taxonomy term" and then customize it the way you need it. As you might already know Views provides much more flexibility and easy to customize.

If you do not want to use Views and only want to update the template then refer to the link


Okay I got a bit working. But it only fills the select options after the textfield is losing focus. How can I make it so that while typing in the textfield, the select options is filled with data. Kinda similar as to autocomplete?

And another question, if i press enter I get an HTTP error . An Ajax HTTP request terminated abnormally. path: /?=system/ajax
status : text
responsetext:
ready/state:4

Any ideas why this is happing?

<?php

function dropdown_menu(){

$items['test/drop'] = array(
'title' => 'Fill select options from db',
'page callback' => 'drupal_get_form',
'page arguments' => array('select_dropdown'),
'access callback' => TRUE,
'weight' => 4,
'type' => MENU_NORMAL_ITEM,
);

return $items;
}

function dropdown_submit($form, &$form_state) {
//dpm($form);
drupal_set_message('Submit handler was called.');
}

function select_dropdown($form, &$form_state) {

$form['searchfield'] = array(
        '#title' => t('Search database and fill select options'),
        '#type' => 'textfield',
        '#required' => TRUE,
        '#maxlength' => 115,
        '#size' => 55,
        '#weight' => 0,
'#default_value' => 'look for it',
'#ajax' => array(
  'event' => 'change',
  'callback' => 'search_db',
  'wrapper' => 'dropdown-second-replace',
),
    );

  // Get the list of options to populate the first dropdown.
$options_first = _drop_get_first_dropdown_options();
$selected = isset($form_state['values']['searchfield']) ? $form_state['values']['searchfield'] : key($options_first);
$form['dropdown_second'] = array(
'#type' => 'select',
'#title' => 'Options filled from db',
'#prefix' => '
',
'#suffix' => '
',
'#size'=>10,
'#options' => _drop_get_second_dropdown_options($selected),
'#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
);

//  $form['submit'] = array(
// '#value' => 'Submit',
//   '#type' => 'submit',
// '#submit' => array('dropdown_submit')
// );

  return $form;
}

function drop_dependent_dropdown_callback($form, $form_state) {
return $form['dropdown_second'];
}

function search_db($form, $form_state) {
return $form['dropdown_second'];
}

// normally pulling data from the database.
function _drop_get_first_dropdown_options() {
return drupal_map_assoc(array(t('empty')));
}

function _drop_get_second_dropdown_options($key = '') {
$matches = array();
$result = db_select('tabel', 'c')
->fields('c', array('product', 'xtra'))
->condition('product', '%' . db_like($key) . '%', 'LIKE')
// ->range(0, 10)
->execute();

// save the query to matches
foreach ($result as $row) {
$matches[$row->product] = check_plain($row->product) . ' xtra:' . ($row->xtra);
}
return($matches);

}


During installation, the 'set up database' phase was skipped. Is that normal?

Did you perhaps already have a settings.php file in place with the database information already in it? If Drupal can find that, it will use that information instead of prompting you and creating a new settings.php file itself.


8 - Register form automatically fills in input fields

I found a solution thanks to the Drupal Community

Apparently this is defined in the core of Drupal: core/modules/user/src/RegisterForm.php

The following should be set to FALSE

// For non-admin users, populate the form fields using data from the browser.
    if (!$admin) {
      $form['#attributes']['data-user-info-from-browser'] = TRUE;
    }

However it would be better to not mess with the core values and write a form_hook_alter instead in your theme file:

function MYTHEME_form_alter( &$form, &$form_state, $form_id ) {
  if ( TRUE === in_array( $form_id, array( 'user_register_form') ) ) {
    $form['#attributes']['data-user-info-from-browser'] = FALSE;
  }
}

This solved the problem.


Use the hook_form_FORM_ID_alter and add a custom submit handler.

function example_form_form_id_alter(&$form, &$form_state,$form_id){
  $form['#submit'][] = 'example_form_id_submit',
}

function example_form_id_submit(&$form,&$form_state){
  $form_state['values']['resource_name'] = 'resource_' . $form_state['values']['resource_name'];
}


How to programatically submit an entityform?

I don't think you can submit entityform using drupal_form_submit() as it's entity, not a standard form.

The best way is to save the entity as you did, but you are missing field_attach_submit which is necessary to perform operations on field data submitted by a form.

The syntax is:

field_attach_submit($entity_type, $entity, $form, &$form_state, $options = array())

Example based on given $form_state:

$form_id = $form_state['build_info']['form_id'];
$entity = $form['#entity'] ?: $form_state['build_info']['args'][0];
$entity_type = $entity->entityType();
$entity_info = entity_get_info($entity_type);
$entity_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
list(, , $bundle) = entity_extract_ids($entity_type, $entity);

// Copy top-level form values that are not for fields to entity properties,
// without changing existing entity properties that are not being edited by
// this form. Copying field values must be done using field_attach_submit().
$values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values;
foreach ($values_excluding_fields as $key => $value) {
  $entity->$key = $value;
}
if ($entity_info['fieldable']) {
  field_attach_submit($entity_type, $entity, $form, $form_state);
}
$entity->created = isset($entity->is_new) ? REQUEST_TIME : $entity->created;
$entity->changed = REQUEST_TIME;
entity_save($entity_type, $entity);

Alternatively you can submit entity form by using entityform_save(), e.g.:

$form = new Entityform(array('type' = 'my_entitty_form', 'language' => LANGUAGE_NONE));
$form->field_entityform_1 = array(LANGUAGE_NONE => array(array('value' => 'field_1')));
$form->field_entityform_2 = array(LANGUAGE_NONE => array(array('value' => 'field_2' )));
$form->uid = 1; // this is the form id
entityform_save($form);

Source: sushantpaste's gist


How to add "new" icon on node view page for predefined time frame

You can do this at least two ways:

1)  Edit your theme's node.tpl.php to include some PHP code that compares the current date and the node creation or modification date, and, if it's within the predefined timeframe, prints that "new" icon wherever you want it, or,

2)  Create a preprocess_node() hook in either a custom module or in your theme that sets a variable that can be used in your node.tpl.php file for the same purpose.

SNIPPET ADDITION:

A quick (but verbose for self-commenting purposes) preprocess() hook in your template.php file could look something like this:

function phptemplate_preprocess_node(&$vars) {

  $node=$vars['node'];

  $two_weeks_ago = time() - (14 * 24 * 60 * 60);

  $node_creation_time=$node->created;
  $node_changed_time=$node->changed;

  if ($node_creation_time >= $two_weeks_ago || $node_changed_time >= $two_weeks_ago) {
    $this_node_is_new="THIS NODE IS NEW!";
  }

  $vars['this_node_is_new']=$this_node_is_new;

}

This would provide a $this_node_is_new variable in your node.tpl.php template file(s) when the node was created or modified within the last two weeks.


How to create an Ubercart add to cart button programmatically with defaults?

I managed to use cart links instead:

/cart/add/p27_a6osfsdfsdfsdf_a7o706_a2o8_a1o515_q1-idomainName?destination=cart


Finding data using MySQL queries in the Node tables

The concept that you are missing is that field data can be on any Drupal entity, nodes, users, etc.  This means that when you JOIN, you need to add in some additional clauses.  In particular, you need to check the entity type in the field data, as the entity ID isn't unique across entity types.  You also need to check that the field value isn't deleted.  So, you would have something like

LEFT JOIN field_data_field_usted_es p
  ON p.entity_id = u.uid AND p.entity_type = 'user' AND p.deleted = 0

Those three columns are typically all on need to JOIN ON.  The rest of the columns would be what you return in the query, or use in a WHERE.

Most of the time, it is easiest to build up a query with Views, preview the SQL, and then use that as your starting point for a query outside of Drupal.

In your case, you could also use Views Data Export to generate your CSV inside Drupal itself.


Control content access whilst creating content

Workbench, Workbench Access and Workbench Moderation modules could help you with access control and content management.

Workbench improves content management for Drupal 7.
It has more then 1200 reported installs.

Workbench allows to :

simplify the user interface for content creators and editors
limiting training and support time.
control who has access to edit any content based on an organization's
structure not the website structure
customize editorial workflow that integrates with the access control
feature described above or works independently on its own

Workbench Access
Workbench Access provides hierarchical permissions across "Sections" of your website. You can use menus, taxonomy or create your own hierarchical structure for controlling access to the content.

Workbench Moderation
provides editorial workflow. It is a flexible system. It provides default workflow states like Drafts, Needs Review, and Published. You can also change these states to suit your needs.


I would use the Superfish module (http://drupal.org/project/superfish), recently this has added an option for megamenu which will allow you to build a display much like your screenshot. You will need to tweak the css to get the display how you would like it.

Demo: http://mehrpadin.net/demo/superfish/ (hover over "products" in the very bottom menu)


How can I update a field on a user profile with Drush

Take a look at Drush Entity. Here is a quote from its project page:

  ... you can query the entity system available for Drupal 8, 7 and (some of) 6.


Change part of theme according to time of day

You can define new variables in the array $variables in preprocess.

Assuming this is the page template:

modules/mymodule/mymodule.module:

function mymodule_preprocess_page(&$variables) {
  if ( ... ) {
    $variables['daynight'] = 'day';
  }
  else {
    $variables['daynight'] = 'night';
  }
}

Then use the variable in your twig code:

{{ if (daynight == 'day') }}

{{ else }}

{{ endif }}

Or shorter:

You will get some problems with caching. In drupal and in proxies and browsers. So this is probably not a server but a client side solution.


How can I redirect users after they cancel their accounts?

There are two fine ways to do it :

With Rules : If you have installed it already then you must use this. Select the event "After a user account has been deleted". Check the conditions you want and add action "Page Redirect".
With Hook : Write a hook_user_delete and add drupal_goto in your condition.


Media module: how to generate a pdf link?

Check out your file-types display settings in admin/config/media/file-types in combination with the field display settings you are using.


Pathauto, user profile alias from content profile fields

In the "Automated Alias" settings page there is a fieldset near the top with rules for treating special characters; check it to see how it is treating hyphens.


Drupal 8 hide meta tag fields in node form

I'll make the assumption you're using the Metatag module (https://www.drupal.org/project/metatag).

Unfortunately, this module doesn't allow fine-grain control of fields through its UI, so the only way I've found to hide these fields is through a form alter.

In this case, I'm modifying all node forms (use whatever hook fits your scenario here). Example, hiding the "advanced" fieldset entirely by disabling access to it, so it's not rendered:

function MY_MODULE_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['field_metadata']['widget']['0']['advanced']['#access'] = FALSE;
}

I'm sure this can be modified to target more specific nested groups/fields, but should give you a start at least!


What is the correct way to setup Drupal file permissions on a VPS?

user:www-data are the correct permissions IMO. For security reasons, the web server should not be able to write to the file system, except for files and temp folders. You haven't mentioned suhosin or anything so I'm assuming you have a typical setup.

Drupal have unfortunately made the above a bit confusing by including a method to update modules via the UI (v. bad idea IMO, swapping security for convenience).

If you still want to do it, it can be solved with *nix permissions on most platforms; the exact nature will depend on your server's architecture and setup. There's an example here and in the comments of the official docs page to get you going, but generally speaking just search for how to manage these permissions for your server type generically - there's nothing Drupal specific about the commands you need to run, so you're closing off a lot of potential help if you include Drupal as a keyword in your searches.


How can I include php file in my module without using composer?

Outside of autoloading, the only option Drupal provides itself is module_load_include(), which literally

Loads a module include file.
Examples:

// Load node.admin.inc from the node module.
module_load_include('inc', 'node', 'node.admin');
// Load content_types.inc from the node module.
module_load_include('inc', 'node', 'content_types');

The final part of the description is worth taking in separately as it's important:

Do not use this function to load an install file, use module_load_install() instead. Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file' instead.

It's also worth noting this function won't be around forever, the plan is to move it completely into the module handler service.


The main menu in Bartik only displays the first level.  Since it's hardcoded in page.tpl.php there's nothing you can do about it.

Here's how to get the menu to work properly:

In your theme settings (admin/appearance/settings/barti) disable "Main menu"
Go to admin/structure/block and add the "Main Menu" block to the header region (or wherever you want it)

Alternatively, you can also check out the excellent Menu Block module, which generates extra customizable blocks (1st level, 2nd level, etc) for each menu.


Drush rsync and drupal composer wrong destination dir

I had the same problem took me ages to find out what was wrong.
Turned out to be the slash (/) behind the root folder that was missing.

self.site.yml

remote:
  host: domain.com
  user: user
  root: /home/user/public_html/
  uri: http://domain.com

@see https://unix.stackexchange.com/questions/402555/why-add-a-trailing-slash-after-an-rsync-destination

Turned out to be a bug in drush
https://github.com/drush-ops/drush/pull/3405


I think you are looking for a node access module. There are many of them, for example http://drupal.org/project/content_access (configure access with roles directly) or http://drupal.org/project/tac_lite (control access by adding special taxonomy terms) and many more.

For your second question, you should always define some permissions (with hook_perm in D6, hook_permission() in D7) and then check that. That allows to configure through the UI, which roles have that permission and the code is not tied to your specific configuration.


Conditionally require user to complete a content type based on answers from other content types?

Interesting question (challenge), with quite some background info (so well documented question). It seems that at its core, this is the key challenge you need to address:

  Finally, I would need a dashboard to keep track of what content types are required, pending and have been completed - then once all of the required supplemental content type questionnaires are verified completed, allow the user to submit a finalized profile.

Here is a "rough step by step" answer you asked for:

Use the Flag module to introduce a set of flags related to your business content type. That set consist of 1 flag for each extra questionnaire (content type) that might possibly be needed. E.g. 1 flag related to "foreign operations" and another flag related to "employees".
Use the Rules module to automatically set the appropriate flags to indicate that some related content type is required, but still missing (or not fully completed yet).
Whenever such related content type gets completed, you "unset" (automatically, via Rules) its corresponding flag.
Should you want to implement some review process (as per your "review completed" you mentioned), you may want to add the Workbench module to the mix (maybe some of its related modules also?), so that the "unset" of these flags only happens after the "status" of some related content type became something like "approved".
As soon as a business profile no longer has any of such flags set, your business content type can be considered as a "finalized" profile.
Possibly you may want to add the Content Access module to the mix, to implement some additional features that you may want to use.
To implement your "dashboard", you just have to build a few (rather basic) reports using the Views module, with appropriate fields, filters, etc related to the various flags.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module.


Advice on how to fix Workbench Moderation error messages

OK, so I found a workaround, which is good enough for the timebeing... enable Views UI modules - https://drupal.org/comment/6971496#comment-6971496


How to create dynamic multi column forms using native form module?

The way you group form items (as you will need to do to create a single column) is to use the FAPI grouping mechanism, which is described here :

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

then you can use a loop and some vars to name them, for example :

<?php

  // How ever many columns your rest callback wants to make.
  $col_limit = 10;

  for ($x = 0, $x < $col_limit, $x++) {
    $form["group_$x"] = array(
      '#type' => 'fieldset',
      '#title' => t('Your Name'),
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
    );
    $form["group_$x"]["first_name_$x"] = array(
      '#type' => 'textfield',
      '#title' => t('First Name'),
    );
    $form["group_$x"]["last_name_$x"] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
    );
  }

  $form["col_limit"] = array(
    '#type' => 'hidden',
    '#value' => $col_limit,
  );

?>

Will create 10 groups, with form items.
You can then use CSS or jQuery to create columns or tabs or format how ever you wish.

The hidden variable is there to tell you submit handler how many coumns there are and therefore how many times it has to loop looking for

$form_state['values']["last_name_$x"]


Workbench Moderation - intermittent save / autosave without new revision

You can do it by using these modules :

Save Draft

  Save Draft adds a 'Save as Draft' Button to the node_form for content
  types, allowing the user to click the 'Save as Draft' button to save
  the node as a draft.

Draft

  The Draft module provides the ability too create drafts of existing
  nodes as well as new nodes before you have saved them.

  The module utilizes the jquery.fields plugin to serialize all of the
  information and then the information is stored in a database row
  serialized.

  The module provides the ability to autosave the content without
  the user having to hit the Save as Draft button on the form.


How to do translation via csv file imported from PHP my admin

You can trnslate Po files with  POEDitor but if you insist use csv
I suggest you use csv2po , export drupal translate in po file, convert po file to csv translate them in excel (or anywhere you want) then convert back it to po and import it to your site.

some quote from its documentation

  csv2po allows you to create CSV files from PO files. This allows you
  to send translation work to translators who do not or cannot use PO
  Editors but who can use a Spreadsheet.

  po2csv allows you to send CSV files, which can be edited in any
  spreadsheet, to a translator. This document outlines the process to
  follow from the raw po files -> CSV files -> back to PO. We also look
  at a case where you may have submitted a subset of the PO files for
  translation and you need to integrate these.


Can't see error messages when creating Drupal form in a separate file

It is working fine for me, only thing is that I get the error message only when submitting for the second time, that is because you are printing the status message before the drupal_get_form(). So if I print the message after drupal_get_form() then it is working as expected.


Why is #field_parents empty in nested, multi-step form?

I don't know what exactly #field_parents is for, but the information about field grouping is in $form (which, it turns out, is an array, not an object) several times over, in $form['#groups'], $form['#fieldgroups'], and $form['#group-children'].


What is the best way to forward visitors to my homepage to an external site but leave the backlinks accessible?

It sounds like one thing you could do is edit the themes template.php file and do something like:

/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  if (drupal_is_front_page()) {
    $url = 'http://newdomain.com';
    drupal_goto($url, ['external' => TRUE], 301);
    // perhaps alternatively you could use header();
  }
}

Outside of doing this at the web server level, it might be the smallest change to do it.


How do you get dropdown menus with toolbar.module?

Install the admin menu module and activate Administration menu Toolbar style , it's a module in the package of admin menu


I have the answer with suggestion of maintainer module. I can use hook_uc_payment_receipt_insert() to do that.

/**
 * Implements hook_uc_payment_receipt_insert().
 */
function uc_payment_uc_payment_receipt_insert(PaymentReceiptInterface $payment) {
  $order = $payment->getOrder();

  // Log a message against the order.
  $method_name = $payment->getMethod() ? $payment->getMethod()->getPlugin()->cartReviewTitle() : t('Other');
  $log_message = t('@method payment for @amount entered.', array('@method' => $method_name, '@amount' => uc_currency_format($payment->getAmount())));
  $order->logChanges(array($log_message));

  // Automatically mark paid orders as "payment received".
  // @todo Remove when Rules is available.
  if (uc_payment_balance($order) <= 0) {
    $state = $order->getStateId();
    if ($state == 'in_checkout' || $state == 'post_checkout') {
      $order->setStatusId('payment_received')->save();
    }
  }
}

Source


How to use the flag counter in a twig template of a node?

This will return an array of all the flag counts on a node:

\Drupal::service('flag.count')->getEntityFlagCounts($node)

(For all flags set for that node)
Via: https://www.drupal.org/node/2476349

You can use that in a preprocess function to get your flag counts and send it as a new variable to your template file. Like so:

function yourtheme_preprocess_node(&$variables) {

  $flag_counts = \Drupal::service('flag.count')->getEntityFlagCounts($node);
  $variables['like_count'] = $flag_counts['like'];

}

Then in your theme file you can output:

{{ like_count }}

The problem with this is that it doesn't ajax update when someone clicks the flag link. For that to work you have to put the count in the flag template.


How to change #weight of fields added to user register page by form_alter()?

Account as a whole is in a group which contains the name password etc. The one we add might be out side of that. That is why it is not effecting the weight.


how rewrite pagination URL views for SEO?

In Drupal 7 you can use Query Parameters To URL but the D8 port needs more work. Maybe you can help with that in the course of the work for your current project?

It's similar with Clean Pagination that cleans up the pagination specifically, D8 needs more work.

In the meantime maybe you can replace some of the exposed Views filters with contextual ones, they take arguments separated with /.

With a Contextual filter you can display a Summary of taxonomy term names at the top of your views (or any region for that matter) instead of an exposed filter with the term names. That way you would see a list of terms as links at the top of your Views, and the links paths would look like mypath/cat.

Pagination would still add ?page=1 so you'd have mypath/cat?page=1 unless you get the Clean Pagination running.


When using drupal_get_query_parameters(), should I still run values through filter_var() or check_plain()?

drupal_get_query_parameters() doesn't perform any sanitisation of vars at all.

If you need to validate the incoming value, or filter it for XSS before it is outputted, etc., you'll need to do that as normal.


You can do it with a database query

$aliases = db_query('
  SELECT alias
  FROM {url_alias}
  WHERE source = :source
', array(':source' => 'node/' . $nid))->fetchAll();

You may need to modify things a little if you have a multilingual site to take the language column into account.


I've just had a problem that took me forever on a View to do with User Relationships, on question #25294.

The screenshot of the View I was debugging and the information I put in my question should hopefully give you everything you need.

(Bear in mind that my View was getting the people following $currentuser, whereas you want the people $currentuser is following, so you'll want to reverse all the instances of requester and requestee.)

I hope this helps!


Problem when using Feeds to import nodes which have a image field

problem was that I had to use the default folder for the image fied, which is images. I had set photos as the folder for the images.


How can I create a path auto pattern token based on a menu path without placing node in menu?

With the use of the Menu Reference module and hook_pattern_alter, I was able to get this accomplished. The code piece ended up looking like:

function custom_paths_pathauto_pattern_alter(&$pattern, array &$context) {
  if (isset($context['type']) && $context['type'] == 'news_article' && isset($context['data']['node']) && !$context['data']['node']->menu['enabled'] && $context['data']['node']->field_menu_path['und'][0]['mlid']) {
    $menuitem = menu_link_load($context['data']['node']->field_menu_path['und'][0]['mlid']);
    $menupath = drupal_get_path_alias($menuitem['link_path']);
    $pattern = $menupath . '/[node:title]';
  }
}


Allow users to >only< upload images to existing nodes?

Hints for your updated, clarified question (from NOT an expert)

Considering your updated question, there exists a documentation-page on Drupal.org on attaching images to nodes:

Attaching images to other nodes

But, perhaps easier to start off, is to read some answers posted to identical / very similar questions, here on StackExchange:

How to allow users upload images to existing nodes?
Add new images to existing nodes

Having referred to these, I would like to add that I would intuitively enable pictures in comments, and let people post the pictures in to the comments; but I don't know if that's what you're looking for.

If you would choose them to use the comments: after having enabled comments to include pictures, one can disable unneeded fields, similarly to the method described below, via

Structure >> Content Type >> Content type >> Comment fields.
Structure >> Content Type >> Content type >> Comment display.

For further fine-tuning of the display of the comments, the module Views is advised, which will allow you to first select a lay-out in the "Comment display" referred to above, via:

Structure >> Content Type >> Content type >> Comment display >> Layout for comment node content type

& will then allow fine-tuning of the fields in the comments.

The approving of the content by the admin; considering comments; can be tweaked via the row:

People >> Permissions >> Comment >> Skip comment approval

Alternative modules for admin approval of general content can be found in the following StackExchange-post:

Allow users to submit content that is approved before it is published.

Just a final extra remark (more of an alternative easy work-around really): if the text format (cf. Configuration » Content authoring >> Text formats) to be used for your users allows for the HTML -tag, one can of course tell your users how to "post" (but not upload technically) images as a comment, by explaining that they could use <img src="URL">, like you can find explained e.g. @ the W3C-wiki or @ W3-schools.

P.S.: You are a funny guy to re-use Rome.

I will leave my original answer below, which is more applicable to letting people upload pictures as separate nodes; but (as described below) is not a good method for letting people upload multiple pictures to already existing nodes (as you have now updated your question).

Answer to your original question

What you can do is to create a new content type.

To do this, use the administrative overlay & go to:

Structure >> Content Type >> Add content type.

Perhaps you could name the content type "Add a photo", or something.

Then, I would manage & display the fields such that all fields are hidden, except a field for a photo. This can usually be done after creating the content type, by going to:

Structure >> Content Type >> Add a photo >> Manage fields.
Structure >> Content Type >> Add a photo >> Manage display.

Then, I would restrict access to authenticated users (all of them / or some authenticated users; as you'd like) to create &/or edit certain content types only. This can be done (again, using the administrative overlay) by going to:

People >> Permissions >> Add a photo: Create new content
People >> Permissions >> Add a photo: Edit own content

The two boxes of these row can be checked at the column "AUTHENTICATED USER". (That is, if you'd like only authenticated users to be able to post pictures). Then, Creating & Editing of all the other content types should be disabled; if I understand you well. This can be done on the same page, by disabling the checkmarks for "AUTHENTICATED USER"s in e.g. the default content type "Article", via:

People >> Permissions >> Article: Create new content
People >> Permissions >> Article: Edit own content

This is just only what first comes to my mind. You'll see that Drupal is very flexible, and multiple roads lead to Rome.


How can I provide an autocomplete filter for tags in a Search API view?

Add the datasource (entity reference) as a exposed filter.

Check the "allow multiple selections".

Now, the user can add comma seperated tags (with autocompletion):

Used search api 8.x-1.13 on drupal 8.6.16


Have you tried rendering the content instead?

<?php print render($block['content']); ?>

That, combined with the Block Class module should at least allow you to add a class to the wrapper, which is the next best thing to overriding the theming of the actual UL.


Is there a means for telling which module or template files generated a block?

If you haven't greatly overwritten the default block.tpl.php, you can tell by looking at the HTML attributes of the block DIV, which follow this naming convention:

<div id="block-MODULENAME-DELTA" class="block block-MODULENAME">
  ...
</div>


One exposed filter for many views/views blocks

If the two content types are using the same date_field and the blocks are shown on the same url, you can use the exposed filter of one view display to filter both views blocks. You just have to configure the exposed filter on the same field in both views/displays


How to navigate in a view result from node full view

Check out Views Navigation module. This seems to be a good fit for your requirement.

  This module adds next and previous links on content pages when
  accessed from a view. It is intended for dynamic and/or paged view
  results, where the result set changes according to exposed filters,
  current user access rights,...

Also here is the link to the comparison other node based navigation modules.


After upgrading from drush 7 to 8 with multisites, using drush from site directory cannot find drupal 7 (Windows)

It appears that drush 8 does not support drupal projects that were not built with composer. Drush 7 does not have this requirement. I added this composer.json to the drupal 7 root directory:

{
  "require": {
    "drush/drush": "~8.0"
  },
  "extra": {
    "installer-paths": {
       ".": [ "type:drupal-core" ]
    }
  }
}

I found this in an issue for project drupal-finder, which seems to be used by the Drupal 9 Drupal Launcher. I'm guessing that drush 8 has similar code.


Using Drupal 7 hashing method in Drupal 6

Need to use user_check_password() method to compare existing key. Guess I overlooked it earlier.


Single Drupal installation with multiple websites

Yes, if these two sites are really separate and have nothing in common, I would go with a multi-site setup and a single Drupal installation.

This is supported out of the box, see the Multi-site documentation on drupal.org for more information.


Add Fields to Field Group programatically

This is a bit old, but I wanted to do the same thing and couldn't find an answer on the web. I ended up figuring it out by myself.

Let's suppose you created a field group through the CMS interface with the name "group_product_fields". You added some fields to that group.

Now you have a new field being included in the form programatically via hook_form_alter. You want to add that field to "group_product_fields". Here is an example of what the field could be:

$form['new_product_field'] = array(
  '#type' => 'textfield',
  '#title' => t('New product field'),
  '#description' => t('Description for this new product field'),
);

All you need to do now is to add that new field to the field group. To do that add the line below to the hook_form_alter. It can be placed anywhere inside it.

$form['#group_children']['new_product_field'] = 'group_product_fields';

That's all. You may wish to adjust the field weight for it to be positioned as you want. But in the end this is really simple. :)


Problem with drush and site alias (Drupal 8.8.6 / Drush 10.3.1)

There is no need for the leading @name and try adding the full path to drush for all remote environments:
dev:
  ...
  paths:
    drush-script: /example/path/www/vendor/drush/drush/drush
prod:
  ...
  paths:
    drush-script: /foo/bar/www/vendor/drush/drush/drush


You can use Taxonomy access module to access control for user role.

  Automatically controls access to nodes (based on their taxonomy    terms).
  Configuration page for each user role.
  Three node access permission types: View, Update, Delete.
  Two term access types: View tag, Add tag.


Create picture module responsive styles programmatically

First step is to create the image styles:

// 1. Create image styles
$multipliers = array(
  '1x' => 1,
  '1_5x' => 1.5,
  '2x' => 2,
);
foreach($multipliers as $label => $multiplier) {
  $style = image_style_save(array('name' => 'tile_image_' . $label));
  $effect = array(
    'name' => 'image_scale_and_crop',
    'data' => array(
      'width' => 390 * $multiplier,
      'height' => 194 * $multiplier,
      'upscale' => TRUE,
    ),
    'isid' => $style['isid'],
  );
  image_effect_save($effect);
}

Then create a group for the image styles:

// 2. Create image group
$new_group = breakpoints_breakpoint_group_empty_object();
$new_group->machine_name = 'tile_image';
$new_group->name = 'Tile image group';
$new_group->type = BREAKPOINTS_SOURCE_TYPE_CUSTOM;
$new_group->breakpoints = array('breakpoints.theme.armi_embl_theme.desktop', 'breakpoints.theme.armi_embl_theme.mobile');
breakpoints_breakpoint_group_save($new_group);
menu_rebuild();

And then finally define the mapping between the image styles and your set of breakpoints:

// 3. Add picture mapping
$mapping = picture_mapping_create(TRUE);
$mapping->table = 'picture_mapping';
$mapping->type = 'Normal';
$mapping->export_type = 1;

$mapping->label = 'Tile image mapping';
$mapping->machine_name = 'tile_image_mapping';
$mapping->breakpoint_group = 'tile_image';
$mapping->mapping = array(
  'breakpoints.theme.armi_embl_theme.desktop' => array(
    '1x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1x',
    ),
  ),
  'breakpoints.theme.armi_embl_theme.mobile' => array(
    '1x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1x',
    ),
    '1.5x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_1_5x',
    ),
    '2x' => array(
      'mapping_type' => 'image_style',
      'image_style' => 'tile_image_2x',
    ),
  ),
);

picture_mapping_save($mapping);


How to specify entity reference fields when programmatically submitting to user_register_form

I think form might be expecting in proper format that is "[entity-title] [entity_id]", so field array should look like.

'field_foo' = {
    'und' = [
        0 = {
            'target_id' = 'Title of entity ($tid)'
        }
    ]
}

Just to make sure you can form alter user form, add a custom validate and do a dsm($form_state);


Advanced search in Multidomain - Multilanguage catalog webpage Drupal 7

There are at least two options. You can use the Views module to expose search filters on the products.

If you have access to an Apache Solr search server you can use some of the modules that integrate with Solr for advanced searching.


How do I collect an end date when creating a Date field in code?

You just need to set the todate under the settings array, I believe the 2 options available are

'todate' => 'optional',

and

'todate' => 'required',


What is the correct way to attach an arbitrary field from a different content type to an existing form?

I considered using field_attach_form(), but I can't wrap my head around what the $entity argument should contain.

It's the entity for which you want to show the form elements to edit its fields. For example, if you want have a reference to a node in $node, and you want to add the form elements to edit its fields, you add the following line to the code.

field_attach_form('node', $node, $form, $form_state, entity_language('node', $node));

The validation handler for the form should then call either one of these functions.

entity_form_field_validate()
field_attach_form_validate()

The first function builds the entity object from its $form_state parameter; the second function requires the entity object as second parameter.

Keep in mind that, despite the fact the UI allows you to add fields to a content type (e.g. add a Portrait image field to a Biography content type, but not to a Blog content type), for Drupal the entity to which the fields are attached is a node, which means you need a node object. passing as entity a string containing the machine name of the content type doesn't produce the expected result.


Error when uploading file through Drush on S3 volume

It's all there really, it's a security warning and you can fix it by creating a .htaccess file at the root of sites/default/files. The actual content should be:

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

Additionally, the .htaccess of the temporary files directory and private files directory (if used) should include this command:

Deny from all

Read more in this security advisory.


By Default you can consider all hooks can be extendible using custom modules...

Hook Documentation says

  Hooks are how modules can interact with the core code of Drupal. They
  make it possible for a module to define new urls and pages within the
  site (hook_menu), to add content to pages (hook_block, hook_footer,
  etc.), to set up custom database tables (hook_schema), and more.

In template.php you can override functions which are exposed by hook_theme or functions like theme_*

There exists a good documentation that explains which functions you can override using template.php..


Memcache not being cleared on cache flush

Turns out it wasn't a memcache problem but a LESS preprocessor issue.


What is the purpose of the config/install directory?

The config/install directory contains the default configuration of a theme/module. Its purpose is explained in Include default configuration in your Drupal 8 module, which says:

  In Drupal 7 default configuration for modules such as content types, field configuration, views, etc. required custom PHP code to install and keep updated. In Drupal 8, these are stored with the configuration system in plain text YAML files.

  For example the configuration management system takes care of creating and managing content types. You can ship a content type with your module by creating a properly named and structured configuration file.

Then, it adds:

  You can include default configuration for other things like block placement, views, text formats, editor configuration, user roles, etc. with your module the same way.

Drupal core itself uses files like block.block.bartik_powered.yml, or block.block.seven_messages.yml.

I didn't find a description of the content, but if you look at the content of those files, you can understand what you need to put.

langcode: en
status: true
dependencies:
  module:
    - system
  theme:
    - seven
id: seven_messages
theme: seven
region: highlighted
weight: 0
provider: null
plugin: system_messages_block
settings:
  id: system_messages_block
  label: 'Status messages'
  provider: system
  label_display: '0'
visibility: {  }

Note that the file declares its dependency from the System module because that is the module implementing the block plugin (plugin: system_messages_block).


Show "Log in" link all the time (even for logged in users)

If you're trying to show a link called "My Shop" which takes anonymous users to the log in page and logged-in users somewhere else, you can just create a second menu item also called "My Shop" and set it to display only for users that have the authenticated user role.  Then set the destination to whatever you want; that way both logged in users and anonymous users will have "My Shop" links pointing different places.

You can have multiple menu items on the same menu with the same name (Drupal doesn't check for uniqueness in order to allow for situations like this).

As long as you give the two "My Shop" menu items the same weight (or drag them so that they are next to each other), they will appear to be the same menu item.


You have to use hook_views_pre_execute and with Devel installed use dpq to view the SQL String:

function hook_views_pre_execute(&$view) {
  dpq($view->build_info['query']);
}


You probably wouldn't use .htaccess for this.  If your webserver is Apache, your apache virtual host configuration is what points your domain to a directory on the server.  On an ubuntu linux server your virtual host file would normally be in /etc/apache2/sites-enabled/mysite.com

If you are using a shared webhosting service (like Dreamhost) that uses an account configuration tool like Cpanel you can usually change your web directory using that tool.  Look under options for "Domain Names" or DNS.

Don't mess with .htaccess unless you really need to--you can mess up your site or render it insecure.  If you do edit .htaccess, make a backup of the original file.


Preventing users from registering with xxx@yyy format email address

There is a core function named: function valid_email_address that will check that the syntax is valid.

Example of use:

$mail = $form_state['values']['submitted_tree']['email_address'];
if (!valid_email_address($mail)) {
  form_set_error('[submitted][email_address]', t('The email address appears to be invalid.'));
}


Git cloning a project asks for git@git.drupal.org password

I was finally able to solve the issue by removing all git programs from my computer and then reinstalling only Git (bash). I think Tortoise Git was interfering somehow and causing the issue.

After removals and clean install, my clone worked right away. Simple.


Using S3BrowserUpload to Add Form to a Content Type

Recently I worked on a project to integrate JW Player into a Drupal 7 site where the videos stream from an S3 bucket. There was also some Zencoder stuff going on but that is not really relevant here I don't think.

Currently we don't upload directly to S3 though, the project ran out of time before we could implement that. What the client does is upload the files directly to S3 and then reference the file in the content type using the Remote File Source module. That is not quite what you are trying to do though.

I have had a look around and see there is an Amazon S3 CORS Upload module which looks promising and might be able to help you. It creates a new form field #type which you can use in your module.

If none of that appeals to/works for you :) then you can use hook_form_alter to add a new custom upload field to the content type form, it is kind of messy but it will work. Then you add an extra submit handler to the form to catch your file. You can then use the code from this example to submit your file to S3.

The nicer way would be to create a new Field using the Drupal 7 Field API.


More Stories appears when a user scrolls on a half page

You can give the drupal infinite scroll module with views a try . Then tweak a bit to suit ur needs for scrolling


What is the command that replaces 'drush variable-set'?

Following some more research it seems the new command is:

drush config-set <config-name> <key> (where the old format was drush variable-set <name> <value>). Alias: cset.

So I'm not totally sure that I have this right (so comment and/or another answer from someone who does would be great...), but it seems that the config that includes emails are: contact.form.feedback recipients, update.settings notification.emails and system.site mail.

This update is the result for some good discussion (below).
Note that some settings are arrays (rather than strings):

www/drupal8# drush config-get update.settings notification
'update.settings:notification':
  emails:
    - admin@example.com
  threshold: all

to update this you need to run:

drush -y config-set update.settings notification.emails.0 admin2@example.com

Source: Leverage Drush 7 for Drupal 8.

Note: Drush 7 no longer supports Drupal 8, but this still applies.


Validation message on Login form not shown

Look at the form id for login form. and then try hook_form_alter() in any custom module.

Add a submit callback or validation callback in which you can check for the empty fields yourself. According use drupal_set_message() to display the error message.


How do I add the tertiary level from the main menu to my skin?

I figured it out.  In template.php, I added the following function:

function MYTHEME_preprocess_page(&$variables) {
    $active_tree = menu_get_active_trail();
    $parent = array_pop($active_tree);
    if($parent['depth'] == 3) {
        $parent = array_pop($active_tree);
    }

    $parameters = array(
        'active_trail' => array($parent['plid']),
        'only_active_trail' => FALSE,
        'min_depth' => 3,
        'max_depth' => 3,
        'conditions' => array('plid' => $parent['mlid']),
      );

    $tertiary_menu = menu_build_tree($parent['menu_name'], $parameters);

    $links = array();
    foreach($tertiary_menu as $branch=>$link) {
        array_push($links, $link['link']);
    }

    $tertiary_links_vars = array(
        'links' => $links,
        'attributes' => array('class' => array('sub-nav')),
        'heading' => array(
            'text' => t('Tertiary menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
        ),
    );

    $variables['tertiary_menu'] = theme_links($tertiary_links_vars);
}

In my page.tpl.php file, I added the following:

<?php print $tertiary_menu; ?>


How to create a product class programmatically in D7 / Ubercart 3

Thanks to Clive for pointing me in the right direction. As requested here is a code snippet I used in my module. I was able to take the code found in uc_product_class_form_submit() and make minor changes to make it work for my situation.

Essentially, in my module, I'm using hook_enable to call a helper function which checks for an existing product class. If it doesn't exist, then it creates it (as well as the node type). My module will go on to do more, but this is the relevant piece. (more specifically the function uc_suggested_donation_levels_add_product_class).

<?php

/**
 * @file uc_suggested_donation_levels.module
 * Adds up to 4 donation levels including a "you choose" amount.
 */
// Constants
define('DONATION_PRODUCT_TYPE_MACHINE_NAME', 'giving_project');
define('DONATION_PRODUCT_TYPE_READABLE_NAME', 'Giving Project');
define('DONATION_PRODUCT_TYPE_DESCRIPTION', 'Adds up to 4 donation levels including a [you choose] amount.');
define('DONATION_PRODUCT_TYPE_ERROR', 'Content type already exists in database. No need to re-create.');

/**
 * Implements hook_enable.
 * When this module is enabled it will check if the product type exists,
 * if not, then it will create it and productize it.
 */
function uc_suggested_donation_levels_enable() {
  uc_suggested_donation_levels_add_product_class();
}

function uc_suggested_donation_levels_add_product_class() {
  // first check to see if this product already exists.
  if (in_array(DONATION_PRODUCT_TYPE_MACHINE_NAME, uc_product_types())) {
    // The product type already exists, abort.
    watchdog('uc_suggested_donation_levels', DONATION_PRODUCT_TYPE_ERROR, array(), WATCHDOG_INFO);
    drupal_set_message(DONATION_PRODUCT_TYPE_ERROR, 'status');
    return;
  }

  $pcid = DONATION_PRODUCT_TYPE_MACHINE_NAME;

  $result = db_merge('uc_product_classes')
    ->key(array('pcid' => $pcid))
    ->fields(array(
      'name' => DONATION_PRODUCT_TYPE_READABLE_NAME,
      'description' => DONATION_PRODUCT_TYPE_DESCRIPTION,
    ))
    ->execute();

  db_update('node_type')
    ->fields(array(
      'name' => DONATION_PRODUCT_TYPE_READABLE_NAME,
      'description' => DONATION_PRODUCT_TYPE_DESCRIPTION,
    ))
    ->condition('type', $pcid)
    ->execute();

  uc_product_node_info(TRUE);

  if ($result == MergeQuery::STATUS_INSERT) {
    variable_set('node_options_' . $pcid, variable_get('node_options_product', array('status', 'promote')));

    if (module_exists('comment')) {
      variable_set('comment_' . $pcid, variable_get('comment_product', COMMENT_NODE_OPEN));
    }

    module_invoke_all('uc_product_class', $pcid, 'insert');
  }
  else {
    module_invoke_all('uc_product_class', $pcid, 'update');
  }

  node_types_rebuild();

  $type = node_type_get_type($pcid);
  node_add_body_field($type, t('Description'));
  uc_product_add_default_image_field($pcid);

  menu_rebuild();

  drupal_set_message(t('New donation content type and product class has been created.'));
}


Then Drupal Rooms is the only option for you and it match your requirement for room calculation, it will update the pricing  depend upon the rooms selected . Rooms is a booking and room management solution for hotels, vacation rentals and B&Bs.

  It allows an accommodation owner to:

  Create rooms and assign availability (or on hold states) via a calendar.
  Manage pricing for rooms using calendars that allow to set pricing for entire seasons or just change it for specific dates.
  Define optional add-ons for rooms.
  Charge either per-night or per-person.
  Handle children discounts.
  Create bookings and keep customer records.
  Make rooms available for booking with a availability search functionality and/or calendar - handling both immediate bookings and bookings following owner confirmation.
  Search by Room Type.
  Full integration with Commerce to manage payments, a range of different payment gateways, and a host of other e-commerce features.
  Accept full or partial payments (deposits) using Commerce features.


How to add a description to the Goals used by the Goals module?

Goals used by the Goals module are implemented using fieldable entities. So you can customize goals by adding your own fields, such as:

descriptions.
images.
links to external resources.
etc.

Head over to its video tutorial, and have a look at what is shown starting from around 4:00 where you can see the typical tabs for Goals, such as:

Manage Fields.
Manage display.

For more details, refer to its Community Documentation also.

Disclosure: I'm the maintainer of this module.


How to integrate a private Google Calendar?

Check Google Calendar API (GCal)

This module uses google api php client refer
http://code.google.com/p/google-api-php-client/ to interact with
google and manage calendars
Requirements
GAuth - Required for authenticating with google.


Using Entity Reference to show a view within a node

Assuming there is an entity reference field in articles that points to the content type "authors", and the view will be show on the article content type..

In your view, you should be able to add the relationship "Entity Reference: ReferencED entity" for that field name.

Then you can add your fields from the authors content type and make sure you point to the referenced entity in the field's settings.

You'll also need a contextual filter for NID "Provide default: Current Node".


How can I dynamically remove an entity constraint?

Validation constraints are plugins with an alter hook: hook_validation_constraint_alter() (the hook name can be seen in \Drupal\Core\Validation\ConstraintManager::__construct()).

That means you can alter that plugin and replace it with your own class that doesn't do anything, or only under some conditions.

Note that constraint plugins are special, unlike everything else, they consist of two classes, the plugin class is just the definition and strings, and then here is a $classname . 'Validator' class that contains the actual logic. So you need two classes, first the constraint class, Drupal\yourmodule\Something and then an overriden version of the Validator as Drupal\yourmodule\SomethingValidator.


How can I create a Views RSS of members only content?

Yes. The forum/%forum_forum route created by the Forum module does a user_access() check for the access content permission; any subpath of this route (e.g. your RSS view, forum/%forum_forum/rss.xml) will be checked as well.

You can override this via a hook_menu_alter() implementation:

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['forum/%forum_forum']['access callback'] = 'MYMODULE_forum_override';
}

function MYMODULE_forum_override() {
  return preg_match('/^forum\/(\d+)\/rss.xml$/', request_path());
}


Can I force cron to process all of my queued tasks?

Basically PHP has memory and execution time limitations, so if you try to do a huge import of an external database you'll run out of runtime if not memory.

So the solution is to spread it out over many http requests, each doing a smaller chunk of the job.

For this, Drupal has the Batch API, which you can call from cron as needed.

Here's the Examples project's Batch example (with tests!) to guide the way. And a decent explanation with some code samples.