How to grant only certain roles permissons over certain field?

Field permissions module now has a release candidate version for D8, this is the way to implement Role-based fine-grained control over fields.

When you enable that module edit the Content type fields you want custom permissions on, you will see a new option Field visibility and permissions where you can choose Custom permissions.

When you tick that option a table will appear listing Create, Edit and View permissions and all the Roles you have defined on the system. Add the Reviewer role to the ones who can Edit the field (Administrator is granted all by default), and adjust the other permissions as needed.

A new menu item will appear under Reports > Fields > Report all field permissions /admin/reports/fields/permissions where you can see all the Fields custom configuration in one place.


I was thinking of creating a custom module that creates form 1 which saves the info in DB tables with a unique value of SID.

Form 2, which has url of /example/% the variable % being the sid.

loads info from db using the url parameter.

$sid = request_path(); // gets the current page url. ex: example/sid
$sid = str_ireplace('example/','', $sid); // removes the example/ from our variable, so we are left with sid

Now that you have the sid inside $sid, you can query the db to grab your fields.

EX:

$field1 = db_query("SELECT field1 from {table_name} WHERE sid = :sid LIMIT 1", array(":sid" => $sid))->fetchField();

PS: In case you are wondering why the mysql query looks the way it does, see Writing secure code and How do I get only one result using db_query()


I'm not sure I understood the question... it is very simple.
You don't need contextual filter, you need to add a relationship with Flag by current user.
Click on relationship a look for Flags: User's flagged content, then select the type of flag and here we go, you got a page or a block with the content flagged by the current user.

If you are using drupal 7 import this view to see if it's what you are looking for

$view = new view;
$view->name = 'User Follow';
$view->description = '';
$view->tag = 'flag';
$view->base_table = 'node';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'User bookmarks';
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  2 => '2',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'type' => 'type',
  'title' => 'title',
  'name' => 'name',
  'comment_count' => 'comment_count',
  'last_comment_timestamp' => 'last_comment_timestamp',
);
$handler->display->display_options['style_options']['default'] = 'last_comment_timestamp';
$handler->display->display_options['style_options']['info'] = array(
  'type' => array(
    'sortable' => TRUE,
  ),
  'title' => array(
    'sortable' => TRUE,
  ),
  'name' => array(
    'sortable' => TRUE,
  ),
  'comment_count' => array(
    'sortable' => TRUE,
  ),
  'last_comment_timestamp' => array(
    'sortable' => TRUE,
  ),
);
$handler->display->display_options['style_options']['override'] = FALSE;
$handler->display->display_options['style_options']['sticky'] = 1;
$handler->display->display_options['style_options']['order'] = 'desc';
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['text']['id'] = 'area';
$handler->display->display_options['empty']['text']['table'] = 'views';
$handler->display->display_options['empty']['text']['field'] = 'area';
$handler->display->display_options['empty']['text']['empty'] = FALSE;
$handler->display->display_options['empty']['text']['content'] = 'This user has not yet bookmarked any content.';
$handler->display->display_options['empty']['text']['format'] = 'plain_text';
/* Relationship: Flags: bookmarks */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'node';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['label'] = 'bookmarks';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'bookmarks';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid_1']['id'] = 'uid_1';
$handler->display->display_options['relationships']['uid_1']['table'] = 'node';
$handler->display->display_options['relationships']['uid_1']['field'] = 'uid';
$handler->display->display_options['relationships']['uid_1']['required'] = 0;
/* Relationship: Flags: User */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'flag_content';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
$handler->display->display_options['relationships']['uid']['relationship'] = 'flag_content_rel';
$handler->display->display_options['relationships']['uid']['label'] = 'bookmarks_user';
$handler->display->display_options['relationships']['uid']['required'] = 1;
/* Field: Content: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid_1';
$handler->display->display_options['fields']['name']['label'] = 'Author';
$handler->display->display_options['fields']['name']['link_to_user'] = 1;
/* Field: Content: Comment count */
$handler->display->display_options['fields']['comment_count']['id'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['comment_count']['field'] = 'comment_count';
$handler->display->display_options['fields']['comment_count']['label'] = 'Replies';
/* Field: Content: Last comment time */
$handler->display->display_options['fields']['last_comment_timestamp']['id'] = 'last_comment_timestamp';
$handler->display->display_options['fields']['last_comment_timestamp']['table'] = 'node_comment_statistics';
$handler->display->display_options['fields']['last_comment_timestamp']['field'] = 'last_comment_timestamp';
$handler->display->display_options['fields']['last_comment_timestamp']['label'] = 'Last Post';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'empty';
$handler->display->display_options['arguments']['uid']['exception']['title_enable'] = 1;
$handler->display->display_options['arguments']['uid']['title_enable'] = 1;
$handler->display->display_options['arguments']['uid']['title'] = '%1\'s bookmarks';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['specify_validation'] = 1;
$handler->display->display_options['arguments']['uid']['break_phrase'] = 0;
$handler->display->display_options['arguments']['uid']['not'] = 0;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user/%/bookmarks';
$handler->display->display_options['menu']['title'] = 'Bookmarks';
$handler->display->display_options['menu']['weight'] = '0';


User referencing another user causes unexpected error

I think, that the user entity will be rendered at the profile page. So you should check the settings here: admin/config/people/accounts/display

Also you check if the role client is able to access user profiles, if the seller will be rendered on the clients profile page


You create a workflow state called "review" and set it so it is only accessible by Head users. Also set the states so any author can only put workflows into this "review" state - only Head users can actually change this to other workflow states.

So, the Head role can access the Workflow summary in order to review all the article group nodes which have been created in the review state.

If the Head approves it, he can change the workflow state to published which is accessible to all.

If the Head denies, he can change the workflow state to Needs work, which will mean the content remains unpublished.

If you want this to go back to the original author you can set this up with an email using actions / triggers or use the rules module.


just add a relationship for "Taxonomy term: Parent term" and select "require this relationship".
Then add a contextual filter for termID, select "parent" as the relationship and select a fixed value of the parentID.

You can also do it without using relationships. Just add a contextual filter for "Taxonomy term: Parent term" and provide a fixed value for the parent term.


Replace summary/description with another field in Views RSS output

I worked it out. On the 'Manage Display' tab for a content type, there is a 'Custom Display Settings' section at the bottom. Opening that and selecting RSS gives you an RSS Display Fields area where you can change the fields to be used. Looks like it might just work for me.


I am unable to login using linkedin integration module drupal 7?

The LinkedIn Integration module won't automatically create a new user account for you. From step 5 of the directions in the module's README:

  Usage : Users will have to associate their LinkedIn account with their
  local Drupal account (at user/%user/edit/linkedin) to use any
  functionality provided by submodules.

So if you log in via LinkedIn with a LinkedIn account that isn't yet associated with a Drupal user account, you still need to create the new Drupal user account, and then the module will automatically associate the LinkedIn account with the new Drupal account in a submit handler that it attaches to the user register form.


Using the entity metadata wrapper, you could also do:

foreach (commerce_order_load_multiple(array(), array('status' => 'pending'), TRUE) as $order) {
  $product_ids = array();
  foreach (entity_metadata_wrapper('commerce_order', $order)->commerce_line_items as $delta => $line_item_wrapper) {
    if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
      $product_ids[] = $line_item_wrapper->commerce_product->raw();
    }
  }
}

The important part here is checking the type of the line item, so you don't end up including shipping line items or other types of line items in your list of product IDs. Additionally, with the wrapper notice that I used the "raw" value of the commerce_product field on the line item. This is because the "value" would be the fully loaded referenced product, while the "raw" value is simply the product ID.


How to get the alt tag from an image field in twig?

You can get the alt of image with:

item.content['#item'].value.alt


Drupal Rooms Show Booking Unit Name in Confirmation Email

You could create a custom token to pull that info in.
Hook_token_info is the hook that makes a token available.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_token_info/7

While hook_token is the hook that actually replaces it.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_tokens/7

Since it's a multivalue field, you may need to include a numeric operator on the end (e.g. node_room_field_room_number:0) for the delta on the field.


A solution that comes in mind is:

Install Rules and Webform Rules
Go to your webform and at form settings set Redirection location: No redirect (reload current page)
Add a rule, when a webform is submitted to fire action "Show a message on the site".


Error in query : Call to a member function execute()

The join() method doesn't return the query object, so can't be used in a chain like you're currently doing. You'll need to do something like this instead:

$query = db_select('node','n');
  ->fields('n')
  ->condition('type','news','=');

$query->join('field_data_group_audience','fdga','n.nid = fdga.entity_id AND fdga.group_audience_gid = :gid', array(':gid' => $gid));

$result = $query->execute();


Drupal Doesnt Load after Installing Theme

Start by re-downloading the theme to eliminate file corruption as a possible cause. Can't say how to fix the site without knowing what's happening- If copying the files doesn't work, enable error reporting and troubleshoot from there.


How can I set some checkboxes to selected upon the first loading of the form?

Use a #default_value:

$form['my_checkboxes'] = [
  '#type' => 'checkboxes',
  '#options' => ['1' => 'one', '2' => 'two', '3' => 'three'],
  '#default_value' => [1, 2],
];


https://packages.drupal.org/7 is the correct url, its just that drupal.org does not server any content under this url. Composer will call https://packages.drupal.org/7/packages.json


How to create an iCal feed of non-Nodes?

You can do this.

Make calendar module create an extra default view:

variable_set('calendar_default_view_options', array(
  array('name' => 'calendar'),
  array('name' => 'calendar_custom')
));

After clearing cache you should now have two calendar default views which are exactly the same.
Override the custom calendar view.

hook_views_default_view_alter(&$views) {
  if (isset($views['calendar_custom']) {
    $views['calendar_custom']->base_table = 'users';
  }
}

You can change the base table of the view, which is what Views will use to determine what you can query from.

Note this is example code and untested, but should work.


That's not so easy, because the filter is normally not aware from which field it is called from.

The token filter module does this trick:

/**
 * Implements hook_preprocess_HOOK().
 */
function token_filter_preprocess_field(&$variables) {
  if (isset($variables['element']['#object']) && $variables['element']['#object'] instanceof ContentEntityInterface) {
    $entity = &drupal_static('token_filter_entity');
    $entity = $variables['element']['#object'];
  }
}

The parent entity of the field is stored in a static variable and can be used in the filter:

  public function process($text, $langcode) {
    $entity = drupal_static('token_filter_entity', NULL);
    if (!is_null($entity) && $entity instanceof ContentEntityInterface) {
      // use entity
    }
  }

http://cgit.drupalcode.org/token_filter/tree/token_filter.module?h=8.x-1.x

This may not be the best solution for most cases. If possible look for a better place for the code where you have direct access to the entity. For example in hook_entity_view_alter().


Why does my admin page appear corrupted after using Backup and Migrate?

If you forget to preserve the file permissions when restoring a backup, you'll run into this. Make sure you use tar's p flag when you extract the backup file. Run drush ws to see watchdog error logs and you'll find permission errors like this:
------ -------------- ------ ---------- ---------------------------------------------------------------------------------------------------------------------
  ID     Date           Type   Severity   Message
 ------ -------------- ------ ---------- ---------------------------------------------------------------------------------------------------------------------
  3436   26/May 18:43   php    Warning    User warning: mkdir(): Permission Denied in Drupal\Component\PhpStorage\FileStorage->createDirectory() (line 145 of
                                          /home/public/core/lib/Drupal/Component/PhpStorage/FileStorage.php) #0 /h

Fix the file and directory permissions, then rebuild the cache with drush cr and you should see:


Send variable to the user profile in Drupal 6

PHP is a "shared-nothing" architecture, nothing persists over multiple requests unless stored externally.

So you really only have two options:

Sessions. Drupal already maintains a session for you for every user (also anon users, except on the first request). So just add your data to $_SESSION['yourmodule']['yourdata'] and you have it available on the next request where you can remove it again if you want.
GET. Alternatively, you can also pass the data forward through the GET request, by doing the redirect like this: $form_state['redirect'] = array('user/' . $account->uid, array('key' => 'value')). As in my example, you should always use the internal URL when doing a redirect, Drupal will take care of the aliasing fory you.


Can the confirmation URL be different based on different selections made using conditionals?

As there is nothing out of the box that will support this
the good news it is quite straight forward in a custom module.
in this example
i have admin/structure/webform/manage/WEBFORMID/settings/confirmation
Confirmation type:
-> Page (redirects to new page and displays the confirmation message)
aka normal in your case for "Home" and "Work"
then you need a custom module to do ...
/**
 * Implements hook_form_alter().
 */
function MYODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // You will need your $form_id.
  // dump($form_id);
  if ($form_id == 'webform_submission_test1_add_form') {
    $form['actions']['submit']['#submit'][] = 'MYODULE_test_form_submit';
  }
}
/**
 * Implements hook_form_submit(). ish.
 */
function MYODULE_test_form_submit(&$form, FormStateInterface $form_state) {
  $form_values = $form_state->getValues();
  // this needs to be your element key.
  if (!empty($form_values['select_one'])) {
    if ($form_values['select_one'] === 'campaign') {
      // Redirect to some page
      $form_state->setRedirect('entity.node.canonical', [
        'node' => 7
      ]);
    }
  }
}


Given the brevity of your description, it is hard to say exactly. If you want to avoid custom coding and use contrib code (always a good thing to try first, in my option), I would consider the following.

Views Page
manager
List item

Panels.

There is a good tutorial on the above (free at the moment) from the good people at Lullabot. The presentation is actually done by Node One, and is one of the best I've seen.

http://drupalize.me/series/learning-page-manager


Your secondary menu will be available as a block.

Go to /admin/structure/block, place the block in the page region you wish to use, and set it to display only on the pages you wish to have it on.

This is much easier than trying to set up specialized templates.


How to trigger hook_form_alter() on my custom $form?

You should use drupal_get_form($form_id) to get the form instead of directly calling user_profile_form() and it will ensure that all the form alters are applied before you get the form.

Update:
          Can you explain why you are not using hook_form_alter()?

But if you want to proceed this way, then instead of calling drupal_get_form() you can replace that with the code from drupal_build_form(), except the call to drupal_process_form(),

Replace drupal_get_form() with the following code, copied from drupal_build-form()

$form_state += form_state_defaults();
if (!isset($form_state['input'])) {
   $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
}
$form = drupal_retrieve_form('user_profile_form', $form_state);
drupal_prepare_form('user_profile_form', $form, $form_state);


How am I supposed to upgrade a site to latest core version?

From Drupal documentation :

  Strictly speaking, 'updating' refers to taking your site from one 'minor' version to another, as for example, from Drupal 7 version d7.1, to d7.2; or from Drupal 8 version d8.0.0 to d8.1.3, etc.

Which means upgrade can be done only to minor version.

If you want to change the whole version for example moving from Drupal 7 to Drupal 8 you need to migrate your site, and this normally involved a data migration and restructuring, Also changing and reviewing your custom modules code.

See Upgrading from Drupal 6 or 7 to Drupal 8


In a custom zen sub-theme I currently use the following code:

$menu = menu_navigation_links('main-menu');
print theme('links__main-menu', array('links' => $menu, 'attributes' => array('class'=> 'menu')));

This is appliable to any manu – just change the name accordingly. And it's easiely printable wherever I need it (page.tpl.php). It prints a `ul´ like this:

Link 1

Link 2

Link 3


Fill a form on one website and second website automatically grabs it

You can do this with a bit of JQuery. Assuming your form action is action1.php which is on site 1 and you have another handler action2.php on site 2:

$('#form_id').submit(function(event){
    event.preventDefault();  // Stop default handling
    var $form = $(this);
    $.ajax({
        type: 'post',
        url: 'action2.php',  // Submit to the second site
        data: $th.serialize(),
        success: function(){
            $th.submit();    // Submit to the first site
        }
    });
});

And now the form will be submitted to both sites and they will both handle it


field_info_instance returns empty in hook_uninstall

You don't need field_delete_instance separately, because field_delete_field has it inside.

According to deleted column in field_config (you can skip this value in field_config_instance if you're deleting whole field) debug field_delete_field function.


Create link with 'name' attribute only using l() function

Sadly this cannot be accomplish with the l function because the href is hard-coded in the theme_link theme function.

You can accomplish this by using the html_tag theme function.

It'll look something like this

return theme('html_tag', array('element' => array('#tag' => 'a', '#value' => 'A link here', '#attributes' => array('name' => 'my-anchor'))));

This will return

A link here

Is a bit more work, but it does give you a properly formatted a tag with out the href.


Specify default sort header for a sortable table (tablesort) in D8?

I was trying  $header= [ .... ['data' => .... 'sort'=> 'DESC' , and that was not working. After step debugging, I found out the sort value is case sensitive. In function tablesort_get_order we have

  if (empty($default) && isset($header['sort']) && ($header['sort'] == 'asc' || $header['sort'] == 'desc')) {
    $default = $header;
  }

So it must be lower case to work. So the follwoing code achieve the desired behavior:

$header = [
      // The header gives the table the information it needs in order to make
      // the query calls for ordering. TableSort uses the field information
      // to know what database column to sort by.
      ['data' => t('Numbers'), 'field' => 't.numbers'],
      ['data' => t('Letters'), 'field' => 't.alpha'],
      ['data' => t('Mixture'), 'field' => 't.random', 'sort' => 'desc'],
    ];

hope this helps others.


Possible side effects when changing node type?

I've changed the content type of nodes directly in the database plenty of times and the only thing I've had to deal with is orphaned field data for nodes.

I think that this orphaned data might cause some false-positive results for certain query types (EntityFieldQuery springs to mind) but I can't be absolutely sure.

Instead of risk this I've always written a small script to go through the field tables in question and clear up any stagnant data after I've made the content type change.

I don't think you'll encounter any errors using node_load() and node_save() as you suggest; it would probably be wise to clear Drupal's cache once you've made the change in case anything needs to be updated there.


Get User's other field instead of Username,in the View?

In order to use fields of user, you have to add a relationship  (panel to the right, under contextual filter). Create a relation to the user entity.


How to ask anonymous to confirm their flag by email?

I would use hook_flag_link_type_info() to provide a link type like the 'confirm' link type provided by the flag module. Copy their approach, but on the 'confirm' form you ask for the users e-mail address (if the user is anonymous). You save the value to the email field you added to your flag and the Rules module should be able to do the rest for you. It requires a bit of custom code (not too much I would guess), but the major part of the functionality (flagging, unflagging, rules integration, ...) still comes from the Flag module.

[EDIT] For the verification part: Add a boolean field to your flag ('Verified') which you change with the verification link you send by mail. The "Solved" flag can be hidden/shown with hook_flag_access().


Prevent CSS/JS query hash when preformance is disabled

Here's the solution (theme based) in template.php

function MYTHEME_process_html(&$vars) {
  if (variable_get('environment') == 'development' && !stristr($_GET['q'],'flush-cache')) {
    $vars['styles'] = preg_replace('/\.css\?.*"/','.css"', $vars['styles']);
  }
}

NOTE: This assume you have an environment setting in your settings.local.php file like so...
$conf['environment'] = 'development'; or $conf['environment'] = 'production';


Update remaining points in different site once purchase through points method

You can call web service using hook_uc_checkout_complete. it takes action when checkout process is completed.

Please refer uc_cart api


Commerce: Unique single products + Custom line items, How to handle?

Unfortunately there's not, you need a content type to match every line item type if you're dealing with different attribute fields.
That was the original intention of Commerce custom product but it's at the point of providing different product types, but the feature hasn't been developed yet.


On the 'manage display' page of your content type you can set fields as hidden. This will make the field not only hidden also it won't load it at all.


What is the correct procedure to restore database in Drupal 7?

Deleting the database and re-importing an earlier backup is the correct procedure. Module states (enabled/disabled/version), content types, and other settings are stored in the database, so if those changes are not part of the backup you have, they will be lost. That said, you should be able to re-create them without any problems.

Modules you've added since the backup will remain there as files, and you can re-enable them at will. There is no need to delete the files themselves.


Drupal Commerce Export Orders in CSV format

You can use Views and Views Export modules.

Views Export provides you with a Export display, you do the filter in the view and in the end it will return a link where the orders can be downloaded in csv format.


How to go about creating location selector: a languages like "countries" global variable?

This is a typical use case for domain access:

https://www.drupal.org/project/domain

This module includes a domain switcher, which would be the selector widget you asked for. There is only a dev version for D8. This is a heavy weight module and until now I did avoid using it in D8 and did some custom coding for the functionality I need. To get some ideas I would investigate this module.


Create a block with information regarding the number of comments and contents created in a specific group

It sounds like this can be accomplished using the views module. Create a view of content from the group you are wanting, and then turn on aggregation. For each field, you can set it to display a count() of the field results.

For the per user part, just set up a filter/contextual filter for the UID.


Hook to change display widget in facet api from template.php

Create another index and configure facet display differently


How to programmatically create views in Drupal 7

My first guess was to create a desired view using UI, export it and paste the generated code into own module.
And I guess this is how admin_menu installs their admin views. You could install the module just for testing and see the contents of /admin_menu/admin_views/views_default/. At any rate, you would have to resort to writing a custom module and adhere to views' hooks syntax.


Commerce - Discount on three or more products in order

You may want to look at these modules that provide some extra conditions:

Commerce Discount Extra provides a "Order has product(s) and quantity" condition that might match what you want.
Commerce Discount Product Quantity allows you to set up a discount based on the number of products in an order that belong to a category (taxonomy).


You can use Secure Pages Module to configure https pages, but before that you need to get a valid SSL Certificate and get it installed in your server.


How would a customer be able to get free shipping when there are no free shipping options?

If the issue is that shipping selection needs to happen for Express Checkout users, then if you edit the Express Checkout module's order confirmation checkout pane you can choose which checkout panes from other pages should appear on the final confirmation page. Make sure you check the box there for shipping service selection and it should show up as expected.


Prevent JS from showing on specific pages

Following your logic, something along the lines of...

$mgo=menu_get_object();
if ((isset($mgo) && $mgo->type=='TYPE') || $_GET['q']=='PATH') {
  ;
} else {
  drupal_add_js(...);
}

...where you are doing your drupal_add_js(...) should do it.  I think this does it cleaner, but it's late in the logic day here:

$mgo=menu_get_object();
if ((isset($mgo) && $mgo->type!='TYPE') && $_GET['q']!='PATH') {
  drupal_add_js(...);
}

ADDITION:

$mgo=menu_get_object();
if (isset($mgo) && $mgo->type=='products') || strpos($_GET['q'], 'user/preference_center/ratings_reviews/')===0) {
  ; // do nothing
} else {
  drupal_add_js(....);
}

will add js only if you are not looking at a product node or not in a path that starts with user/preference_center/ratings_reviews/ BUT please note that if what is after user/preference_center/ratings_reviews is a node, this won't work because that path is actually node/#, so you will have to then do...

$mgo=menu_get_object();
if (isset($mgo) && $mgo->type=='products') || strpos(drupal_get_path_alias(), 'user/preference_center/ratings_reviews/')===0) {
  ; // do nothing
} else {
  drupal_add_js(....);
}

..instead.


How to show entityQuery results as block

Try the above suggestion:
Create Custom Block for example MyBlock.

In the your src/Plugin/Block/MyBlock.php File.
implement build method and getNodesBuild method to get the nodes build:

  public function build() {
    return array(
      '#theme' => 'mymodule_my_block',
      '#nodes_build' => $this->getNodesBuild(),
    );
  }

NB: Change the $nids array by the result of your Query.

  /**
   * This function return view_builder of list of nodes.
   * @return array
   */
  protected  function  getNodesBuild(){
    //- Replace this by the result of your Query
    $nids = [38, 39];
    //- Get the current lang
    $language_manager = \Drupal::service('language_manager');
    $language = $language_manager->getCurrentLanguage()->getId();
    //- Get view_builder for node entity type
    $entity_type_manager = \Drupal::service('entity_type.manager');
    $view_builder = $entity_type_manager->getViewBuilder('node');
    //- Load nodes
    $nodes = Node::loadMultiple($nids);
    return $view_builder->viewMultiple($nodes, 'teaser', $language);
  }

Implement hook_theme in your mymodule.module

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'mymodule_my_block' => [
      'variables' => [
        'nodes_build' => [],
      ],
      'template'  => 'mymodule-my-block',
    ],
  ];
}

templates/mymodule-my-block.html.twig

  {{ nodes_build }}


Find entity field order and display names in code

In Drupal, the display of fields is controlled by display mode configuration entities, which define the configuration for field formatters and the such.

You cannot get this metadata by viewing the node itself (or other entity). You would have to load the display mode for it.

The config object is entity_view_display and may be accessible over RESTful endpoints. An example output (in YAML) looks like so:

content:
  body:
    type: text_default
    weight: 0
    label: hidden
    settings: {  }
    third_party_settings: {  }
    region: content
  variations:
    type: commerce_add_to_cart
    weight: 1
    label: hidden
    settings:
      default_quantity: '1'
      combine: true
      show_quantity: false
    third_party_settings: {  }
    region: content
hidden:
  created: true
  stores: true
  uid: true


hook_menu URL giving 404 error on running site randomly

Page arguments, if specified, should always be an array. If you do not want to pass any arguments to your callback you should either code an empty array or omit the parameter. From experience I am fairly confident that this is your problem.

Also, the correct way to return a JSON response is to return NULL from your callback after printing the JSON, rather than exiting. This ensures that cleanup tasks can be run.

Your code does not comply with Drupal standards, and I would strongly advise you to follow them. It's a major part of learning to work with the framework. https://www.drupal.org/docs/develop/standards


You could try the Field Collection module. It allows you to group fields and add more of these "collections" inside the same node. Works great for slideshows for instance when you don't know how many images the site editor wants to use and you need custom fields (like big headline, small headline, promo text, link etc) grouped with the image.


Disabling Page Cache for Redirect Response

This doesn't exactly answer your question, but I feel it's relevant information. I did something similar, but I also didn't like using the kill switch. In another iteration I used a TrustedRedirectResponse which allowed me to handle my cache issue differently. My understanding is this is forcing browsers to always bypass cache when executing the redirect, but the redirect itself is cached by Drupal until $entity's (my cache dependency) cache is invalidated.
$response_headers = [
  'Cache-Control' => 'no-cache, no-store, must-revalidate',
];

$response = new TrustedRedirectResponse($url, '302', $response_headers);
// In my case $entity is a content entity where my redirect $url is generated.
// In your case you'd add cache dependencies relevant to determining shouldIRedirect().
$response->addCacheableDependency($entity);
$event->setResponse($response);


Load multiple entities with entity_metadata_wrapper

There isn't, but you can just combine the two to get the same effect:

foreach (node_load_multiple($nids) as $node) {
  $wrapper = entity_metadata_wrapper('node', $node);
}


How can I avoid users can change the "Make revision" field?

You can try Hide Revision field module with this patch. See issue [#3001097]


change the body and the title of my content type by css

Install the Firebug and find the appropriate class or id.
Look for kick start inside the zen theme and follow the instructions to crete a sub theme.
Adjust the CSS found with firebug to your needs.

After all this is basic drupal theming stuff. Check this out to get a bigger picture.


Where should I put a modified version of l() function?

You should put it in your custom module. I think it's anyway good development practice to have a custom module in every project you develop.

What I do usually, is that I create MY_MODULE.helpers.inc file, and include it at the top of the .module file.

Here's an example of .module file:

// Get helper functions.
require_once dirname(__FILE__) . '/MY_MODULE.helpers.inc';

This way, if your module is enabled, the function will become available to other modules or your theme, and your .module file is cleaner because it doesn't include the helper functions.

You can see my Drupal 7 Boilerplate and specifically the boilerplate.helpers.inc file on Github.


how to access drupal site using domain containing host ip address as prefix

It sounds like your site's settings might be in a multisite folder like /sites/dev.example.com/. When you aren't visiting via the hostname it will fall back to the settings in /sites/default/—check that those values are correct.


SQLSTATE[42000]: Syntax error or access violation (db_insert Function)

CHANGE is a reserved word in MySQL. PDO doesn't have a built-in function for quoting identifiers (just string literals and dates), so presumably Drupal simply hasn't tried to implement this on PDO's behalf.

Using a different column name would be the simplest solution.


That message error is returned also when the FFmpeg executable is found, but its output is not the module is expecting.

TranscoderAbstractionFactoryFfmpeg::adminSettingsValidate() contains the following code.

  if (!$ffmpeg['ffmpeg-found'] || ($version = self::getVersionFromOutput($ffmpeg['raw'])) == NULL) {
    form_set_error('video_ffmpeg_path', t('FFmpeg not found at %path. To convert videos and create thumbnails you have to install FFmpeg on your server. For more information please see the !documentation.', array('%path' => $ffmpeg_path, '!documentation' => l(t('documentation'), 'http://video.heidisoft.com/documentation/ffmpeg-installtion-scripts'))));
  }

PHPVideoToolkit::getFFmpegInfo() contains the following code.

$formats = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -formats');
$codecs = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -codecs');
$filters = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -bsfs');
$protocols = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -protocols');
$pixformats = $this->_captureExecBufferFallback($this->_ffmpeg_binary . ' -pix_fmts', $this->_ffmpeg_binary . ' -pix_fmt list');
$help = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -h');

self::$ffmpeg_found = $data['ffmpeg-found'] = !empty($formats) && strpos($formats[0], 'not found') === FALSE && strpos($formats[0], 'No such file or directory') === FALSE;

The message error could be returned when:

The module is not able to detect the FFmpeg version from its output
The module finds the string "not found," or "No such file or directory" in output returned from ffmpeg -formats
The command line fails for any reason

In the latter case, the first condition of !empty($formats) && strpos($formats[0], 'not found') === FALSE && strpos($formats[0], 'No such file or directory') === FALSE; is FALSE, and $data['ffmpeg-found'] is set to FALSE, causing the error message you see.

For trouble shouting, you can:

Execute ffmpeg -formats and check the output doesn't contain not found, nor No such file of directory
Test FFmpeg works perfectly when running from the command line
Execute the following code, and verify $buffer is not an empty array

$command = "ffmpeg -formats"; // Use the full path of the command line you are testing.
$buffer = array();
$err = 0;
exec($command . ' 2>&1', $buffer, $err);

if ($err !== 127) {
  if (isset($buffer[0]) === FALSE) {
    $tmp_file = '/tmp/_temp_' . uniqid(time() . '-') . '.txt';
    exec($command . ' &>' . $tmp_file, $buffer, $err);
    if ($handle = fopen($tmp_file, 'r')) {
      $buffer = array();
      while (!feof($handle)) {
        array_push($buffer, fgets($handle, 4096));
      }
      fclose($handle);
    }
    @unlink($tmp_file);
  }
}

I would execute the code I shown in the last point with both the executables, just to see if there is a difference. To be sure the problem is not file permissions, I would execute the code using the same user that runs PHP code, which means I would put the code in a PHP file on the server, and run it as http://example.com/test.php. (Replace example.com with the domain name of the site you are testing.)

If the output of the command contains not found, or No such file of directory, but it works perfectly for you, it could be the module is being too cautious about what the command returns, and it assumes it would not work even if it effectively works. In this case, there is few that can be done, if not changing the code used from the module to detect when FFmpeg would not work.

In the case you get an empty $buffer array from the test code I described, it means the user used to run PHP doesn't have the necessary permissions to execute the command. In this case, you need to change the permissions.

As you have FFmpeg installed in two different directories, I would also check there aren't some conflicts between the commands, just to be sure. I am thinking, for example, to some files the command copies in another directory, and that is version dependent; if you have two versions of FFmpeg, that could be an issue.


How to get all term descriptions from a specific taxonomy vocabulary?

I think you could use taxonomy_get_tree or just write your own query_function with the following query: db_query('SELECT description FROM {term_data} where vid = %s',$vid).


rules condition to check whether user has flagged another

Okay so I managed to work something out although I dont entire understand why its working. I created a data comparison condition and set the DATA TO COMPARE to "account:flag-consultant-flag-flagged" and DATA VALUE is set to "account:flag-consultant-flag-user".

Here was my logic although I thought it would do the exact opposite. I figured that if i compared all the flagged consultants with the consultants flagged by the current user, there should be a match and so the condition would be true. Weirdly though the rule is firing for users that didnt select a consultant so it turns out it did the exact opposite. If anyone is able to give some clarity, it would be much appreciated.


List of parent nodes with a sublist of child referring nodes on a single content type

Recapitulation

Relationships->Add->Entity Reference: Referencing entity of the Field that reference to himself. Also check Require this relationship.
Fields->Add->Content: Title.
Fields->Add->Content: Title and use the relationship.
Format->HTML list (makes a wrapper element).
Format->Settings->Grouping field Nr.1->Content: Title.
Fields->Edit Content: Title->Exclude from display (it will be displayed by the grouping).

PS Also check the Views Field View module mentioned by @tenken here


On the edit screen for your select list component (node/NODE_ID/webform/components/COMPONENT_ID), there's a checkbox labeled "Multiple" whose description says "Check this option if the user should be allowed to choose multiple values."

With that checkbox checked, by default your component will be displayed as a set of checkboxes. To get it to display instead as a select element, look further down on the edit screen for the component, under the "Display" section. There's a checkbox labeled "Listbox" whose description says "Check this option if you want the select component to be displayed as a select list box instead of radio buttons or checkboxes."

EDIT: here's a screenshot of Webform's select component interface when used with the Bartik theme:

EDIT 2:
After googling "drupal form builder select multiple", I found this issue which suggests that via form builder's UI you need to use the "checkboxes" component type in order to have a "select multiple" field. Per this question you could disable form builder's UI and then you'll get the stock webform UI where you'll find the checkbox.


Rendering nodes and other content compatible with all themes

I know that rendering should be done by the themes.

That is not exactly correct. Theme functions are generally defined from modules, and themes can override them, or implement a theme function that is specific for a purpose.

theme_node_preview() is implemented by the Node module
theme_field() is implemented by the Field module
theme_rdf_metadata() is implemented by the RDF module
Other theme implementations are contained in the theme.inc file

If you are creating the output for a page, the code for generating it should be in a module. That is because it's a module that can implement hook_menu(), which is the hook that defines the menu callback used for pages.
That is what is done from Drupal core code with node_view(), which is the page callback for node/%node, and node/%node/view. The page callback is defined from the Node module, not from a theme; themes can eventually alter the output of node_view() through the node.tpl.php template file used from node_view() to render the node page.

As for outputting the result, there are two methods:

Returning a string containing the HTML output
Returning an array with a specific structure (it is called render array) that can be used from drupal_render()

As example of a page callback that returns a string, see aggregator_view(); as example of page callback that returns a render array, see node_view().


Subtotal calculates from original product price, disregards applied per product discounts

Since this question is now almost 2 years old, I assume this "discount" that they were dealing with was an older version of commerce_discount. The newest version doesn't have any kind of subtotaling problems because it affectively utilizes the price calculation system for discounting.


How to check where in a menu tree a node is & then display a portion of the tree?

I am pretty sure Menu Block will do what you need. I have used this module to display portions of menus only under one parent item as you mention and it worked great. It's for Drupal 6 & 7 as well.


Is it safe to change INT to BIGINT or DECIMAL in database?

Usually, when you make a change of this type it is recommended to make it in a development environment, so you can make some test to check your site is working correctly.

In the case you decide to make it in a production environment, be sure you make a backup of your database, in order to restore your system in case of problems.


There is a posting from Dries Buytaert titled Drupal mentors needed, where he basically asks senior people to become mentors ("Find, motivate, guide and empower people to take on a role within the Drupal community").  So if Dries is the official voice of the Drupal community (and I suppose he is), you're supposed to hang around until some aspiring mentor finds you :-(.  Unfortunately, this very rarely gives the prospective student access to a mentor.

There has been some attempts from other community members to improve on this situation.  For instance, there is the Drupal mentor group. with first and last posts in October 2010 (and one spam post from 2012).  You could try to introduce yourself there, but the group seems to be dead.

There is also Drupal Kitchen.  There is a handful of people signed on to the site as tutors, but to me, this site looks like yet another failed effort.

If you want to learn how to contribute to the core, there is core contribution mentoring. It uses @drupalmentoring (twitter) to set up office hours and sprints for mentoring aspiring core contributors. This may be educational, but is very much oriented towards the core contribution workflow, and not suitable for learning about Drupal in general-

Here is what I suggest:  Start by getting a user account on Drupal.org and Groups.Drupal.org (unless you've already done so).  In Groups.Drupal.org, look for groups in your geographic area. Join those groups and try to find someone local to communicate with, and look for local meet-ups and sprints you can attend.

Also, use this site (Drupal Answers), the forums on Drupal.org, and IRC to ask specific questions about the problems you have developing.  You will not get a specific mentor, but you will usually get relevant help from the community.

However, in my experience, when developing a module, the best way to get the attention from senior members of the community ("mentors") is to join the Review bonus program.  This requires some effort on your part, since you're supposed to mentor others (by reviewing their modules) -  but you learn a lot from doing so!  Do not be afraid of being a novice reviewer.  You'll get feedback from the other reviewers about your reviews.   It is OK to make mistakes, and you'll learn from them.


Change the disabled status of a form element via Ajax

I found the solution here:

Enable DropDown using Ajax Call

The code finally gets this:

     function hook_models_update($form, &$form_state) {
         unset($form_state['input']['model'], $form_state['values']['model']);
         $brand = $form_state['values']['brand'];
         $form['model']['#autocomplete_path'] = 'providers/autocomplete/' . $brand;
         unset($form['model']["#attributes"]['disabled']);
         $form['model']['#disabled'] = FALSE;
         return form_builder($form['#id'], $form['model'], $form_state);
} // function

The trick lies in these two lines:

     unset($form['model']["#attributes"]['disabled']);
     $form['model']['#disabled'] = FALSE;

Apparently, there has to be an unset and not of #disabled, but #attributes - disabled. Why this is so convoluted is beyong my comprehension.


User Registration Password Module will do the job for you;)

  By default, users can create accounts directly on the registration form, set their password and be immediately logged in, or they can create their account, wait for a verification e-mail, and then create their password. With this module, users are able to create their account along with their password and simply activate their account when receiving the verification email.


What cache tables should I keep on Memcache on a multi-site server?

I guess the question is if and when those tables would be "poorly cached". This will depend completely on the actual request load of your website. Without detailed insight it's hard to give you a concrete recommendation, except that "premature optimization is the root of all evil" (D. Knuth).

Therefore, simply start with caching all tables in Memcache and then measure how effective (hits vs. misses) Memcache works. You could do this with the Memcache admin module or, with a bit more effort, using Munin. Then you'll see if you actually should shift some RAM from the more ineffective tables to the more frequented ones. That's exactly what we do to optimize Memcache on our Drupal hosting clusters.


how to include main navigation twice with different display

Don't rely on a hardcoded class in your overridden template to style the menu, but instead rely on a container to style it (for example the containing block or region).


Cann't delete the CSV file after imported by Feeds module

The "file still in use and cannot be deleted" means Drupal's still managing the file, so don't remove it via FTP because that basically bypasses Drupal and could cause other issues related to Drupal expecting a file to be somewhere and it's suddenly not there. So I'd recommend finding a solution that involves working via the UI and not directly on the file system.

Is the file attached as a field to an item of content somewhere? That would result in "file still in use". If so, delete the item of content, clear cache a few times and check again.


Fetch content from another website into a new one

You should take a look at the Feeds module. It can import many different things into your Drupal site. I am using it to import RSS feeds as nodes.


how to apply exposed filter without apply button in Drupal 8 views?

Try this It may solve your problem. It may not be the proper solution but it will help you apply filter without having to click on apply button.

(function($) {
  $(document).ready(function() {
 $(document).ajaxComplete(function(event, xhr, settings) {
 $(".views-exposed-form .form-select").change(
         function(){
           $(".form-submit").click();
         }
);
  });
       });
})(jQuery);


I wrote a module that does this!

https://drupal.org/project/commerce_shipping_field

It allows you to define a shipping cost for each individual product. Let me know if you have any other questions!


You may check my post answer. You can apply your condition. I think this may help you to solve your query.


Display image from Webform submission using views

This can not be done with webform module alone.
All you need to do is get help of 2 extra modules.

File Entity
Views Field View

Further you need to do following things.

Download and enable both of the modules and clear the cache.
Webform is storing file, not only image. I am assuming here you are only uploading image files, you can further get idea to show any type of file there. So go to Image File Type Display: admin/structure/file-types/manage/image/file-display and set the preview/image style. Or if you do not want to change settings for default view mode of the file, download another module Entity View Mode. Go to it's configuration and create specific display and set image style accordingly in file display settings.
Create a view of files, it should be a block. and there add contextual filter for the fid and add field "File: Rendered". You can set file view mode by this field. For your convenience I'm exporting the view below, you just need to import this.

    $view = new view();
    $view->name = 'file_view';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'file_managed';
    $view->human_name = 'File view';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'File view';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'some';
    $handler->display->display_options['pager']['options']['items_per_page'] = '5';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Field: File: Name */
    $handler->display->display_options['fields']['filename']['id'] = 'filename';
    $handler->display->display_options['fields']['filename']['table'] = 'file_managed';
    $handler->display->display_options['fields']['filename']['field'] = 'filename';
    $handler->display->display_options['fields']['filename']['label'] = '';
    $handler->display->display_options['fields']['filename']['alter']['word_boundary'] = FALSE;
    $handler->display->display_options['fields']['filename']['alter']['ellipsis'] = FALSE;
    /* Field: File: Rendered */
    $handler->display->display_options['fields']['rendered']['id'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['table'] = 'file_managed';
    $handler->display->display_options['fields']['rendered']['field'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['label'] = '';
    $handler->display->display_options['fields']['rendered']['element_label_colon'] = FALSE;
    /* Contextual filter: File: File ID */
    $handler->display->display_options['arguments']['fid']['id'] = 'fid';
    $handler->display->display_options['arguments']['fid']['table'] = 'file_managed';
    $handler->display->display_options['arguments']['fid']['field'] = 'fid';
    $handler->display->display_options['arguments']['fid']['default_action'] = 'default';
    $handler->display->display_options['arguments']['fid']['default_argument_type'] = 'node';
    $handler->display->display_options['arguments']['fid']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['fid']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['fid']['summary_options']['items_per_page'] = '25';

    /* Display: Single File View */
    $handler = $view->new_display('block', 'Single File View', 'block');

Now in your main view (where you are showing submissions). Add a new relationship for Webform submissions: Data. You'll need to set the nid for the webform here and select the image component.
Add new field to the view submission data: Value (raw). This will give you the file_id for the associated file. Exclude it from display.
Add another field Global: View. Select the view you imported and the block display. In contextual filter set [!data] from replacement patterns. It was the raw value of the field which you excluded from the display. And Here you go, save the view and rock :). Thanks for asking such good question. Still if you face any problem during this tutorial, ask me.


How to implement user hierarchy with different levels of roles under different branches, groups etc

Have you looked at Organic Groups.

Im using it for a similar use-case. I would allow you to create content types that can act as 'Departments' and add different roles within those.

You can have for example:

'department' content types with following roles: admin, supervisor
'branch' content type with completely different roles: it programmer, temp

It is very flexible and access control works with views as well. Nice tutorial can be found here.

If you opt to however to write your custom access control module, make sure that you read up on that here

Hope that helps.


When you add a logo this way, the entire image is a link back to the homepage.    The only answer I can think of is to place a link over the image.   using css the link will be

Float over the image using margin, position, etc
Text indent -9999px;
z-index higher than the logo img
pad the link to be the size of the image

I would probably custom code this in page.tpl.php, however it looks like you are looking for a non-custom code solution.   To do this create a new custom block, with the link being its content (remember to have a input filter that will take  HTML tags).   Move this block into header region.


I would suggest https://www.drupal.org/project/easychart. It has support for both Drupal 7 & 8. I don't have a lot of experience with the module itself but I have used the Javascript library (http://www.highcharts.com/products/highcharts) it uses and it is nice.


There is a setting for this.

Advanced > Exposed form > "Basic"

If the view is still on default, it will be set to Basic, click basic and change it to "Input Required"


How to convert location module data to geofield?

So, I haven't found a way to convert it, but I did do the following.

Update content with Addressfield and Geofield
Set geofield to code from addressfield
used views data export to export the data
used feeds to spit the data into addressfield.

This basically met my requirements, pretty laborious and had to do a lot of data integrity checking, but it did what I wanted it to do.

Just as a heads up, Addressfield is very specific with it's term, which are internationalized. The fields you have to map have different field names, and different requires fields for each country, so be cautious with the spelling and fulfilling all the required fields. You can use Feeds Tamper if it's all single-country data. Just for example here are a few:

Province = Administrative area
Street = Thoroughfare
City = Locality


Invoke custom JS function in AJAX callback?

Yes, it is.

Code sample:

$commands = array();
$commands[] = array(
    'command' => 'your_js_callback', // the name of your javascript callback
    'value1'  => 'My first value',
    'value2'  => 'My second value',
);

JS Code:

(function($, Drupal) {
    Drupal.ajax.prototype.commands.your_js_callback = function(ajax, response, status) {
        alert(response.value1);
        alert(response.value2);
    }
})(jQuery, Drupal);


Colorbox Slideshow not Working on Mobile Devices

The default behavior of Colorbox is to disable mobile functionality when the device's max width exceeds 480px. This functionality can be disabled with the Mobile detection option in Configuration > Media > Colorbox > Advanced settings.


How do I make ugly URLs such as "/index.php?main_page=about_us"?

My advice would be to keep Drupal's URL handling as is and simply configure a set of redirects with code 301 in your .htaccess.
That way your URLs will maintain their google ranking.

A useful quote:

  "Be aware that when moving a page from one URL to another, the search
  engines will take some time to discover the 301, recognize it, and
  credit the new page with the rankings and trust of its predecessor.
  This process can be lengthier if search engine spiders rarely visit
  the given web page, or if the new URL doesn't properly resolve."

This is an excerpt from https://moz.com/learn/seo/redirection, I would recommend reading that whole article, it's quite useful.

And an example of such a redirect:

RewriteCond %{QUERY_STRING}     ^main_page=about_us$     [NC]
RewriteRule ^.*$             /node/1234     [NC,L,R=301]

Hope this helps!


Commerce is protecting its own data integrity - if you were able to delete a product that's referenced by an order line, the next time you view the associated order something would break.

You'll need to remove the product from all associated orders before deleting it; I think the easiest way to do so would be to construct a View using Views Bulk Operations, select Line Items filtered by the relevant product ID, and bulk delete them. Obviously this will have an effect on existing orders, but since the product is attached to the line item by its ID, there isn't really an alternative (short of rewriting a bunch of stuff in Commerce).


How to debug a Commerce value in Rules if field is not exposed?

Looks like you did pretty much everything you can do to "debug" a rule that doesn't seem to do what you want, so I can't give you any other hints to the "how to debug"-part of your questions. But... I may have a solution to get around the actual problem ...
Have a look at the issue "After updating existing content" runs before content is saved, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which IMO is not a bug, simply how the Rules module  works ...).
A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rules Conditions and -Actions in a Rules Component, so that after your First Rules Action you "schedule the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs).
BTW, there are also scenarios where it is sufficient to just execute the Rules Component (containing the equivalent of your "subsequent Rules Action"), instead of using the Rules Scheduler to schedule its execution.
Update: as per geraldo's comment below this answer, the actual solution to the question here seems to be as described in comment nr 8 of support issue # 2502703, and which is like so:

The problem is line 317 in commerce_credits.rules.inc. Using count($credits->credits) always returns 1. Everything works fine when changing it to:
 if ($credits->credits >= $credit_number) {


Are you loading the node first? If you are not getting anything returned then it's probably because $node isn't set. Also is the 'News node' a node type of article?

I would start by trying to retrieve the node information first:

$node = node_load(arg(1));
var_dump($node);

Also I think your field_get_items is not working as your entity type is 'page' but you are inside a check for a node type of article try:

$news_header = field_get_items('node', $node, 'group_header');


A proper way IMO is a “Sponsor” Entity content type with the Fields you need, then create as many Sponsors as you need. Then use Views to create a Block display and select all published Sponsor content and output it as needed. Then place the block in the desired region. Later you may want to expand on sponsors and add more structured data around them, which is why you'd have a content type (or custom entity type) over just a single-use block type.


How to get a complete list of blocks that are active content on current page?

Follow the instruction to get the details of block for current page

In this template_preprocess_page function You can get a variable in that u have all region and it's block array
Using the above function we can get all the information of blocks note(if u want to see know the regions list see this function system_region_list


Ask services "Which user am I?", as defined by session id?

This service resource simply return an object representing the currently authenticated user:

/**
 * Implements hook_services_resources().
 */
function MYMODULE_services_resources() {
  $resources['MYMODULE'] = array(
    'actions' => array(
      'whoami' => array(
        'help' => 'Get an object referring to the currently authenticated user.',
        'callback' => '_MYMODULE_whoami_service_resource',
        'access callback' => 'services_access_menu'
      )
    )
  );

  return $resources;
}

/**
 * Resource callback
 */
function _MYMODULE_whoami_service_resource() {
  return $GLOBALS['user'];
}

Once enabled you should be able to access the resource at http://site.com/[endpoint]/MYMODULE/whoami.json.


How to translate the month name in a date select list field?

Enable the "Language" & "Interface Translation" modules.
Then download the translation .po file on https://localize.drupal.org and import it in /admin/config/regional/translate/import


First attempt to adding states to a custom Content type

There are two things to consider:

The name of the input element is visible in the HTML output of the page, and that could not match with the ID used for that form element from the form API. That happens with form elements created with the field API too.
I created a field_season field, which allows just a value to be select (which means it is rendered with radio buttons); the input element name that appears in the HTML output, which is the one jQuery sees, is field_season[und], not field_season.

If I change the field to allow three choices (which means the form field is rendered as checkboxes), the input element name changes to field_season[und][1], field_season[und][2], and field_season[und][3].

When you want to tell to Drupal to alter the state of a form element when a radio buttons are used, you should not use t(), and the string to use as value in the state is not the string that appears to the users, but the value assigned to the value attribute of the <input type="radio"> tag. For example, for the form element added from the following code, those values are 0, 1, and 2.

$form['registration_cancellation']['user_register'] = array(
  '#type' => 'radios',
  '#title' => t('Who can register accounts?'),
  '#default_value' => variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL),
  '#options' => array(
    USER_REGISTER_ADMINISTRATORS_ONLY => t('Administrators only'),
    USER_REGISTER_VISITORS => t('Visitors'),
    USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL => t('Visitors, but administrator approval is required'),
  ),
);

Since the input element name contains und, which is the string value for the LANGUAGE_NONE constant, I suspect the input element name could change basing on the language associated with the field, even if I suspect it would always be und, for radio buttons and checkboxes.

As side note, learningxm is correct when it says that you should use `:input[name=""]' since that is what the example in the drupal_process_states() page shows.

$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);
$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array('checked' => TRUE),
    ),
  ),
);

As noted by Clive, you are overriding the form element added using the field API; to change the states associated with the form element, you should just use the following code.

$form['field_winter_sports']['#states'] = array(/** Add here your states. **/);

I assume field_winter_sports is the correct form element ID.

I would also investigate using hook_field_widget_form_alter(), which is the hook thought to alter the form elements used for a field.


Access argument string for all administrators to access menu

Defining your module in hook_menu is not enough. You need to define hook_permission() too. You can do something like this

function raffle_permission() {
   return array(
    'administer site configuration' => array(
      'title' => t('Administer Site Configuration'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}


How to use metatag:image_src to share images on Facebook using the Service links module?

Try the approach suggested in Comment nr 1 of Issue nr 2387519, which is like so:

Install module Metatag (easy to understand module). Use the module and make your configurations.
Clear the cache.
Go to https://developers.facebook.com/tools/debug/og/object and click the "Fetch new scrape information" button to ping/update your meta tags to Facebook server.


Increase max_input_vars in your PHP environment as Clive suggested in the comment.

Another indication of this problem is the form validate handler won't trigger either. Unless you have E_WARNING set in the php.ini error_reporting setting the form will silently fail and run the form hook again.


In which database table does the number views of a node get stored?

As well as statistics there is the aptly titled Node View Count module

https://www.drupal.org/project/nodeviewcount

It has a few advantages over the native stats module in the way it counts and also has views integration so you can get some nice tables up and going quickly.


How do I alter images being added via IMCE CKEditor plugin?

So, here is what I did, even if maybe its dirty.

Add a new module which attaches a custom library to forms:

function mymodule_form_alter(&$form, $form_state) {
  $form['#attached']['library'][] = 'mymodule/form';
}

In the mymodule.libraries.yml:

form:
  version: 1.x
  js:
    js/mymodule.js: {}
  dependencies:
    - core/ckeditor
    - ckeditor/drupal.ckeditor
    - imce/drupal.imce
    - imce/drupal.imce.ckeditor

And in the mymodule.js I pretty much just re-write the imce sendto function:

if (undefined !== CKEDITOR && CKEDITOR.imce.sendto) {
  CKEDITOR.imce.sendto = function (File, win) {
    var imce = win.imce;
    var editor = CKEDITOR.instances[imce.getQuery('ck_id')];
    if (editor) {
      var i;
      var text;
      var lines = [];
      var selection = imce.getSelection();
      var is_img = imce.getQuery('type') === 'image';
      for (i in selection) {
        if (!imce.owns(selection, i)) {
          continue;
        }
        File = selection[i];
        // Image
        if (is_img && File.width) {
          lines.push('');
        }
        // Link
        else {
          // Use the selected text/image for the first link
          text = !lines.length && CKEDITOR.imce.getSelectedHtml(editor) || File.formatName();
          lines.push('' + text + '');
        }
      }
      editor.insertHtml(lines.join('
'));
    }
    win.close();
  };
}

Hope this is helpful to somebody. And maybe there is another, better way of doing this - glad for any input!


Search Solr View with exposed filter fullsearch return no results

After several hours, I discovered that search_api_solr 8.x-3.7 was the issue. I downgraded using composer to the latest v2.7 and it works fine.


Ajax HTTP error occured. HTTP Result code: 200

You can't just add arbitrary HTML at the top of a module file - Drupal runs through a process to theme the page, and you need hook into that.

You have a couple of options:

Override html.tpl.php in your theme, and add the tag to the <head> section manually. This is probably the easiest way.
Use drupal_add_html_head() in your module, e.g.

$tag = $element = array(
  '#tag' => 'meta',
  '#attributes' => array(
    'http-equiv' => 'X-UA-Compatible',
    'content' => 'IE=edge',
  ),
);
drupal_add_html_head($tag, 'mymodule:ua_compatibility');

Make sure you pick an appropriate hook to do this in (preprocess_page, etc), don't just add it to the top of the file or it won't work.


Ajax returned values do not update when field value changes

Check for any errors in Firebug's console.
In Firebug's net tab, what is the value coming back from the XHR callback?

If the value coming back from the XHR is the old value, then your problem is on the server side. If the value coming back from the XHR is the new one, then your problem is on the client side (like JQuery not being able to find it's target element). Hope that helps.


How can I change the front-page title when front page is not /node?

You can use the Metatag module. It has a section for front page metatags, where you can set the title.


How can I add a class to #markup output?

You can do this...

$form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination, array('attributes' => array('class' => array('cancel')))),
    '#weight' => 20,
  );

The third argument on the 'link' function is for attributes and such...

l($text, $path, array $options = array())

Documentation: http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7


How to change default registration form?

In  Administration » Configuration » People » Account settings, uncheck the Require e-mail verification when a visitor creates an account. option. This will allow user to directly enter their password on the registration form.


Take all sites in a multisite environment offline at the same time

If you have drush installed you could use this snippet:

#!/bin/bash
sites[0] = "http://www1.example.com";
sites[1] = "http://www2.example.com";
sites[2] = "http://www3.example.com";

for site in $sites; do
  drush vset --always-set --uri=$site site_offline 1
done

I'm not an expert in sh scripting but something like that should work.


What have you already tried?
Having a look at the module JS, there is a function jquery_ajax_load_load(el, target, url). Have you tried calling it?

EDIT
To load block content you could either use another module specifically for it (search "drupal block ajax load") (ajax blocks) or you could create your own module that just returns block content when navigating to a url. This should be quite easy by implementing hook_menu and returning the value returned by block_load()


The Inline Entity Form pushed me in the right direction.

Here's what worked for me:

Install File Entity module. It will allow you to add fields to files, in my case a "Description" textarea field.
Install File Entity Inline module. It will allow you to optionally include some of the fields directly in the file upload widget.
Add a file field and on configuration page under "Inline fields" choose either "All available fields" or "Only selected fields".

That's it - hope this helps someone!


Run my JS after views slideshow has finished loading?

I faced the same issue many times (especially when I used lightbox2 module), you can use the theme_preprocess_views_view hook or one of Views template files and add the JS using drupal_add_js.

With your code

drupal_add_js('jQuery(window).bind("load resize orientationchange",function (e) {
//do something
});', 'inline');

Thanks :)


Try something like this:

$.ajax({
   url: Drupal.settings.property_check.base_url + '/search/property-by-address',
   type: 'POST',
   data: {
       'add1':'address line1',
       'add2':'address line2',
       'add3':'address line3'
   },
   headers:{
       'Content-Type': undefined,
   }
}).done(function(response) {
        console.log(response);
})

or

 var address = {'add1':'address line1','add2':'address line2','add3':'address line3'};

 $.ajax({
     url: Drupal.settings.property_check.base_url + '/search/property-by-address',
     type: 'POST',
     data: address,
     headers:{
         'Content-Type': undefined,
     }
 }).done(function(response) {
     console.log(response);
 })


How to change the order of content types

The function node_type_get_names() calls the utility function _node_types_build().  If you look at the source, there is a call to asort() at the bottom.

If you read the documentation for asort(), you will see that it isn't called with it's second parameter, $sort_flags.  This means that it will be called with the default, which is "normal" rules.  In this case, I am prety sure normal rules means ordering based on the value of the code point, which places the English alphabet first, then "specials".

To take your characters with diacriticals into account, you would have have a proper locale defined, and then call asort() with the SORT_LOCALE_STRING option.  For example,

$types = array('Émission', 'Page', 'Article');
print_r($types);

sort($types);
print_r($types);

setlocale(LC_ALL, 'fr');
sort($types, SORT_LOCALE_STRING);
print_r($types);

results in

Array
(
    [0] => Émission
    [1] => Page
    [2] => Article
)
Array
(
    [0] => Article
    [1] => Page
    [2] => Émission
)
Array
(
    [0] => Article
    [1] => Émission
    [2] => Page
)

That explains why the ordering isn't what you expect.  A quick look through the Drupal source only reveals a single call to setlocale(LC_ALL, 'C'); (it's in the bootstrap).  See https://stackoverflow.com/questions/5231620/what-does-set-localelc-ctype-c-actually-do for what this does.

All of this means that without doing a hook_menu_alter() on the 'admin/structure/types' to change the page callback to be your own, or to hook_pager_alter() the render array for the page, you can't change the ordering.

As a stupid American :) who doesn't really understand all of the implications of localization and internationalization, I cann't comment whether the Drupal behavior is by-design or is a bug.


Customise message notifications in Drupal 7

OG7 Uses the Rule module for sending email notifications. See admin/config/workflow/rules/reaction/manage/rules_og_group_content_notification


How do you get the current destination URL query parameter in Twig?

You can use path() function with '<current>' pseudo URI to generate current page relative URL.
For example:
{# in hard-coded path (bad practice) #}
<a href="/user/login?destination={{ path('<current>') }}" class="btn btn-sm btn-primary icon-before"> Sign-In

{# more proper twig-like way #}

You can try <a href="{{ path('user.login', {}, {'query': {'destination': path('<current>') }}) }}">logging in to see if you have access.

More about Drupal's twig built-in functions here: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/functions-in-twig-templates


Ajax callback called on textfield typing

here my solution:

first you've to create (or alter) a text field

$form['user_search'] = array(
  '#type' => 'textfield',
  '#title' => t('Search'),
  '#description' => t('Cool description'),
  '#ajax' => array(
    'callback' => 'MODULE_ajax_user_search',
    'wrapper' => 'user-search-replace',
    'event' => 'finished_input', // custom event called by js code
    'effect' => 'fade',
  ),
  '#attributes' => array(
    'class' => array(
      'delayed-search-submit' // custom class to attach behavior to
    ),
    'data-delay' => '300', // custom property to set submit delay
    //'data-event' => 'finished_input', // custom event name, default is "finished_input"
  ),
);

then you'll have to create some js code to attach to your form

(function($){
  $(function(){
    Drupal.behaviors.delayedSearchSubmit = {
      attach: function (context, settings) {
        $('input.delayed-search-submit').once('event', function (){
          var $self = $(this);
          var timeout = null;
          var delay = $self.data('delay');
          var triggerEvent = $self.data('event');
          if (!delay) {
            delay = 1000;
          }
          if (!triggerEvent) {
            triggerEvent = 'finished_input';
          }
          // Every time a keyup event is fired
          // timer is reset
          $self.bind('keyup', function(){
            clearTimeout(timeout);
            timeout = setTimeout(function(){
              $self.trigger(triggerEvent);
            }, delay);
          });
        });
      }
    }
  });
})(jQuery);

now attach js file to your form

drupal_add_js(drupal_get_path('module', 'MODULE') . '/js/MODULE.textsearch.js');


page tpl pattern for a page with contextual parameter

I write down my answer because maybe this help another guys in future,I found out that there is not related to url parameters,and it work according to current path, then accroding the tpl file name pattern accroding to the pattern ( page--path.tpl.php) the answer is
page--products.tpl.php and work for any address  according this pattern products/% .


Add multilingual support to Drupal 8 Hello World module

Drupal 8 has many improvements for interface, configuration and content translation. There are great series of articles from Gábor Hojtsy: Multilingual Drupal 8.

Let's make Hello World module settings from this article translatable.
Full module code is avalible here: https://github.com/kalabro/drupal-examples/tree/master/hello
This code was tested with core 8.x dev branch (ed8dfae 2014-05-19).

1. Preparing Drupal 8 installation

Enable “Language”, “Interface Translation” and “Configuration Translation” modules.
Configure multiple languages.
Place “Language switcher” block.
Check how “Configuration Translation” with Site information form.

2. “Hello World” module

Use Drupal 8: Hello, Configuration Management article as base for “Hello World” module.
This module provides static /hello page with hardcoded “'Hello, World!'” message in it. The message can be outputted in normal or upper case. There is a setting for message case:

Play with the code until it becomes yours.
hello.info.yml:

name: Hello
description: '"Hello World" module with config translation support.'
core: 8.x
type: module
configure: hello.settings_form

3. More complex settings

Let's make message on /hello page configurable (dynamic).
For this purpose we should update form and controller.

Add 'hello_message' textfield in 'buildForm' method:

$form['hello_message'] = array(
  '#type' => 'textfield',
  '#title' => t('Your "Hello World!" message'),
  '#default_value' => $config->get('hello_message'),
  '#required' => TRUE,
);

Update HelloController to take hello message from setting instead of hardcoding it:

$hello_message = $config->get('hello_message');

Check full code in repository: HelloConfigForm.php, HelloController.php and etc. Feel free to ask any questions.

4. Make settings translatable

Our setting 'Your "Hello World!" message' should be translatable.

First of all we have to add config schema. It is recommended to add schema for any modules with configuration.
hello.schema.yml:

hello.settings:
  type: mapping
  label: 'Hello World settings'
  mapping:
    case:
      type: integer
      label: 'Letter case of your "Hello World!" message'
      # translatable: true
    hello_message:
      type: text # translatable by default.
      label: 'Your "Hello World!" message'

Now Drupal knows what kind of data is stored in module config. Some of config data types are translatable by default (text, label, mail). You can also add translatable: true to settings manually (try to do it for “case” setting).

Add Configuration Translation support.
hello.config_translation.yml:

  hello:
    title: 'Hello World settings'
    base_route_name: hello.settings_form
    names:
      - 'hello.settings'

Just small YAML file and that's all.

To see “Translate settings” tab you need existing default local task (See hello.local_tasks.yml for an example. Note: because of a change in Drupal core, this file name is no longer correct. It should be hello.links.task.yml now.).

Only translatable settings are appeared.

P.S.: In Drupal 7 i18n_variable API is used for this task.


Okay, I found the answer. It was as simple as adding this to $variables:

$variables['#cache']['tags'] = $config->getCacheTags();

My question is basically a duplicate of this:

How do I avoid having to clear the cache when changing a module configuration parameter?


Views Conditional or Conditional Fields can help you reach your goal .

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

  Equal To
  Not Equal To
  Greater Than
  Less Than
  Empty
  Not Empty

  Views conditional allows you to output text based on the result of the condition.


Server side Drupal install as git local repo

Fair warning, I don't know Drupal, so it's possible you're describing a common workflow. All the same I know a thing or two about git, and what you describe is a bit backwards. The problem is here:

  The hosted Drupal install is my git's "local" repo.
  Make changes, commit
  Push to github

By treating your production environment, the hosted Drupal install, as your local repository, you basically circumvent the benefits of versioned deployment. If you break that local, you break the site. If you want to work on a test feature branch (maybe new content you're still creating), you have to expose it to the world. A more canonical approach might be:

Commit to the site locally (on your computer) as well as a clone on your hosted site. Use github to push and pull between them. The Drupal docs have a solid example of this.
Commit to the site locally (on your computer), and use a post-receive hook to deploy the Drupal site, if your hosting provider supports git installation. This is a common setup in web application deployment.

In either case, note that you want a truly local copy, some place to experiment around, rather than the live website.


How to add contact us form in to front-page?

You can use Contact Form Blocks module, in case if you want
to use the core contact form.
Alternatively, you can create your contact form using Webform module which supports embedding the form
in a block, which you can then display wherever you want.
Also, you can display your existing contact form in a custom block,
writing a custom module. In that case, you need to implement 2 hooks:

hook_block_info
hook_block_view

and then use the function drupal_get_form to retrieve the form for
rendering. (See this for some more info)


File upload hook - how to integrate existing file manipulation code into Drupal

Create a content type with a file field to upload the mp3 file.
Create a custom module and implement hook_node_presave. There you can do whatever you want with your node before it gets saved.
For the file handling have a look at File interface.


how to add a "add user" tab to admin/people

I think what you're asking is the same as this.  Apologies if not.

Here I've added a menu item that links out to another page.  So you should be able to change the links to your needs.  For this I created a module 'taskmenuextras'

    **
* Implementation of hook_menu_alter
*/
function taskmenuextras_menu_alter(&$items) {
    $items['user/%user/featuredjobs'] = array(
        'title' => t('Featured Jobs'),
        'page callback' => 'taskmenuextras_redirect_nodequeue',
        'access callback' => 'taskmenuextras_user_has_role',
        'access arguments' => array(1, array('admin')),
        'type' => MENU_LOCAL_TASK,
        'weight'  => 0,
        );

    return $items;
}

function taskmenuextras_redirect_nodequeue() {
  drupal_goto('admin/structure/nodequeue/featured_jobs/view/1');
}

function taskmenuextras_user_has_role($user, $roles = array()) {
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}


Query to include if condition in addField

You can add an expression:

...
$query->addExpression("IF(N_lan.translate = 1, 'Outdated', 'New')", 'lan_translated');
....


Where are the database username and password stored?

The settings are stored in sites/default/settings.php. That is indeed the only file with that information and it is sufficient that you change the username and the password in that file.


When your visitor send the form, Drupal process the input, executing the validate and submit handlers (you have only provided your submit handler).

Once handlers are executed, Drupal needs to send a page to the user (the answer), so, if no redirection is made (in $form_state['redirect']), Drupal renders the content for the current URL, so Drupal renders your form again (because is a new HTTP petition, there's no memory of past petitions).

You must do something in the submit handler to let Drupal know your visitor can see the protected content.

For example, you can set a flag in the $_SESSION data. Then, in the entry_handler check for that value: if it's there the content is rendered, if not then the form is rendered.

Something like this (I've also divided your submit handler into validate and submit handlers):

function entry_daily_code_validate($form, &$form_state) {
    if (isset($form_state['values']['code']) && $form_state['values'] != "1234") {
   form_set_error('code', 'Invalid code!');
}

function entry_daily_code_submit($form, &$form_state) {
  $_SESSION['code_validated'] = TRUE;
}

function entry_handler() {
  if ($_SESSION['code_validated' == TRUE) {
    return 'Arbitrary content';
  }
  else {
    return drupal_get_form('entry_daily_code');
  }
}

If your visitors are registered users you can edit the user account or whatever merthod you like. Remember that session data can be lost.


Is it possible to address a single item of a field collection in pathauto?

I managed it now like this in a custom module.
What I do is add a new argument to the system path, so
node/<nid> becomes node/<nid>/<slide_num>

Can it be made better?

/**
 * implements hook_pathauto_alias_alter()
 * alters the alias of a newly created slideshow node
 */
function coco_slideshow_pathauto_alias_alter(&$alias, &$context) {
        // print_r(array($alias, $context));
    if ($context['module'] == 'node' && $context['type'] == 'slideshow'
        && ($context['op'] == 'insert'
            || $context['op'] == 'update')
        ) {
            $node = $context['data']['node'];

            module_load_include('inc', 'pathauto');
            module_load_include('inc', 'path');

            // get default path alias from patterns
            // this will be start of url alias
            $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
            $path = pathauto_clean_alias(token_replace($pattern, array(
                'node' => $node,
            ), array(
                'sanitize' => false,
                'clear' => FALSE,
                'callback' => 'pathauto_clean_token_values',
                'language' => (object) array('language' => $node->language),
                'pathauto' => TRUE,
            )));

            $pages = field_get_items('node', $node, 'field_pages');
            if (!empty($pages)) {
                $slide_id = $pages[0]['value'];
                $slide = field_collection_item_load($slide_id);
                if (!empty($slide)) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    $headline_text = $headline[0]['safe_value'];
                    if (!empty($headline)) {
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");
                        // alias is replaced with new one
                        $alias = "{$path}-{$path_text}";
                    }
                }
            }
    }

}

/**
 * implements hook_node_insert()
 *
 * creates aliases for each slide in slideshow node type
 */
function coco_slideshow_node_insert($node) {
    if ($node->type == 'slideshow') {
        module_load_include('inc', 'pathauto');
        module_load_include('inc', 'path');

        $title = $node->title;
        $nid = $node->nid;

        // get default path alias from patterns
        // this will be start of url alias
        $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
        $path = pathauto_clean_alias(token_replace($pattern, array(
            'node' => $node,
        ), array(
            'sanitize' => TRUE,
            'clear' => TRUE,
            'callback' => 'pathauto_clean_token_values',
            'language' => (object) array('language' => $node->language),
            'pathauto' => TRUE,
        )));

        $pages = field_get_items('node', $node, 'field_pages');
        if (!empty($pages)) {
            $slides = field_collection_item_load_multiple($pages);
            if (!empty($slides)) {

                $i=0;
                foreach ($slides as $slide_id => $slide) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    if (!empty($headline)) {
                        $headline_text = $headline[0]['safe_value'];

                        // create clean string for pathauto for every single slide
                        // this will be second part of url alias
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");

                        // first slide should alias to node/<nid>
                        // not to node/<nid>/<slide_id>
                        // this is handled in hook_pathauto_alias_alter
                        if ($i > 0) {
                            $save = array(
                                'source' => "node/{$nid}/{$i}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            path_save($save);
                        }
                    }
                    $i++;
                }
            }
        }
    }
}

/**
 * implements hook_node_update
 */

function coco_slideshow_node_update($node) {
    if ($node->type == 'slideshow') {
        module_load_include('inc', 'pathauto');
        module_load_include('inc', 'path');

        $title = $node->title;
        $nid = $node->nid;

        // get default path alias from patterns
        // this will be start of url alias
        $pattern = pathauto_pattern_load_by_entity('node', $node->type, $node->language);
        $path = pathauto_clean_alias(token_replace($pattern, array(
            'node' => $node,
        ), array(
            'sanitize' => TRUE,
            'clear' => TRUE,
            'callback' => 'pathauto_clean_token_values',
            'language' => (object) array('language' => $node->language),
            'pathauto' => TRUE,
        )));

        $pages = field_get_items('node', $node, 'field_pages');
        if (!empty($pages)) {
            $slides = field_collection_item_load_multiple($pages);
            if (!empty($slides)) {

                $i=0;
                foreach ($slides as $slide_id => $slide) {
                    $headline = field_get_items('field_collection_item', $slide, 'field_slide_headline');
                    if (!empty($headline)) {
                        $headline_text = $headline[0]['safe_value'];

                        // create clean string for pathauto for every single slide
                        // this will be second part of url alias
                        $path_text = pathauto_cleanstring("{$headline_text} {$slide_id}");

                        // first slide should alias to node/<nid>
                        // not to node/<nid>/<slide_id>
                        // this is handled in hook_pathauto_alias_alter
                        if ($i == 0) {
                            $save = array(
                                'source' => "node/{$nid}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            $temp = drupal_get_path_alias("node/{$nid}", $node->language);
                            path_delete(array('alias' => $temp));
                            // print '<xmp>' . print_r($save,1). '</xmp>';
                            path_save($save);
                        } else {
                            $save = array(
                                'source' => "node/{$nid}/{$i}",
                                'alias' => "{$path}-{$path_text}",
                                'language' => $node->language,
                            );
                            path_delete(array('source' => "node/{$nid}/{$id}"));
                            path_save($save);
                        }
                    }
                    $i++;
                }
            }
        }
    }
}


I dont think this can be done but its not too hard to have an elegant solution anyway. This is probably pretty obvious to anyone whos used Context for a while but here it is:

Create a front page context that has every block except for the one thats hidden on mobiles. Then add another context that is front page and not mobile devices, and add the block.