1. Using metatag module

If you want to do it without custom coding you can try metatag module

enable MOBILE & UI ADJUSTMENTS submodule
go to metatag settings admin/config/search/metatag
edit the GLOBAL settings
under MOBILE & UI ADJUSTMENTS fill in viewport input box

2. Using viewport module

There is also a dedicated module called viewport which will allow you to do just that.

3. In your custom theme

But can be easily done in your custom theme. Put the following code inside the THEMENAME_preprocess_html function in your THEMENAME.theme

function THEMENAME_preprocess_html(&$variables) {
  $viewport = [
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => [
      'name' => 'viewport',
      'content' => 'width=device-width, user-scalable=no',
    ],
  ];
  $variables['page']['#attached']['html_head'][] = [$viewport, 'viewport'];
}

NOTE: if THEMENAME_preprocess_html function does not exist you can create it and put the code inside.  You can't redeclare it otherwise you will end up with WSOD.

function THEMENAME_preprocess_html(&$variables) {
  //...
}


Drupal Commerce custom pane as payment and shipping address

This feature does not exist in core yet but it is in progress right now. Look for it in Commerce 2.13.


An exposed filter works only with certain taxonomy terms (weird to me)

Found my mistake. I rechecked every value on the View filters, and the city filter had a value on it, so I left empty the city and now the property is showing ok, because that property is not on the city that was the default.


Manage displays of Product:image field directly in Product Display?

Go to the Manage Display tab of your product entity and enable the same "View Mode" you use at "Product Display". Do it in the "Custom display settings" fieldset.

Then set up image style for the Image field. And see changes at the "Product display" page


Will importing a View that already exists merge with what isn't there in Drupal 7?

WHOA STOP. haha

Install the Features module and create a feature with this View in it and deploy (git/sftp) the Feature up to production. then revert feature and boom. latest view is there.

Download, enable Features on Dev
Create a new Feature
Add your View to this Feature
Save the exported feature into your file system for Drupal
Enable on Dev and verify that it is in the default state (it should be)
Download, enable Features on Prod (or use git to merge you dev branch into prod)
Place this new Feature onto prod (either using git or SFTP)
Enable this feature on prod. Since you have the View already, it will probably be Overridden. You can simply view differences (using Diff module) or revert it.

Note: I highly recommend a staging environment between development and production so you can test these types of reverts and adjustments prior to making changes on a production site.


pattern name for override view templates

Just use  views-view-unformatted--(your view block name).html.twig.
Eg. If your view name is Slideshow, use views-view-unformatted--slideshow.html.twig

This is a good reference point - http://redcrackle.com/blog/drupal-8/theme-views-templates


Splitting Drupal commerce order for easier shipping

I'm not sure you need to consider this as order splitting. I'm working on a project currently that will make use of the Commerce Shipment module to handle splitting an order into shipments for fulfillment. It can accommodate either a single shipment per order or multiple if necessary.


Feed Import is successful and shows number of nodes imported but nodes not listed under content

I found the solution. This is what I did for the nodes to be picked and listed under content:
For the importer, Mapping for Node Processor, added a source xpathparser mapped to target GUID and checked Unique target.

Then for XPath XML parser mapped the GUID field to the Node id field in my xml file (for my case the label was Nid)


Some of my pictures and fonts are not loading after uploading to host

Seems like ini_set is disabled by your hosting provider.  There is a thread on drupal.org that may help.

Seems like your best option is to contact your hosting provider directly and see if there's anything they can do for you.

This might help as well.

  I had the exact same problem, and by reading the posts here and
  Googling around I found out that this error is caused by ini_set being
  disabled by the hosting provider.

  Unless you have root access, you cannot edit the php.ini file
  directly, but at least on my hosting the support gave me these
  instructions to circumvent the problem:

  Create a "php.ini" file in your public_html directory and put one line
  of code exactly:

  disabled_functions =


How do I integrate a nodes edit form on a page?

Use drupal_get_form(NODETYPE . '_node_form', NODEOBJECT); as callback in your custom menu item.
The original node module callback for menu item 'node/%node/edit' is located in the node.pages.inc file:

/**
 * Menu callback; presents the node editing form.
 */
function node_page_edit($node) {
  $type_name = node_type_get_name($node);
  drupal_set_title(t('Edit @type @title', array('@type' => $type_name, '@title' => $node->title)), PASS_THROUGH);
  return drupal_get_form($node->type . '_node_form', $node);
}


How can I omit downloading default themes in drupal core in make file

No, I do not believe a makefile (assuming you mean Drush Make) can do this.  Deleting the actual theme files is not the best approach, since each time core is updated they will be re-downloaded.

If you want to remove core themes from the Appearance admin section, you can hide them with hook_system_info_alter().

function example_system_info_alter(&$info, $file, $type) {
  if ($type == 'theme' && $info['name'] == 'Bartik') {
    $info['hidden'] = TRUE;
  }
}


You can add variables in hook_node_preprocess in the template.php file in your theme.  Something like:

function MY_THEME_node_preprocess(&$vars) {
  // EXAMPLE: add variable according to view mode.
  switch ($vars['elements']['#view_mode']) {

    case 'teaser':
    $link_text = t('Add new comment...');
    // Build render array for link.
    $link = array(
      '#theme' => 'link',
      '#text' => $link_text,
      '#path' => "comment/reply/" . $vars['nid'],
      '#options' => array(
        'html' => FALSE,
        // Make sure it jumps to the right anchor point
        'fragment' => 'comment-form',
        'attributes' => array(
          'class' => array('add-comment'),
        ),
      ),
    );
    $vars['add_comment'] = $link;
    break;
  }
}

And then in your node.tpl.php you can check for $add_comment and print it out using render():

    <?php if (!empty($add_comment)): ?>
        <?php print render($add_comment); ?>
    <?php endif ?>

You can probably split out the comment link from $vars if that is neater.


How can I display a view's count in a navigation item?

I know only how to get it with codding.
You can define in your module function, which gets total rows count from your view. And you can use drupal cache system for result, but actually you can use Views cache for it.
Something like that:

/**
 * Executes View to know rows count
 */
function testm_get_view_items_count($view_name, $display_id, $args) {
    $count = &drupal_static(__FUNCTION__);
    if(!isset($count)) {
        if($view = views_get_view($view_name)) {
            $view->set_arguments($args);
            $view->get_total_rows = true;
            $view->execute($display_id);
            if(isset($view->total_rows)) {
                $count = $view->total_rows;
            }
        }
    }
    return $count;
}

You can add cache_set/cache_get as Lulabots showed, but then you need to think about when to do flushing you cache.
You can use this function in THEMEORMODULE_preprocess_menu_link() function in Drupal 7. Here I showed example.
This code works on D7.


Why doesn't my custom entity work in an entity reference field?

You have no label key, so autocomplete doesn't know what to search for.


How to restrict access to blocks depending on the roles?

This patch could help you in controlling access to blocks.

Patch is here https://drupal.org/node/1916028#comment-7302100.

Need to apply this patch on dev version of this module 7.x-1.x-dev of Block Access


You first need to add one more field in your view i.e Global Custom Text.

After that you need to merge your two fields result in this field output using Replacement patterns

As in attached screenshot, I am merging nid and first name field in global custom text field output.

You also need to exclude "Uploaded covering letter" and "Uploaded e-book" field from output using Exclude from display attribute. You need to checked this check box for both the fields.


How can I save and exit from the middle of editing an already completed multipage webform submission?

I was able to get this to work like so:
In a form alter, make the Submit button visible, and change the name.
   if (stristr($form_id, 'edit_form') !== FALSE) {
    $form["actions"]["submit"]['#value'] = t('Save & Exit');
    $form["actions"]["submit"]["#access"] = TRUE;
    $form["actions"]["submit"]["#_webform_access"] = TRUE;
    // Add a custom submit function so we can redirect the edit form.
    $form['actions']['submit']['#submit'][] = 'mymodule_webform_submission_form_submit';
    $form['actions']['submit']['#validate'][] = 'mymodule_webform_submission_form_validate';

  }

Next, in the custom validation function:
  // If this is the edit form, and the submit button is the trigger, always
  // do the final submit by setting the current wizard page to the confirmation
  // page.
  $trigger = $form_state->getTriggeringElement();
  if ($trigger["#id"] == 'edit-actions-submit' &&
    stristr($form['form_id']['#value'], 'edit_form') !== FALSE) {
    $form_state->set('current_page', 'webform_confirmation');
  };

Finally, in the custom submit function:
$build = $form_state->getBuildInfo();
$callback_object = $build['callback_object'];
$entity = $callback_object->getEntity();
$source = $entity->getSourceEntity();
if (!is_null($source)) {
  $nid = $entity->getSourceEntity()->id();
  $form_state->setRedirect('entity.node.canonical', ['node' => $nid]);
  $form_state->setRebuild(FALSE);
  \Drupal::messenger()->addStatus("Your work has been saved.");
}

While this answers my question, it leaves me having to deal with potential errors from conditionally required fields affected by whatever changes the user is trying to save.


You can use the post_execute() method on your handler to remove entries from the list of all results. This is certainly a bit tricky but it works.


Look in your Drupal admin area at /admin/config/media/file-system

This will tell you where Drupal thinks it's tmp folder is currently set to.

Depending on your host provider you may or may not be able to write to that location.

The php-info report found on your Status Report page admin/reports/status can tell you where PHP's temp directory is defined to be on your system:

upload_tmp_dir     no value

Using htaccess, or ini_set in settings.php you can tweak where the upload temp directory is for your Drupal installation if need be.


How to create a URL to an unmanaged public file in Drupal 8

You need to run the file path through file_create_url() and then use it together with base:

Url::fromUri(file_create_url($dest));

(file_create_url() should return absolute URL's, so you don't need base)

There's an issue to simplify that: https://www.drupal.org/node/2539622


You may want to look at this https://drupal.org/project/views_quicksand

It integrates this plugin http://razorjack.net/quicksand/ with views.

Hope it helps.


How to join values of multiple geofields in a view?

Have you tried conditional views?
You could have 2 fields, using the first by default, and the second instead if the value of the first is empty.
This module has helped me a few times. Just add the module, in your view add a field type "Views conditional", exclude from display your fields and use replacement patterns in your conditional field in one case or the other, depending on the condition (let's say address field is empty, then use latitude/longitude).

EDIT:
What about 3 fields in your content type:

Address field [field_address]
Lat/long [field_lat_long]
Composed field (type text) with token value [field_address][field_lat_long] using field token value or field tokens
In this way the composed field will always have a value from one or another field, and then you can use this field as data source.
Then you may need to manage field dependencies to avoid that both fields are used.


What hook is triggered when adding / updating and deleting taxonomy?

Take a look at the taxonomy.api.

Looks like you're gonna want to take a special look at hook_taxonomy_term_insert, hook_taxonomy_term_update, and hook_taxonomy_term_delete.


Admin menu bar covers part of the screen while working in mobile mode

There is no configuration settings at admin/config/administration/admin_menu for hiding the admin_menu at the mobile screen, hence you can do 2 things:

Either inspect you site in incognito mode of Chrome or private browsing in Firefox
Permanent solution would be applying CSS for this

@media screen and (max-width: 640px) {
  #admin-menu {
    display: none;
  }
}


How to create a lightweight domain access alternative in Drupal 7

Out of the box drupal 7 installs are domain agnostic (don't save absolute urls in content or as paths). Assuming you haven't got any custom server directives or alternate domain with a need for a different relative url, you could try either:

A) Create a separate content type, if content managers know up front what content will need to be visible.

B) But if they don't know up front (and since you can't easily convert a node from one type to another), you could try using a taxonomy field to tag content for visibility. Then use taxonomy access lite module (https://www.drupal.org/project/tac_lite) to grant access to nodes tagged with a specific term to anonymous users.


You seem to have CSS that removes the top margin from the first block:

.block:first-child h2.block-title, .page-header {
   margin-top: 0;
}

You can override this by simply adding this piece of CSS in your CSS file:

.region-content-bottom .block h2.block-title {
  margin-top: 21px;
}


Using print render($content['taxonomy']); in node.tpl.php

I think the proper way to do this would be to implement THEME_preprocess_HOOK() in your theme's template.php.

In that function, just add each taxonomy term name into the classes array.  You'll probably also want to cleanse the term names as you put them into the classes array, dig around Pathauto or Transliteration modules to find a function to do the dirty work.

function mytheme_preprocess_node(&$vars) {
    foreach ($vars['node']->field_my_taxonomy_field[LANGUAGE_NONE] as $term) {
        $vars['classes_array'][] = pathauto_cleanstring($term->name);
    }
}


Please tell me what drupal table the block php visibilities settings is stored at

The php code should be stored in the pages field of the block table, and it should not be serialized.

The visibility field can have one of three values:

BLOCK_VISIBILITY_NOTLISTED (0),
BLOCK_VISIBILITY_LISTED (1), or
BLOCK_VISIBILITY_PHP (2).

In the case of the first two, the pages field will contain a text list of the notlisted or listed pages for the block. in the case of the third, the field will contain the php code.


how to add wrapper div for a image via image formatter in drupal 7?

You need to add one more hook to default add  to field wrapper.

 function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings']; // Key needs to be defined in info array (who knew?)
  $element = array();
  if ($display['type'] == 'default_formatter') {
    foreach ($items as $delta => $item) {
      $element = array(
        '#prefix' => '
',
        '#suffix' => '
',
      );
    }
  }
  return $element;
}


Is there a way to insert "0000-00-00 00:00:00" in a datetime database field?

In Drupal 7 DB API, support for the datetime type was removed. This means that you must use use mysql_type or pgsql_type if you want this functionality.  Below is an example of of to declare this schema provided your database is MySQL.  By setting not null to FALSE, you can store an empty value (''), which is equivelent to '0000-00-00 00:00:00':

'mydate_date' => array(
  'description' => t('My date field.'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

Note that to make the schema portable, you should provide a fallback type (varchar) for the case that the database is not mySQL.


How to disable/hide /unset a block programatically?

You could try hook_block_list_alter to hide a specific block.

Act on blocks prior to rendering.
This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.


How to create groups and assign users to them using Organic Groups?

Have you read the readme file in og module folder, it shows basic instruction to create a group, assign content to the group.

Basically, after enabling OG module, you need to create a content type, if you want it to be a 'group', select the "Group Type" option, then each instance of this content type will represents a group.

Below are some links will help you start:

Basic OG Documentation: http://drupal.org/node/483234

Amitai's presentation of OG7: http://www.archive.org/details/GrouptheNewOrganicGroups-BuildingSocialNetworksInDrupal7    (I recommend you watch this video, very informative. I am sure you will sort it out)


Can I use Simpletest to test site upgrades?

It depends of your Simpletest tests. Upgrade your site in a test environment (stagging ideally) and then run your Simpletest tests. If tests are ok you can be sure that everything covered by your tests is ok.

If your question is if Simpletest can create nodes, yes, it can. What Simpletest can't do is test Javascript. If you need to test Javascript you should use another tool like Behat. Behat is a BDD tool, so it allows you to describe the behavior of your app and test it. Behat has several drivers, one of them is the Selenium driver, that includes full JS tests (because the tests are performed by a real browser). There are otheres drivers and many posibliites.

In general Behat is better than Simpletest for integration tests, while Simpletest is better for functional testing.

If you are going to use Behat use the Behat Extension approach. Check the Drupal Behat Group too.


form textfield name -value changed and does not validate any more

It all happens in drupal_validate_form().

  Validates user-submitted form data in the $form_state array.

If I could offer some advice - have a re-think. Changing the name attribute of form elements, especially on those that are part of field widget forms, is a good way to get unexpected results. The name on an input is completely irrelevant to the page, so changing it doesn't actually get you anything. If you're trying to change it so you can target the elements using JS, for example, I'd advise changing your JS code rather than the form markup. Trust me when I say it will be easier.

The only valid situation I know of to override the name of an element is when you need to provide multiple submit buttons on a single form that carry out the same action, but in a different context.


Will there be any unexpected side effects when I upgrade the Zen theme?

Themes don't create their own database tables.

The changes about the theme status (enabled, default, theme settings) are stored in the system and variable tables, along with many other system settings, it's nothing you should be worried about.

Some themes are accompanied by a special module built especially for them, but Zen isn't one of those.

Yes, you can disable and delete old Zen and its subthemes without consequences. Set Bartik as default theme before removing old Zen out of your system.

It's good practice to backup files before deleting, it's up to you, at least check if there are any files you might want to keep, maybe logo images.

Then download and enable the latest Zen. Create the latest Zen subtheme using the latest Zen procedure.

The latest Zen theme structure and procedures are significantly different from the older versions. You'll have to install some bundles and other dependencies and learn how to build Sass through Gulp (if you want Sass)...

You might experience problems if you want to keep the old subthemes and make them work with new the Zen, but if you want to start fresh there aren't bad consequences if you remove old Zen and its subthemes and then install new Zen.

It's good to remember to clear (theme) cache when changing things like these, even though theme registry is rebuilt on visiting the Appearance page.


Slideshow of images which are not a field of node

I have solved the problem by using Lightbox2 module, which allows to render a Slideshow with no need of a View or configuring the images as fields of nodes.

You can see the solution with some code, in this other question and answer of mine. So this is a solution for someone looking for:

A gallery of many many images.
Slideshow with thumbnail.
Thumbnail + Medium image (detail of product, for example), with the Slideshow launched from the Medium image, no the thumbnails.

How to configure a Slideshow with thumbnails in modal window


How can I create a variable with different values for each domain using Domain Access?

You must enable "domain configuration" submodule (domain_conf)
This will provide you the save per domain option:

function your_module_form($form, &$form_state) {

  $form['variable'] = array(
    '#type' => 'value',
    '#value' => time(),
  );

  return system_settings_form($form);

}

getting the variable manually:

function domain_conf_variable_get($domain_id, $variable = '', $all = FALSE, $reset = FALSE)

seeting the variable manually:

function domain_conf_variable_set($domain_id, $variable, $value = NULL)

There is a module which aims to be a replacement variable handling module for Domain Access,If you need setting different variable values for each domain and for each language at the same time you need domain variable module https://drupal.org/project/domain_variable


How do I filter down on multiple taxonomies?

For this case, exposed filters are the wrong approach.

You can do this by making a contextual filter that operates on your region vocabulary.

Assuming your view is set to display taxonomy terms, I would do the basic configuration like this:

Add a contextual filter of type Taxonomy term: Term ID.
Set When the filter value is not available to Display a summary.

When you do this, you should get a page that list the regions if you have not selected one yet but lists data if you have selected a region.


Drush remote sql-dump starts with "stdin: is not a tty"

I'm reading from here: https://stackoverflow.com/questions/7062521/rsync-exits-with-the-message-stdin-is-not-a-tty

You need to add:
[ -z "$PS1" ] && return
to the beginig of .bashrc that is located in your home dir. That command checks to see if the shell is running interactively. If so, it exits immediately. This makes sense since stuff in the bash configuration file isn't needed for non interactive processes, like rsync

"in your home dir" meaning the user used to login on your @SITEALIAS.live server. So you need to SSH into your server as that user, and add the above line to the beginning of your ~/.bashrc on that server.
An explanation from another answer:

The error message "stdin: is not a tty" is due to something in the startup script on your server attempting to process an action that should only happen for interactive logins (when you connect with ssh direct to the server, etc).


Users can have the same password, but they cannot have the same username by default. Theoretically, users could have the same username with some customization, but they would need to log in with something else that makes them unique such as an e-mail address.


Mixing attributes and line item fields in Drupal Commerce Add To Cart form

You may find it easier to organize the form elements in a form template.

e.g

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state{
  $form['#theme'] = array('commerce_add_to_cart_form');
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path){
  return array(
    'commerce_add_to_cart_form' => array(
      'render element' => 'form',
      'template' => 'form--commerce_add_to_cart',
      'path' => $path . '/templates',
    ),
  );
}

Then you can use a file in

MYTHEME/templates/form--commerce_add_to_cart.tpl.php

and in the template file

print drupal_render($form['element_name']);
// or
print drupal_render_children($form['element_name']);

to specify exactly where to render each form element.


Is hook_file_download the right hook for taking action when a private file is downloaded?

If I recall correctly, there's an access pass before hook_file_download is ever called. hook_file_download is called so you can modify headers, or do a last minute abort on the download.

So on the assumption that no one else is calling that hook (which you should check for the modules you have installed), a hook_file_download implementation is a perfectly fine place to do something like call a Google API. The only caveat is that if you're calling a web service, you want to make sure it doesn't take so long as to screw up the download.

I'm fairly certain that the hook will be called for any file scheme (i.e., "private:", or a custom scheme).  You may want to look at the Drupal 7 Example module "File" example, which I believe shows a hook_file_download implementation.

The behavior in Drupal 8 is similar, BTW.


How can I hide Delete option from Operations in Admin - Drupal 7

There is always more than one way to skin a drupal, but they are rarely of equal merit.

It sounds like you have a page that is using Views Bulk Operations?  If that is the case, find the view that generates the page and remove Delete from the operations selected.

If that is not the case, but you would like it to be, then see if the page in question is covered by Admin Views.  Enable the module, find the related view, and modify it to suit you.

If that also is not the case, then fortunately for you this interaction is a form of some type.  You can use a hook_form_ID_alter() function to change the $form['field']['#options'] array and remove Delete from it.  If php is not your language, I am sure there is a javascript method of doing the same thing ... but I don't like that, feels like too weak of a solution.  You can also have this same alter function check the global $user; $user->roles array so you retain the delete function for yourself.

If you want to let the user in question retain the Delete option, and just fail when they select that for a nodetype that is out of their permission range, then use drupal form validation.  This lets the form stay as it is, but if your check of the node types selected does not match up with the current user's roles then you can just fail their action before it reaches the next screen.

There is always more than one way, they may not all work for you but one of them should.  If none of these match your need then please update the question.


Using Entity Registration, how can I create a view that shows all the events that a user has NOT registered for?

I'm afraid it will be hard.

Seems like you are looking for something like this feature - sadly, it is not implemented (yet?). Problem is, SQL does not support anti-joins in any reliable generic way, so most of generic solutions built on top of SQL databases can't do it, either. Materials I used to code similar case (or similar ones) are still to be found under this search: http://google.pl/search?q=sql+anti-join

Maybe there is a way to create view like that. If you only want it to work when view is filtered by one user, you could implement hook_query_alter(). Use ->hasTag() to determine if query came from the view you want to alter, and then ->conditions() to make sure it shows results for just one user (to avoid things getting messy). Then you can outer join appropriate table and (if it's our usual many-to-many intermediate table), only select rows where registration entry ->isNull().


Yes, you can do it with Rules module.

Basically, after enabling the Rules & Rules_UI module, you create a new Rule acted on a node is created, add an action of creating a new user entity. You need to spend a bit of time to specify the condition to suit your need.

Some screenshot of flow attached for you.


Consider looking at the Image Class module, which extends the Image formatter by adding an option to add an element class.

It requires the Field formatter settings module (dependency).


In Drupal 8, you can archive your webform if it's closed.

To close your webform, go in the settings of your webform in the "Form" tab. You can schedule the closing too.

When it will closed, you will have the option to archive it in the "General" tab of its settings.


Sounds like your memory limit on your server is too low.

Have a look under Reports >> Status report what it is.
Default on most servers are 32M. This is too low.

If you do not manage your own server then go beg your server admin to increase it. I can't give you a number, best to increase in 32Mb steps until you are happy.
I normally set mine to 256Mb during development and drop it to 128Mb on fairly large sites (this is just a guideline what I do).

If your server admin does not want to change it then first answer would be to get a new provider, which I know is not always the correct route. But read here how you might be able to set it yourself. Increase PHP settings


Allow customer to change Quantity in cart

Go to the display settings of the product(#overlay=admin/structure/types/manage/product_display/display)
Click on the gear icon and select the checkbox "Display a textfield quantity widget on the add to cart form."


Views: List content NOT authored by the logged-in user

In contextual filter, scroll all the way down, click on "▾ MORE" and check mark ☑ Exclude


Removing Queue Table Items / Queue UI Module D7

The default Drupal supplied queues only exist when they have $items within them. It will be regenerated when it's next inserted into.

Depending on whether or not a worker process is working on a claimed item the queue item(s) when you delete the queue -- you may raise like a warning when the process tries to notify the queue of completion of an item. It shouldn't break the queue itself; the worker processes may need to be reset of course.


Removing the "File Browser Tab" for certain roles

No need to do any coding. We can do it through admin dashboard itself.

Just go to below link:

  /admin/config/media/imce

Under "Role-profile assignments" just choose "Public Files" as NONE against a user role to whome you don't want to show the "File Browser".


How to display messages from a block separately from $messages in page.tpl.php

If the notification is being set in the $messages variable used in page.tpl.php you can emulate theme_status_messages() by adding this to your theme's template.php file

function YOURTHEME_preprocess_block(&$vars) {

  $block = $vars['block'];

  if ($block->module == 'MODULENAME' && $block->delta == 'DELTA') {
  $output = '';
  foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
    $output .= "
\n";
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }

  $vars['messages'] = $output;
  }
}

Then in the template file for just your block (e.g. block-MODULENAME-DELTA.tpl.php), print the $messages variable.


Error in simplenews when send the node more than one

This is by design. Why would you want to send the same newsletter twice?
If you want to test your newsletter, choose the option "Send test newsletter". This can be done multiple times before sending out the newsletter to all subscribers.

EDIT: I just saw your other question (you should maybe combine both) and if you want to send a newsletter containing a View on a regular basis, see my answer to the other question or my documentation on drupal.org.


How do I get the number of nodes using terms from a vocabulary on the same line together the link to the term page?

Yes. By default, a HTML List View displays fields wrapped in a couple of DIVs, a block-level element. Hence, it displays each field on a new line. To disable this, use the Style Settings > Customize field and label wrapper HTML checkbox for each field to use an element that isn't a block-level element (e.g. SPAN).


Form API and Ajax frameworks work quite well together.

In your submit button, that you want to trigger the popup, it should work as an Ajax element first.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit (and open popup)',
);

If you use submit and validate handlers as you have shown in your question, those submit and validate handlers will be executed at this point. If you want different submit/validate handlers, then you have to add them to the submit button itself.

Now, add #ajax property to the element.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit (and open popup)',
  '#ajax' => array(
    'wrapper' => 'id_of_some_unique_element',
    'callback' => 'my_module_give_this_function_a_nice_name',
  ),
);
ctools_include('modal');
ctools_modal_add_js();

We play a trick here. Typically, #ajax property is used to replace some parts of the form. That's why we use the wrapper to indicate the replacing element. This will not be used at all if you trigger the modal, but make sure you refer to a unique DIV. Better leave it empty.

The callback is what we need. This callback should be a PHP function name, that returns some or full $form first parameter, or, it can print some Ajax commands. Do not set $form_state['rebuild'] = TRUE in your #submit handler.

ctools_add_modal_js() adds the modal.js file because it's necessary to trigger the popup.

function my_module_give_this_function_a_nice_name($form, &$form_state) {
  // this function gets the $form_state after submitting the form. All values, including the submitted values preserved.
}

Now, we need to print the modal contents.

function my_module_give_this_function_a_nice_name($form, &$form_state) {
  // this function gets the $form_state after submitting the form. All values, including the submitted values preserved.
  ctools_include('modal');
  ctools_modal_add_js();
  $commands = array();
  $commands[] = ctools_modal_command_display('title', 'modal content goes here');
  // You can add extra modal using drupal_add_js/css. You can also have them `#attached` to a rendarable array that you are going to print.
  print ajax_render($commands);
  exit;
}


Why are some contrib module functions not recognized?

Do module load include of twitter.inc in which above function was defined.. .module files are automatically included, but .inc are not. So you need to include them using above function...

module_load_include('inc', 'twitter', 'twitter');
dpm(module_load_all()); // returns 1
dpm(module_exists('twitter')); // returns 1
dpm(twitter_account_load('@twitter'));


You can't (at least not directly). Don't forget that multiple taxonomy terms may have the same name so they need to be identified by their tid or you'd get clashes.

You have a couple of options to load a taxonomy term by name, but for each you'll need to know the vid of the term's vocabulary.

The first option is to use the deprecated $conditions parameter of the taxonomy_term_load_multiple() function:

$terms = taxonomy_term_load_multiple(array(), array('name' => 'online', 'vid' => $vid));
$first_term = array_shift($terms);
$tid = $first_term->tid;

As you can see it's limited to loading just one term at a time.

The second (much better) way is to use an EntityFieldQuery:

$terms = array(
  'online',
  'offline',
  'pre-online'
);

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $vid)
  ->propertyCondition('name', $terms, 'IN');

$results = $query->execute();

if (isset($results['taxonomy_term'])) {
  // Get an array of tids
  $tids = array_keys($results['taxonomy_term']);
}

That way you can load multiple terms in one go, and take advantage of non-SQL field storage solutions if you need to.

If you're worried about speed you could also go directly into the taxonomy_term table to get this data; but I don't advise doing this unless you really know what you're doing.


Special Character Encoding Issues in Node Titles

I just checked with Drupal 7, and it will replace Unicode Character 'APOSTROPHE' with its NCR equivalent (&#39;) in headings.  This is not a bug, but a security measure.

Apperently, when FaceBook receives this, it changes it to &amp;#39, with the result you observe.  IMHO, this is a bug in how Facebook treats incoming NCRs, and has nothing to do with Drupal.  (It is not a good idea for Drupal to have plain apostrophes in headings.)  You may want to report this bug to Facebook, but it will probably not be their top priority.

You may also add a feature request to the authors of the module the sites uses to interact with FaceBook, asking it to rewrite NCR apostrophes into a single byte ASCII before sending to FaceBook.  They may be more symphatetic.

(Btw: This problem has already been mentioned on stackoverflow: https://stackoverflow.com/questions/11821400/apostrophes-turns-crazy-on-facebook-app - but I'm pretty sure the upvoted answer is hokum.)


Set the id property of a form element using D6 Form API?

I would avoid changing that at all and use the Drupal-generated IDs in your Javascript. I have never been forced to do otherwise.

Keep in mind, however, that you'll have better luck if you use classes or if you prefer IDs that don't have a node ID or other sequence-based ID in them. For example, I try to avoid using IDs when theming webforms because if I create the webform on another site, the ID will change.

If there are existing styles for what you want to do, I would check which selectors they are using as well.

Remember that you can add your own classes with the theming layer and then you can use them for your Javascript or jQuery. Sometimes this is the best choice, and I've done it numerous times.

If worst comes to worst, implement hook_form_alter and change the #id in question. If your form continues working, then you're good.


How do I include a CSS library in my custom module?

Fundamentals

To bind a CSS library into your Drupal installation, it should be defined and exposed via a *.libraries.yaml file.

For example (taken from core's classy theme):

book-navigation:
  version: VERSION
  css:
    component:
      css/components/book-navigation.css: {}

defines that there is a library called book-navigation that when included in a page will deliver the css/components/book-navigation.css css file.

Using composer with 3rd-party CSS libraries

Composer works easily and reliably for PHP dependencies, using the merge-plugin in the way you started working in the OP. But, CSS and Javascript libraries, especially when some preprocessing or building step is required, are a different story.
This is an open and unsolved (to my knowledge and to the date) problem, you can read this issue to get an idea of what problems arise:

https://www.drupal.org/project/drupal/issues/2873160

The main problem is, that when you import the library as a composer dependency, as you did, the library is installed inside the vendor directory wherever that is located. So, you cannot assume much inside your *libraries.yaml file about the file path to the CSS/JS file(s) you want to use.

Alternative (A) without composer: using CDN / externally hosted libraries definitions

For you case, and taken that you want to include this file:

https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css

you could define it inside your *libraries.yaml file as an externally hosted library (see #external):

my_module.yamm3:
  remote:  https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css
  version: VERSION
  license:
    name: MIT
    url: https://github.com/geedmo/yamm3/blob/master/LICENSE.txt
    gpl-compatible: true
  css:
    theme:
      https://raw.githubusercontent.com/geedmo/yamm3/master/yamm/yamm.css : { type: external }

N.B.: This approach should always deliver the latest yamm.css version.

Alternative (B) without composer: keeping a local copy in your own module's folder

If you place the CSS file inside your module's folder, e.g. css/yamm.css, you will be able to use the following yaml definition in your *.libraries.yaml file in order to be able to use it:

my_module.yamm3:
  version: VERSION
  css:
    theme:
      css/yamm.css : {}

Attaching a library to page(s)

Finally, after you are done defining your library, you can start using it.

This is documented extensively here (https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module) and I would recommend reading that if you haven't already.

Good luck!


Need to add SKU to order confirmation email - Commerce 2

I found this article that helped:

https://www.drupal.org/forum/support/module-development-and-code-questions/2018-08-23/drupal-8-commerce-2-get-item-from

This is my commerce-order-receipt twig that displays the quantity, title, price and in a row below the sku.

Hope it helps.

      {{ 'Order Confirmation'|t }}

        {{ 'Order #@number details:'|t({'@number': order_entity.getOrderNumber}) }}

        {% block order_items %}

          {% for order_item in order_entity.getItems %}
           {% set product = order_item.getPurchasedEntity %}

              {{ order_item.getQuantity|number_format }} x

              {{ order_item.label }}
              {{ order_item.getTotalPrice|commerce_price_format }}

              SKU:

              {{ product.getSku }}

          {% endfor %}

        {% endblock %}

        {% if (billing_information or shipping_information) %}

            {% if shipping_information %}
              {{ 'Shipping Information'|t }}
            {% endif %}
            {% if billing_information %}
              {{ 'Billing Information'|t }}
            {% endif %}

            {% if shipping_information %}

                {% block shipping_information %}
                  {{ shipping_information }}
                {% endblock %}

            {% endif %}
            {% if billing_information %}

                {% block billing_information %}
                  {{ billing_information }}
                {% endblock %}

            {% endif %}

          {% if payment_method %}

              {{ 'Payment Method'|t }}

                {% block payment_method %}

{{ payment_method }}

                {% endblock %}

          {% endif %}

        {% endif %}

        {{ 'Subtotal: @subtotal'|t({'@subtotal': totals.subtotal|commerce_price_format}) }}

    {% for adjustment in totals.adjustments %}

        {{ adjustment.label }}: {{ adjustment.total|commerce_price_format }}

    {% endfor %}

        {{ 'Order Total: @total'|t({'@total': order_entity.getTotalPrice|commerce_price_format}) }}

        {% block additional_information %}
          {{ 'Thank you for your order!'|t }}
        {% endblock %}


block_admin_display_form_submit not getting called

I'm having the same issue, I cannot call function block_admin_display_form_submit($form, &$form_state).

I've set a custom variable that should be updated if I change block region.

Everything works if I do it from the block edit page(admin/structure/block/manage/menu_block/ID/configure), but if I try to do it in the block admin display form (admin/structure/block), It will not work.

I've tried to increase max_input_vars with no success.

Have you solved it?


hook_views_post_execute() don't work on AJAX View with exposed filters after 1st refresh

When checking the current route match in a Views Ajax request you get the route of the Views Ajax endpoint views/ajax and not the route of the page where the View is placed on.

However, Ajax requests contain the original path of the View and ViewAjaxController::ajaxView() puts this path in the global current path stack (for the pager to work correctly).

So if the path is no longer in the request

$path = \Drupal::request()->request->get('view_path');

it should be transfered to:

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

Which should then point to the node route you are looking for.


How to extract images from Statuses(Facebook style publisher) and display in seperate page?

I am not sure if it's related to the statuses module at all. It seems it can be a very different story, unrelated to that module. One easy way is to use bridges like janrain (rpx).


Here is one module that I found that will do this work for me. Views hacks, selective views Filters: Views Selective Exposed Filters.


If what you want to do is create a list of nodes (or fields of nodes rather) that have a certain $tid, you would create a view, probably filter it on node type and if it's published, put $tid in as an argument to further filter things based on it, select whatever fields in the nodes that pass all of these you want displayed, and then over on the top left of the form, add a block display, name it whatever you want, save it all, then go into your Blocks admin page and put that block in whatever region of your theme you want. (Or at this point use panels, but I don't, so don't know how lol) And take a couple breaths in between all of these steps :)

ADD:  Check out the http://mustardseedmedia.com/podcast/episode31 video as Bob there answers in great depth how to adjust your views to do what I think you are attempting here, and can answer all the details you need a lot easier than me going into that detail here.


You have two "simple" options and a third "hard" option, which involves writing a custom Views field ... I'm going to skip that one and focus on the simpler options.

Those links all share a common pattern with only the order ID changing based on the row you're looking at. You can use tokens ("replacement patterns") in custom text fields on Views, including the order ID if you've added it to the View's fields list. This means your first option is to add the Order ID field to the View (and hide it by "excluding it from display") and then add a custom text field that adds whatever HTML you want, using the order ID token in the URLs.
The other option would be to add custom CSS to the View that alters the dropbutton styling. In the default HTML for that operations column, it's just using CSS to turn multiple links into that dropbutton format. You can undo that with your own CSS if you'd like, using the classes on the individual links to pick the right icon or whatever from your theme (e.g. "edit", "delete", etc.).

Either one of these solutions will be much simpler than writing custom Views code, and the second doesn't involve editing the View at all. : )


What is the hook to alter links in the Book Outline tree?

Turns out there isn't one.  Had to go back to an ajax approach and update the book outline in the client browser.


Give non-administrator users acces to node-class

Here is a framework for a module to add that permission:

In your contrib module folder, add the folder node_class_perms and add these files within that folder:

node_class_perms.info
node_class_perms.module

in node_class_perms.info add this:

name = Node Class Perms
description = Alters permissions for Node Class.
core = 7.x
dependencies[] = node_class

in node_class_perms.module add this:

<?php

function node_class_perms_permission(){
  return array(
    'administer node classes' => array(
      'title' => t('Administer Node Classes'),
      'description' => t('Allows node classes to be added to nodes.'),
    ),
  );
}

function node_class_perms_form_alter(&$form, &$form_state, $form_id) {
  // Check form type && if user_access is ok
  if (isset($form['#node']) && ($form_id == $form['#node']->type . '_node_form') &&
    user_access('administer node classes')) {
    // Add form elements in vertical tab to node settings.
    if (!isset($form['node_class'])) {
      $form['node_class'] = array(
        '#type' => 'fieldset',
        '#title' => t('Node Class settings'),
        '#description' => t('Assign CSS classes to the node.'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#access' => user_access('administer node classes'),
        '#weight' => 80,
        '#tree' => TRUE,
        '#group' => 'additional_settings',
        '#tree' => TRUE,
        '#attributes' => array('class' => array('node-class-form'))
      );
    }

    // Get css attribute information
    $attributes = node_class_attributes($form['#node']);

    // Check CSS exists in DB to prepare SQL update
    if ($attributes) {
      $form['node_class']['existing_css'] = array(
        '#type' => 'hidden',
        '#value' => '1');
    }

    $form['node_class']['css_class'] = array(
      '#type' => 'textfield',
      '#title' => t('CSS class(es)'),
      '#default_value' => $attributes,
      '#description' => t('Separate classes with a space.'));
  }
}

Now install the module, then add the permission 'Administer Node Classes' to the role you want.

You can tighten the permissions if you want, but as the node edit form has already gone through a basic node-edit permission it really is not necessary.


How to set the number of front page's promoted nodes?

Configuration -> System -> Site Information

In the Front Page section there is an option for 'Number of posts on the front page'


You may want to try out the Rules module. It allows a lot of powerful conditions and actions to be configured. You may also pair it with the Webform Rules module to connect it to your Webforms (https://www.drupal.org/project/webform_rules).


The Override Node Options module looks like it would help you out. More details from the module's project page:

  The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form. It also allows selected field sets to be set as collapsed and / or collapsible.


How to resolve notice : Undefined offset: 3 in user_node_load()

I'd guess you might be right. I think I have a different version of the user module from you (different line numbers), but user_node_load() adds stuff back in from the users table.

If you are missing a user with uid 3, you will get this error.

You probably need to update all of the nodes authored by user 3 to another user, the following SQL should do the trick (replace {new_user_uid} by the uid of the user you want to move the nodes to):

UPDATE node SET uid = {new_user_uid} WHERE uid = 3;


Point dev URL to the default folder of a multisite

Above settings are correct. But there was an error in the DNS settings.


Why are nodes not saving, and redirecting to edit instead?

It was the FileField that was causing the problem. I still don't know why but I removed it and the node could be saved again.

Edit:
It seems the problem is caused by CCK fields. Nodes without CCK fields are not experiencing this problems.


Well, found my issue. I didn't enable the File entity module under Media which exposes the permission I needed to set for viewing private files.


Start your query from the Taxonomy table. Meaning select Taxonomy as your base table when creating your view. Then establish a relationship to your content from there. This will ensure your results contain all taxonomy names and then their subsequent children.


How to use tokens as watermark on images

I think Imagecache Actions can do what you want. Text Overlay watermarking comes default in this module. I haven't checked if it supports tokens but you'll notice it immediately if it does. Don't forget to enable the tokens module.


Google Translate changed their policy, this module does not work anymore according to the issue queue.

There seems to be a newer version on an external website, which also offers a paid Pro version that seems to require ioncube encoder which means that it is encrypted, which sounds like a violation of the GPL to me.


Step 1

To have such a list of authors that can be referenced, you should first (repeat: first) create a view (with the Views module) to create a list of all the authors that are allowed to be selected. And the display type of such view must be an Entity Reference display.

Step 2

Your select box field (to select from a filtered list of authors) should be field that looks like so:

Field Name = Anything you want, eg field_authors_list.
Field Type = Entity Reference, using these additional settings for it:

Target type = node
Number of values = 1, though something like "unlimited may do as well (not clear to me from your question).
"Mode" (within "entity selection") = Views: Filter by an entity reference view. However, before you can select an appropriate view at this point (which is eligible to do so), you first need to create a view with an Entity Reference display, or add such a display to an existing view. In your case, you should select the view created in "Step 1".
Pick any of the other options to define this field as you see fit.

Step 3

If the list of authors you can select (after completing the previous 2 steps) is not exactly what you want, eg "you want to have the ones in which all of authors are active, whereas active means 'have a specific value for one of their fields'" (as in your question), then refine/tune the view in step 1 so that the Views results do match with what you want the list to look like.


How to assign a user a title based on the number of created nodes?

I doubt there is a module for this, but hey. Do not let that bring you down, it's actually a great idea for a custom module! If you have a bit of patience, Drupal is very easy to learn once you get past the initial learning curve.

If you need a start, the module developper section and the create a module page on Drupal are great place to start.

There are many, many ways you could do this, but to start I would probably create a small module. Imagine it's called super_usernames, for the purpose of this post. I would just create a folder in sites/all/modules called `super_usernames. That folder would need to  contain only 2 files:

super_usernames.info and super_usernames.module. The info file is very easy:

name = Super Usernames
description = Gives special credits to usernames depending on number of posts.
core = 7.x
files[] = super_usernames.module

The module file would need at the minimum just one hook to be defined.  Hooks are just plain old php functions that use a simple naming convention in order to be executed by Drupal automatically.

The hook you need here is hook_node_view. Basically you want to add :

/*
 * Implements hook_node_load
 */
function super_usernames_node_view($node, $view_mode){
  $supported_node_types = array('page', 'article', 'blog'); // Supports default content types
  if (in_array($node->type, $supported_node_types) {
    // query to get number of nodes this user has published
    $result = db_query("SELECT count(nid) as nodecount from {node} WHERE uid = %d", $node->uid);
     $row = db_fetch_object($result);
     $node_count = $row->nodecount; // Easier to read
     switch ($node_count){
       case $node_count >= 50:
           $node->super_username = "God";
         break;
       case $node_count >= 20:
          $node->super_username = "Super Poster";
         break;
       case $node_count >= 10:
          $node->super_username = " Frequent Poster";
         break;
       case  $node_count >= 1:  // same as > 0, but who cares...
           $node->super_username = "Poster";
         break;
       default:
           $node->super_username = "Noobie";
     }
  }
}

Now. After doing this, all your nodes should contain the dynamic value of the number of nodes posted by that node's author.  This would be added on the fly on every page load from content-types articles, and pages.

You still need to have it displayed somewhere, though! This is where you would ideally create a sub-theme (so as not to hack a base theme). But for the purpose of this post, we will simply modify one file: node.tpl.php.

Check the theme you are using, by default it is bartik but the procedure is mostly the same whatever theme you are using.

Go into your themes/bartik/templates directory, open the node.tpl.php file.  Locate where you want to add the super username in the html, and add this code snippet:

<?php if ($node->super_username): ?>
  <div class="superUsername">
    <?php print $node->super_username; ?>
  </div>
<?php endif; ?>

Now. One last step, you may need to clear the cache for changes to take effect. Devel module makes it easy, Drush makes it even easier. After this, you should have your super usernames dynamically shown on all the content-types defined in the supported_node_types array.

Hope this doesn't sound too complicated, it's actually quite trivial when you go through the process a few times.  Feel free to message me or repost here if you need any help.

Happy coding, cheers!

PS: This code has been slapped up from memory, nothing is tested but should be pretty close to a fully working example. Your mileage may vary, there may be typos in there.


Have you tried using PHP to manually send the POST data? Here is a snippet from http://www.webmasterworld.com/php/3164561.htm

$server= 'www.someserver.com';
$url = '/path/to/webform/posturl';
$content = 'name1=value1&name2=value2';
$content_length = strlen($content);
$headers= "POST $url HTTP/1.0\r\nContent-type: text/html\r\nHost: $server\r\nContent-length: $content_length\r\n\r\n";
$fp = fsockopen($server, $port, $errno, $errstr);
if (!$fp) {
    return false;
}
fputs($fp, $headers);
fputs($fp, $content);
$ret = "";
while (!feof($fp)) {
    $ret .= fgets($fp, 1024);
}
fclose($fp);
print $ret;

Of course this would fail if you are using any form of captcha on the form, and will also currently fail if you are required to be authenticated to post a reponse


How to Uninstall/Reinstall a custom module whithout losing the content?

You can update your database with

  hook_update_xx

if your module define hook_shema

https://www.drupal.org/docs/8/api/update-api/updating-database-schema-andor-data-in-drupal-8


Berdir's answer gave me a search term that got me this:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

After a bit of trial and error, this is the code that works, in case anyone else needs:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$r_period = $user->field_r_period_length_sec->value;

For multiple values, use

$r_period = $user->get('field_r_period_length_sec')->getValue();


Views Dependent Filters

Allows the presence of exposed filters on a view to be controlled by
values in another exposed filter. Dependent filters are hidden when
not relevant, and their values are not considered when the exposed
form is submitted.


Drupal 8 what is the ajax event for auto complete dropdown?

use autocompleteclose event.

#ajax' = array(
  'callback' =>'get_user_details',
  'event' => 'autocompleteclose',
);


Getting empty error message when install Drupal using Windows server 2012

I figured it out, I think that trying to connect to "localhost" was failing because I should have been specifying {servername}\SQLEXPRESS instead.


add CSS programmatically for a specific page in .theme file

I could solve the problem (thanks to @Eyal).

template.theme :

function template_preprocess_html(&$variables) {

    $css_file_name = 'specific-page';
    $clean_alias = Html::cleanCssIdentifier($css_file_name);

    $activeThemeName = \Drupal::theme()->getActiveTheme()->getName();

    //OR

    $activeThemeName = 'template';

    $variables['#attached']['library'][] = $activeThemeName . '/' . $clean_alias;

}

template.libraries.yml:

specific-page:
  css:
    base:
      css/pages/specific-page.css: {}


Which Omega theme should I use with Drupal 7?

There are Drupal 7 versions of both, so you can choose either. As of writing the 4.x branch is actively maintained, and 3.x not so much.
The 3.x branch will hold your hand a lot more, and make a lot of decisions about how you want to work. This may be or ideal, or may be frustrating. SASS support is clunky and a bit of a pain to work with, if I'm honest. Its main 'selling point' is that you can configure most of the options it supports through the UI.
The 4.x branch is much more of a developer-focused solution. Very little UI, but it incorporates a full front-end stack of tools for development/asset management. If you're a developer, this will likely be the one for you.
This is what the docs have to say:

Whether you should use Omega 4.x or Omega 3.x depends on several considerations:

Do you rely on the user interface for building layouts, or are you comfortable defining layouts in code in a tpl.php file? Omega 4.x does not include the elaborate layout definition UI that was a hallmark of Omega 3.x
Do you want to use a theme that is under active development, or are you comfortable with a theme that is minimally maintained? Omega 3.x is minimally maintained. In all likelihood, unless a new maintainer steps up to the task, Omega 3.x will not be upgraded to Drupal 8.
Are you comfortable with or willing to learn SASS, or do you want to stick with straight CSS? Omega 4.x does NOT require use of SASS but certainly is much easier to implement if you adopt SASS.

Beyond that, the only way you'll get a satisfactory answer is to install and try both.
Edit: to add a bit of balance to the above docs (thanks @FreeRadical for the info):
The 2nd point (claim?) is hotly disputed. It has been written by the Omega 4.x team who currently holds "ownership" over the project pages. This is a bitter dispute and there are negotiations currently taking place which probably will get the project page rewritten soon.
Sounds like fun :/


How do I use a term as contextual filter correctly?

You don't need Relationships for matching through ER fields, IDs are enough so it's enough to use the ER field Contextual matching directly.
Instead of the ID Contextual filter add the Contextual filter for the ER field and configure it:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms by vocabulary
[Your vocabulary]
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
[Your vocabulary]
Set other options according to your needs.
You can test it by entering a Taxonomy ID into the Views Preview field, you should get only the nodes that reference that term.
When you place the Block in a theme region also configure the Contextual option, it won't work without it.


Exclude configuration from import/export

You can use the "Config Ignore" module: https://www.drupal.org/project/config_ignore

Ever experienced that your site's configuration was overridden by the configuration on the filesystem, when doing a drush cim?
Not anymore!
This module is a tool to let you keep the configuration you want, in place.


How can I filter a view by date ranges from another content type?

It's not a dropdown list, but if you don't want to write code, consider the following.

Create a view of all UK PM's in a view. Rewrite the results to output links in the format: events/start_date/end_date.

On your events view (with 'events' path). Add contextual filters catching start_date and end_date.

You could make the first view a jump menu and show it as a block above your events view. This will have the same effect as exposed filters, but will be harder to combine with actual exposed filters.


Reinstating and uninstalling the module again fix this issue for me.


The solution was simpler than I thought, it was simply using

{{ node.field_custom_title.value }}


How can I more efficiently save nodes programatically with my custom module without cron?

To fix the bootstrap issue you need to change the CWD (Current Working Directory) to where index.php is located. So in your case you are one directory deep so adding this to the top of your scripts inside of "myscripts" should make them work

// Change the directory to the Drupal root.
chdir('..');

If you were 2 directories deep the code would look like this chdir('../..');. If the errors had to do with php notices/warnings and things of that nature I would look at scripts/drupal.sh (checkout the "define default settings" section) or running your commands/functions with Drush.

There are a couple of options to help with dealing with millions of items of content per week. My recommendation is the HTTP Parallel Request & Threading Library. It will help with downloading things in parallel and doing things in background processes. As an example Link Checker recently integrated with it http://drupal.org/node/380052. With HTTPRL, Link Checker runs _linkchecker_check_links in a new process independent of cron, issue parallel http requests, and runs a callback inside of the event loop allowing work to be done locally while we wait for things to download.

The other options (That I know of) for dealing with LOTS of items are Elysia Cron and Background Process. The stock Batch API will be too slow if your looking to do millions of things per week (there are only 604,800 seconds in a week).


How do I embed an "EVA" view display in a twig template?

EVAs get added as a field with name like VIEW_ID_DISPLAY_ID. They should appear in the content variable like any other field.

If you've added your EVA to the node's display you should be able to render your EVA, with the configuration from the Manage Display screen, like

{{ content.contenu_relation_groupe_entity_view_1 }}.


The only Drupal-centric of doing this is by making sure your content type is utilizing the Private files directory for your file field. Otherwise, downloads are served by the web server.

When private file storage is utilized, this enables Drupal as the file download gatekeeper through its /system/files/{filepath} route. When the controller for the download route is called, it evokes hook_file_download() which can be used to store your ongoing file download count.

For example a custom module could implement:

/**
 * Implements hook_file_download().
 */
function MYMDOULE_file_download($uri) {
  // @TODO: Store/Increment count for unique $uri.
}

Then reference the count when building variables for your node template:

/**
 * Implements hook_preprocess_node().
 */
function MYTHEME_preprocess_node(array &$variables) {
  if (isset($variables['node']->field_MYFILE_FIELD)) {
    $uri =  $variables['node']->field_MYFILE_FIELD->entity->getFileUri();
  } else {
    $uri = '';
  }
  // @TOOD: lookup count for $uri and inject it into
  // $variables['field_MYFILE_FIELD_count'] for display
}


How to keep your Drupal 8 site synced with 8.x branch

All those comments are correct. While running Drupal 8 for a simple blog, brochureware or similar site is a good idea to test it, doing anything more is most definitely not. Upgrading any code on a production site without testing it first is a bad idea, upgrading it with code which is openly declared to be possibly broken is a spectacularly bad one.

So: build you site, upgrade locally occassionally, be ready to export your content (somehow) and reimport it into the new one (somehow). Neither of these are supported. Writing migrate sources for D8 and a CSV source and target pair would be appreciated and quite possibly would work well for this scenario. You can find me in #drupal-migrate on freenode IRC should you want to work on this.


How to hide an empty view block when using a contextual filter and NO file fields?

Add  another filter it's not important which field , as example if you have Content:title ( or any field you have in fields row) and  set filter is it's not empty.

The mechanism is simple, contextual filter cause view not consider as empty even thought there is no any row, and when you add a filter on a field that not exists it cause view considered as empty. So only add one of your view field to  filter and  check if it is not empty


Combining views slideshow and views gallery on single page

try the following:

create a copy of one of the views as a BLOCK instead of a page
under block configuration (admin/structure/blocks) for that view, limit it by page to ONLY show for the view still set as a page, and place it in the content or content bottom region


How Do You Make a 'Rules Link' Work in a Custom Content Pane?

To render a Rules link programmatically use the following:

<?php
    print render(rules_link_render('RULES_LINK_NAME', $node->nid));
?>


How to remove the Day field from a Date?

There seems to be no coding-free way to achieve this but to create a separate Number-type field for year and month.


How to clear cache bins via the admin interface

In D6 install the admin menu. By clicking on the favicon on the left hand side of the menu you can clear all/seleted caches.


How to prepopulate the currency of a commerce_price field

You can use Commerce Multi Currency module.

  This module enhances some of the multi-currency capabilities of Drupal
  Commerce.

  Current features:

  UI for fine granular definition of exchange rates. (Every currency
  combination can be defined separately if needed) Synchronization of
  currency exchange rates directly from the European Central Bank (ECB).
  UI to specify which rates shall be synchronized and which are handled
  manually. Generation of currency specific price fields inclusive
  generation of rule-set to handle them. hooks for easy integration of
  custom currency exchange rate sources.

This will give you a 'Price with currency' widget for your field.

And you will have a dropdown with all active currencies next to the price.


User can self-register unless email is on a blacklist

No need to add any custom code as your requirement is just to allow visitors to register by themselves but you want to block them for log in till the administer won't approve them, if this the scenario then just go to the following URL:

/admin/config/people/accounts

or you can navigate through Admin Menu:

configuration >> People >> Account Settings

Here you can find section "Registration and Cancellation" under which you can find:

Who can register accounts?
Select:
Visitors, but administrator approval is required

Note: You can also set "Require e-mail verification when a visitor creates an account", if you required e-mail verification too.

For validation whether the email is in your blocked List or not you can validate it by writing your own custom validation function using:

function hook_form_alter(&$form, &$form_state, $form_id){

if($form_id == 'user_register_form'){

  $form['#validate'][] = 'your_validate_func_handler';

}

}

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

// here is your code to compare

}

Note: "hook" will be replaced from your custom module name.

Hope this will help you.


Solved it in Hook_preprocess_page(&$vars) {

  $all_warnings = $_SESSION['messages']['warning'];
  foreach ($all_warnings as $nr => $messageinfo) {
      if (strpos($messageinfo,"do not have permission to moderate") != false){
        unset ($_SESSION['messages']['warning']);
      }
  }


Solution:
It took me quite a while to figure this out.
Let us say you want to use Verdana as the default font. Here is what you can do:

Open contents.css and change the font tag:

font-family: Verdana;
In the application/page where the output will be published, add this style:

.entry-content {font-family: Tahoma;}

That's it! Now you have change the default font successfully. This works for the font size as well. I just finished developing this question2answer site, http://banatbanat.com, which utilizes CKEditor and this tiny issue kept me awake for two days!


How to customize validation functions for some field?

In order to add a validation for a entity field and that validation can work in any form you can use entity validation constraints, and add programatic validations.

/**
 * Implements hook_entity_base_field_info_alter().
 */
function foo_entity_base_field_info_alter(array &$fields, EntityTypeInterface $entity_type) {
  // Add Bar constraint to the user name.
  /** @var \Drupal\Core\TypedData\DataDefinitionInterface[] $fields **/
  if ($entity_type->id() == 'user' && !empty($fields['name'])) {
    $fields['name']->addConstraint('Bar');
  }
}


Related Content By Taxonomy Term and fields

You don't need to duplicate Taxonomy Vocabulary, one is enough.

You do need to have two Fields referencing the same Taxonomy Vocabulary, one for Department categorizing it, and the other for Select through which you're controlling what the related content is.

This is still a case of showing sibling nodes but through criteria of matching one field to a different field that just happens to references the same taxonomy.

Create Views listing your Organization nodes in a Block Display
Add Filter Select, set it to your vocabulary and then choose Is not empty (NOT NULL)
Add a Contextual filter for the Field Department and configure it:
 When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
[your vocabulary]
One or more IDs separated by , or +
Place your block in a region shown only on Organizations, you will see nodes listed that are tagged with the term that is in the current node Select field.

This solution relies on the concept that you won't have the same terms in Select Field that you have in the Department field.


Simplenews send mail when specific content is created

One reasonably straightforward way of doing that is with the Rules module.

Assuming there's only a few recipients, not hundreds...

You can use a "Send email" action to conditionally send an email to specified recipients.

Here's some example Rules that can be imported.

1. Basic "Send email" rule

{ "rules_send_email_notification_engineering" : {
    "LABEL" : "Send email notification (engineering)",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Mail" ],
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "AND" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_department" } },
          { "data_is" : { "data" : [ "node:field-department" ], "value" : "engineering" } }
        ]
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "example@example.com,example2@example.com",
          "subject" : "New student record created [engineering]",
          "message" : "Sample message"
        }
      }
    ]
  }
}

You could also use the "Send mail to all users of a role" action in Rules to send to all users assigned to the "Engineering department" role, if such a role existed.

Update:

2. Create and send a simplenews newsletter with Rules

Here's how to create and send a newsletter with Rules:

{ "rules_send_email_notification_engineering" : {
    "LABEL" : "Send email notification (engineering)",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "Mail" ],
    "REQUIRES" : [ "rules", "simplenews_rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "AND" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_department" } },
          { "data_is" : { "data" : [ "node:field-department" ], "value" : "engineering" } }
        ]
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "simplenews",
            "param_title" : "New engineering student record created.",
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "entity-created:status" ], "value" : "1" } },
      { "entity_save" : { "data" : [ "entity-created" ] } },
      { "simplenews_rules_action_send" : { "node" : [ "entity-created" ] } }
    ]
  }
}

You can set other field values on the newsletter node as required with the data_set action.


Use multiple URL arguments to prepopulate multiple entity reference fields

You can follow the same approach given in the example.

You will need to rewrite the link from

http://example.com/contactform?field_name=12345

to

http://example.com/contactform?field_name=12345&field_name_second=4567&field_name_third=890

This should do the trick for you.

If you want it to look more elegant, then you can just pass the entity id of the referring object and then write some code to pre-populate the values based on the given entity.


Can any one please explain to me where I am going wrong please?

libraries:
  - thunder_admin/global-styling

There is no need to load the base theme's library, so this needs to be your theme's library.

libraries:
  - my_theme/global-styling


Entity Reference + Views + Profile 2 | User Filtering

I believe its because profiles are an entity unto themselves. So you are referencing users which means that if you want the profile fields to be searchable you will need to add a relationship in the view to User:Profile. Then use this relationship on the profile fields you want searchable.

Alternatively you could use entityreference to refer to the profiles directly from the content type.


Separate exposed sort form from exposed filter block

I didn't see solution for such issues.
But I solved these issue with custom form elements and using the hook_views_query_alter.
In the hook_views_query_alter you can alter orderBy property.


For blocks, Title fields is optional so it is not required to enter. However
Description field is mandatory to enter but it displays in the admin side listing only.

So you can keep title blank or use <none> as Patrick mentioned in his comment.


Is it possible that these modules conflict with each other?

I'd like to clarify.
As far as I can tell, there's no way to use Draggable Views to reorder a View that uses the Views Accordion display format. However, as Jens mentioned, you can follow the instructions on the Draggable Views documentation page to clone the Views display and change its display format to Table or HTML List. This cloned display can then be used to order the items, and the order will be respected on the Views Accordion display (as long as it's part of the same View or uses Field API weights).


How to theme a custom object from an external datasource?

You should use hook_theme() for that:

  Register a module (or theme's) theme implementations.

  The implementations declared by this hook have two purposes: either they specify how a particular render array is to be rendered as HTML (this is usually the case if the theme function is assigned to the render array's #theme property), or they return the HTML that should be returned by an invocation of theme(). See Using the theme layer Drupal 7.x for more information on how to implement theme hooks.


How to change composer file directory after it has been set?

RuntimeException: Error creating directory: /home/phislub9/public_html/sites/default/files/composer in composer_manager_file_dir() (line 299 of /var/www/html/psrlivetoupdate/sites/all/modules/composer_manager/composer_manager.module).

Is this location, sites/default/files/composer not accessible?. I think you probably need to update some permission or maybe create the file manually. This means that you can't upload files.

I think the variable is composer_manager_vendor_dir

If so, running this,

drush variable-set composer_manager_vendor_dir 'path_here'

Would update it.

If that's not the variable, running

drush variable-get

Should list all the variables and it's just searching which is the right one.

  I've run into an issue where I need to fix a composer error in my production environment

You should consider not moving your database from Development to Production for this exact reason.

Check the Features module and other ways to move configuration into production, without having to import the database.

Always move your database from Production to Development, and move code from Development to Production.

This way, if you had to change something or apply a fix, it would be on your development environment, not on production.


Display views block only on user profiles

If you want to display this block only if the path "username" you should use Context.

In the view you have to add the relation on "Author" and then you should have the filter criteria to show contents of the logged user.

With Context you can say "When I'm on the path X then display the block Y in the region Z".


I would suggest you look at
This helps you translate whatever you need to have translated

Internationalization

The default language is always enabled as a detection method and that will  give you a fallback language if none of the other language detection methods are available.

(if your using Entity Translation)
You will have to enable the translation of nodes or entities that would be translatable at admin/config/regional/entity_translation.

After that you should :

  Be able to enable "Multilingual support: Enabled, with content
  translation" on the content type edit form under "Publishing options".
  For example, for a content type named "example", this would be at
  admin/structure/types/manage/example/edit in the "publishing options"
  fieldset.

// Randy Fays answer to this

Try to check out this, It might also be helpfull depending on how you want to go about it

Entity Translation

Title module will help you translate node titles

Sources I used in this answer

Randy Fays blog - Multi Lingual (thank you, for making this great post

I found this helpfull too.

Multi Lingual Setup Guide

I hope it was helpfull

Best regards


How to programmatically add a user to a group in Drupal 7

I figured it out. It ended up not working because the group ID is NOT the same as the node ID for that organic group. Here is the working version:

function MYMODULE_page_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1; //(1 or 0): published or not
    $node->promote      = 0; //(1 or 0): promoted to front page
    $node->comment      = 1; //2 = comments on, 1 = comments off

    $node->og_description   = t("OD Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    // Get the group ID from the node ID
    $group = og_get_group("node", $node->nid);

    // Load the user we want to add to the group (ID #2 was my test user)
    $account = user_load(2);

    // Add the user to the group
    og_group($group->gid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
            ));

    // Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
    og_role_grant($group->gid, $account->uid, 3);

    drupal_set_message(t("Finished"));
}


Form state redirects do not respect https

On another server the same is not working: on this server the domain
  is only reachable via https - not via http

Perhaps a redirect to force HTTPS was not set up on your other server.

see Enabling HTTP Secure (HTTPS). You can do this by altering the VirtualHost definitions on your 2nd server:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect "/" "https://www.example.com/"
</VirtualHost>

or alternatively you can do it in the .htaccess file by adding:

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Save button missing from content type edit form

The problem was the i18n synchronize translations module. Disabling it fixed the problem. Of I have to immediately re-enable it afterwards since I actually use this module. So I filed an issue: http://drupal.org/node/2004260. Thanks to Ayesh K who gave me the idea in his comment on my question. Since it's not an answer I can't mark it correct, so I'm just answering here and will mark this correct.


You need to call drush when you are within your Drupal folder. Otherwise drush does not know where your database is and so on.

cd /public_html/site2

Alternatively, you can set up a .drush/aliases.drushrc.php (Google should be able to tell you more about it) but that's probably not worth the effort in your case.


Drupal theme layout - recommendation based on example needed

If it were me I'd start with Bartik and go from there.  It's very solid and flexible.  It has the main elements you'll need.

But that's just me.  Take a look at http://drupal.org/project/corporateclean

If you are looking for something extremely quick and easy, your best bet is just browsing the different template websites that offer Drupal designs.  These have some themes similar to what you're looking for:

http://www.templatemonster.com/drupal-themes.php
http://www.themeshark.com/
http://fusiondrupalthemes.com/
http://www.sooperthemes.com/drupal-themes


You need to set the text format as Full HTML, text format select list will available below the body text area.

If the text format is specified as Plain text, then it will remove the html tags.

You can find out more information and best practices here - Specifying the allowed formats for user input


How to setup Advanced Content Filter to not remove drupal-entity tags?

Try this :

admin/config/content/ckeditor/edit/Full->
Advanced Options ->
Custom JavaScript configuration ->
Paste in:  config.allowedContent = true;
Save


Override a view definition programmatically

Ok, I got to a working solution :

$my_view_name = 'my_test_view';

$view = views_get_view($my_view_name);
if ( $view ) {
  views_delete_view($view);
}

// ... code from view export UI ...

$view->save();

If the view exists already then I delete it before recreating it.

Then I throw in the code taken from the views export UI, and add right after a $view->save();

And that does it.


How to enable IMCE in a field of a custom block

You can provide an alternative URL input(type=text) for IMCE integration.

You just need to include drupal.imce.input library and set the input class name as "imce-url-input". Also see imce.input.js file

if (\Drupal::moduleHandler()->moduleExists('imce') && \Drupal\imce\Imce::access()) {
  $form['background'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Background URL'),
    '#attached' => array('library' => array('imce/drupal.imce.input')),
    '#attributes' => array('class' => array('imce-url-input')),
    '#default_value' => isset($this->configuration['background']) ? $this->configuration['background'] : '',
  );
}


Content type not responding to AJAX callback

yes it seems like panles content type plugin handles the ajax calls differently. You could use the ajax commands listed in the ajax.inc file in core. There are functions for ajax_command_remove, ajax_command_append and more...

Here is my ajax callback that i call from my ajax form submit button
example:

function my_form_ajax_callback($form, &$form_state) {
  $output = '
Clicked!
'
  $commands = array();
  $commands[] = ajax_command_remove('#id_to_remove');
  $commands[] = ajax_command_append('#id_of_wrapper_to_insert_in', $output, $settings = NULL);

return array('#type' => 'ajax', '#commands' => $commands);
}


Is it possible to uninstall a module which is causing some errors?

Yes, you can uninstall it, here is the easiest way-

If you have phpmyadmin access then-

You can disable a module via phpMyAdmin by login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save. So this will disable the module, now you can access your site and can easily login to backend and uninstall the module.


Getting the value of a user reference field and using it to display information about that user

You will have to use Views for Drupal 7. First time you will have to do it manually.
Then you can convert to module using Features module. Features will give you an auto generated module that will product the same view block on the behalf of Views.


Add AJAX to form that was loaded through AJAX

You need to provide Drupal.attachBehaviors with the context (what was added) and the Drupal.settings. You should also use context in your script, so the JS should be rewritten something like this (not tested)

(function ($) {

  Drupal.behaviors.aforms = {
    attach: function(context, settings) {
      $('body', context).on("click", "#load-me-up", function() {
        $('#target-container').load('/aforms/article', function() {
          Drupal.attachBehaviors($(this), settings);
        });
      });
    }
  }

})(jQuery);

You need to use context on the $('body') to avoid the handle to be attached multiple times.
In the load callback you need to add $('#target-container') to attachBehaviors, but in this case $(this) should be the same thing.


How to exclude current page from Views results when "taxonomy term ID (with depth)" is set?

Query Preview will not be show when you add contextual filters.

You will need to add 'nid/termid' in "Preview with contextual filters:"

In short, Contextual filters will take nodeid/termid from URL.


How can I prevent user data being cached and showing the wrong username?

You are retrieving the user name from the current context and the user entity, but then you make it a dumb string value to pass it to the template. Include the cache metadata to define where this value is coming from and under which circumstances it could change:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$firstname = $user->get('field_firstname')->value;

$variables['firstname'] = [
  '#plain_text' => $firstname,
  '#cache' => [
    'contexts' => ['user'],
    'tags' => $user->getCacheTags(),
  ],
];

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


How to fetch X random entities of a given type using rules?

Investigate the Views Module.  It can create lists of nodes for you.  Investigate node_load() and node_save().  They will allow you to modify those nodes.


You can always add access argument "edit own page content" replace page with you content-type name. If you want more complex permissions you can add your own access callback to a menu item which will return true or false. For further information check http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7


Move timezone field in user/%/edit field

The next snippet should work

<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    $form['#after_build'][] = 'MYMODULE_user_profile_form_pre_render';
  }
}

function MYMODULE_user_profile_form_pre_render($form) {
  $form['timezone']['#weight'] = -10;
  return $form;
}


Why do I have to add main-menu under features[] in the theme info file?

The features elements in the .info file are used to add or suppress Drupal core/global theme settings. If you add any features options to your .info file, you must add all of the options you wish to have available to your theme. All of the options are included by default if no features options are added to the theme's .info file.

If you want to set the default setting for any of these features to your theme's .info file, you can use the setting entry. For example, if you wanted to default the "main_menu" option to be on, you would add this to .info:

setting[toggle_main_menu] = 1

More information on all of these topics can be found in the drupal.org Theming Guide


Since the patch in Use hook_entity_operation_alter() for manage fields and manage display links has been deployed, there is now a easier way to alter the operations visible in a list of entities. Also, the Field UI module automatically adds some operations.
Differently from what the patch in that issue shows, the hook to implement is hook_entity_operation(), which is implemented as follows, from the Field UI module.

function field_ui_entity_operation(EntityInterface $entity) {
  $operations = array();
  $info = $entity->getEntityType();
  // Add manage fields and display links if this entity type is the bundle
  // of another and that type has field UI enabled.
  if (($bundle_of = $info->getBundleOf()) && \Drupal::entityManager()->getDefinition($bundle_of)->get('field_ui_base_route')) {
    $account = \Drupal::currentUser();
    if ($account->hasPermission('administer ' . $bundle_of . ' fields')) {
      $operations['manage-fields'] = array(
        'title' => t('Manage fields'),
        'weight' => 15,
        'url' => Url::fromRoute("entity.{$bundle_of}.field_ui_fields", array(
          $entity->getEntityTypeId() => $entity->id(),
        )),
      );
    }
    if ($account->hasPermission('administer ' . $bundle_of . ' form display')) {
      $operations['manage-form-display'] = array(
        'title' => t('Manage form display'),
        'weight' => 20,
        'url' => Url::fromRoute("entity.entity_form_display.{$bundle_of}.default", array(
          $entity->getEntityTypeId() => $entity->id(),
        )),
      );
    }
    if ($account->hasPermission('administer ' . $bundle_of . ' display')) {
      $operations['manage-display'] = array(
        'title' => t('Manage display'),
        'weight' => 25,
        'url' => Url::fromRoute("entity.entity_view_display.{$bundle_of}.default", array(
          $entity->getEntityTypeId() => $entity->id(),
        )),
      );
    }
  }

  return $operations;
}

Before that patch was deployed, you had to implement a list controller and use its getOperations() method. For example, for nodes that is done in NodeTypeListController, whose NodeTypeListController::getOperations() method contains the following code.

  if ($this->moduleHandler->moduleExists('field_ui') && user_access('administer node fields')) {
    $operations['manage-fields'] = array(
      'title' => t('Manage fields'),
      'href' => $uri['path'] . '/fields',
      'options' => $uri['options'],
      'weight' => 0,
    );
  }
  if ($this->moduleHandler->moduleExists('field_ui') && user_access('administer node form display')) {
    $operations['manage-form-display'] = array(
      'title' => t('Manage form display'),
      'href' => $uri['path'] . '/form-display',
      'options' => $uri['options'],
      'weight' => 5,
    );
  }
  if ($this->moduleHandler->moduleExists('field_ui') && user_access('administer node display')) {
    $operations['manage-display'] = array(
      'title' => t('Manage display'),
      'href' => $uri['path'] . '/display',
      'options' => $uri['options'],
      'weight' => 10,
    );
  }

The description for the class simply says "Provides a listing of node types." Looking at the plugin annotation for the NodeType class, you could notice a reference to NodeTypeListController.

@EntityType(
  id = "node_type",
  label = @Translation("Content type"),
  module = "node",
  controllers = {
    "storage" = "Drupal\Core\Config\Entity\ConfigStorageController",
    "access" = "Drupal\node\NodeTypeAccessController",
    "form" = {
      "add" = "Drupal\node\NodeTypeFormController",
      "edit" = "Drupal\node\NodeTypeFormController",
      "delete" = "Drupal\node\Form\NodeTypeDeleteConfirm"
    },
    "list" = "Drupal\node\NodeTypeListController",
  },
  config_prefix = "node.type",
  entity_keys = {
    "id" = "type",
    "label" = "name",
    "uuid" = "uuid"
  }
)

The class defined as list controller for your Vendor Type entity uses the following code, for ConfigEntityListController::getOperations().

public function getOperations(EntityInterface $entity) {
  $operations = parent::getOperations($entity);
  $uri = $entity->uri();

  // Ensure the edit operation exists since it is access controlled.
  if (isset($operations['edit'])) {
    // For configuration entities edit path is the MENU_DEFAULT_LOCAL_TASK and
    // therefore should be accessed by the short route.
    $operations['edit']['href'] = $uri['path'];
  }

  if (isset($this->entityInfo['entity_keys']['status'])) {
    if (!$entity->status()) {
      $operations['enable'] = array(
        'title' => t('Enable'),
        'href' => $uri['path'] . '/enable',
        'options' => $uri['options'],
        'weight' => -10,
      );
    }
    else {
      $operations['disable'] = array(
        'title' => t('Disable'),
        'href' => $uri['path'] . '/disable',
        'options' => $uri['options'],
        'weight' => 20,
      );
    }
  }

  return $operations;
}

To get the same links, you should define a custom class that extends ConfigEntityListController and implements EntityControllerInterface, adding in the getOperations() method the necessary code.


Add a meta content="noindex,nofollow" tag on a node created programmatically

You can use below code for adding no-follow and no-index meta for the node. Put this code in your themes template.php file.

function MYTHEME_html_head_alter(&$head_elements) {
  if (arg(0) == 'node' && arg(1) == 'YOUR NODE NID' && !arg(2)) {
    $head_elements['MYMODULE_meta_robots'] = array(
      '#tag' => 'meta',
      '#type' => 'html_tag',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex'
      )
    );
  }
}


Translating a site where default is in two languages

When you pass string through t() without specifying a langcode, then it will default back to English.
So, if string is a French word, it will be handled as an English word.

Two options:

Always use English words in t() and use the translate interface to
translate it to French.
As per https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7
set the langcode as such t($string, $args = array(), $options =
array('langcode' => 'fr'))