Missing form state values after adding submit function

Entity forms usually run as first submit handler the entity builder functions. Then following submit handlers can get the processed field values directly from the form object entity:
$entity = $form_state->getFormObject()->getEntity();
$field_values = $entity->field_foo->getValue();


Display nodes under Parent Taxonomy in Views

I have managed to work this one out.

Apparently you can add a filter using two methods:

"Simple hierarchical select"
"Content: Has taxonomy terms (with depth; Simple hierarchical select)"

Select the second method Content: Has taxonomy terms (with depth; Simple hierarchical select) as the filter.

Then after selecting the filter, you then have the option to select which taxonomy term to use. After that just select Simple hierarchical select.

Next step was to just simply expose the filter to users, so they can manipulate it.


How to get available view modes per content type?

You can use following function to get this information

$view_mode_settings = field_view_mode_settings($entity_type, $bundle);

example:

$view_mode_settings = field_view_mode_settings('node', 'article');


creating multi-country website, where each country's site is multilingual

You need a mix of (at least) 3 modules to do this:

Domain : to create the 3 sites USA, Japan and France
Internationalization : to create the different languages
Domain locale : to enable languages per Domain


Drupal_get_title() but for another field by name?

Maybe print $content['field_MACHINE_NAME']['und'][0][taxonomy_term]->name;? That should print the field without the HTML

If you want the HTML, trying using print render($content['field_review_nationality'][0]);

Source


How can i add a property(uuid) to existing custom entity base_table?

Found a workaround for this:
Step 1: Add uuid to entity keys in annotation.
Step 2: Add custom storage handler in annotation.
Step 3: Create the custom storage handler class extending SqlContentEntityStorage with getCustomTableMapping overridden:
/**
 * Use AddUuidTablemaaping to support adding uuid to base table.
 */
public function getCustomTableMapping(ContentEntityTypeInterface $entity_type, array $storage_definitions, $prefix = '') {
  $prefix = $prefix ?: ($this->temporary ? 'tmp_' : '');
  return AddUuidTableMapping::create($entity_type, $storage_definitions, $prefix);
}

Step 4: Create AddUuidTableMapping extending DefaultTableMapping and override create method.
public static function create(ContentEntityTypeInterface $entity_type, array $storage_definitions, $prefix = '') {
  $table_mapping = new static($entity_type, $storage_definitions, $prefix);

  $revisionable = $entity_type->isRevisionable();
  $translatable = $entity_type->isTranslatable();

  $id_key = $entity_type->getKey('id');
  $revision_key = $entity_type->getKey('revision');
  $bundle_key = $entity_type->getKey('bundle');
  $uuid_key = $entity_type->getKey('uuid');
  $langcode_key = $entity_type->getKey('langcode');

+ // The Magic, without this uuid will be added to dataTable if such exists.
+ if (array_key_exists('uuid', $storage_definitions)) {
+   $uuid_key = 'uuid';
+ }
+ // end Magic.

  $shared_table_definitions = array_filter($storage_definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
    return $table_mapping->allowsSharedTableStorage($definition);
  });

  $key_fields = array_values(
    array_filter(
      [$id_key, $revision_key, $bundle_key, $uuid_key, $langcode_key]
    )
  );

  $all_fields = array_keys($shared_table_definitions);
  $revisionable_fields = array_keys(array_filter($shared_table_definitions, function (FieldStorageDefinitionInterface $definition) {
    return $definition->isRevisionable();
  }));
  // Make sure the key fields come first in the list of fields.
  $all_fields = array_merge($key_fields, array_diff($all_fields, $key_fields));

  ...
}

Step 5: Create the field storage definition in post update hook:
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();

/** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
$field_storage_definition = BaseFieldDefinition::create('uuid')
  ->setLabel(new TranslatableMarkup('UUID'))
  ->setReadOnly(TRUE);

$definition_update_manager->installFieldStorageDefinition('uuid', $entity_type_id, 'my_custom_module', $field_storage_definition);

Step 6: Set uuid values for existing entities in baseTable:
$rows = $db_connection->select($entity_type_id, 'e')
  ->fields('e', ['id'])
  ->isNull('uuid')
  ->execute()
  ->fetchAll();

foreach ($rows as $row) {
  $db_connection->update($entity_type_id)
    ->fields(['uuid' => \Drupal::service('uuid')->generate()])
    ->condition('id', $row->id)
    ->execute();
}

Step 7: Update entity type and field storage schema:
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();

$e = $definition_update_manager->getEntityType($entity_type_id);
$keys = $e->getKeys();
$keys['uuid'] = 'uuid';
$e->set('entity_keys', $keys);

$definition_update_manager->updateEntityType($e);
$field_storage_definition = $definition_update_manager->getFieldStorageDefinition('uuid', $entity_type_id);
$definition_update_manager->updateFieldStorageDefinition($field_storage_definition);

This last step will update the entity type definition in db + make uuid field not_null in in baseTable.
Done.
Alternate solution is to use $definition_update_manager->updateFieldableEntityType, but will require overriding storage_schema handler(assuming there are existing entities) for the entity type as it forces not_null for entity keys by default.


How do I provide a page manager page override for my custom entities using ctools plugins

We can achieve this quite easily by using node_view as a guide. First though you must implement hook_ctools_plugin_directory() in your module file to register the ctools plugins:

/**
 * Implements hook_ctools_plugin_directory().
 */
function my_entity_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner == 'page_manager' || $owner == 'ctools' || $owner == 'panels') {
    switch ($plugin_type) {
      case 'tasks':
      case 'content_types':
          return 'plugins/' . $plugin_type;
      break;
    }
  }
}

This tells ctools that we are implementing plugins under the plugins directory inside our module folder and the plugins will be in their own directories. Since I am only implementing "tasks" I want to only return for that plugin type. The "task" plugin type is what we will use to implement our custom entity view.

After implementing this we just have to create the .inc file to implement our task. The file must be named name_of_plugin.inc, so for this we will use "my_entity_view.inc"

And here's the code for that, note that function names are made up of the following keys: module_name_plugin_name_hook(). I found it quite easy to follow this code, the hook_my_entity_task_tasks() is what all the other callbacks hang off. After implementing this, clear cache and your override should appear in /admin/structure/pages

<?php

/**
 * @file
 * Handle the 'my_entity view' override task.
 *
 * This plugin overrides my_entity/%my_entity and reroutes it to the page manager, where
 * a list of tasks can be used to service this request based upon criteria
 * supplied by access plugins.
 */

/**
 * Specialized implementation of hook_my_entity_task_tasks(). See api-task.html for
 * more information.
 */
function my_entity_my_entity_view_page_manager_tasks() {
  return array(
    // This is a 'page' task and will fall under the page admin UI
    'task type' => 'page',

    'title' => t('my_entity template'),

    'admin title' => t('my_entity template'),
    'admin description' => t('When enabled, this overrides the default Drupal behavior for displaying my_entitys at my_entity/%my_entity. If you add variants, you may use selection criteria such as my_entity type or language or user access to provide different views of my_entitys. If no variant is selected, the default Drupal my_entity view will be used. This page only affects my_entitys viewed as pages, it will not affect my_entitys viewed in lists or at other locations. Also please note that if you are using pathauto, aliases may make a my_entity to be somewhere else, but as far as Drupal is concerned, they are still at my_entity/%my_entity.'),
    'admin path' => 'my_entity/%my_entity',

    // Menu hooks so that we can alter the my_entity/%my_entity menu entry to point to us.
    'hook menu' => 'my_entity_my_entity_view_menu',
    'hook menu alter' => 'my_entity_my_entity_view_menu_alter',

    // This is task uses 'context' handlers and must implement these to give the
    // handler data it needs.
    'handler type' => 'context',
    'get arguments' => 'my_entity_my_entity_view_get_arguments',
    'get context placeholders' => 'my_entity_my_entity_view_get_contexts',

    // Allow this to be enabled or disabled:
    'disabled' => variable_get('my_entity_my_entity_view_disabled', TRUE),
    'enable callback' => 'my_entity_my_entity_view_enable',
    'access callback' => 'my_entity_my_entity_view_access_check',
  );
}

/**
 * Callback defined by my_entity_my_entity_view_my_entity_tasks().
 *
 * Alter the my_entity view input so that my_entity view comes to us rather than the
 * normal my_entity view process.
 */
function my_entity_my_entity_view_menu_alter(&$items, $task) {
  if (variable_get('my_entity_my_entity_view_disabled', TRUE)) {
    return;
  }

  // Override the my_entity view handler for our purpose.
  $callback = $items['my_entity/%my_entity']['page callback'];
  if ($callback == 'my_entity_page_view' || variable_get('my_entity_override_anyway', FALSE)) {
    $items['my_entity/%my_entity']['page callback'] = 'my_entity_my_entity_view_page';
    $items['my_entity/%my_entity']['file path'] = $task['path'];
    $items['my_entity/%my_entity']['file'] = $task['file'];
  }
  else {
    // automatically disable this task if it cannot be enabled.
    variable_set('my_entity_my_entity_view_disabled', TRUE);
    if (!empty($GLOBALS['my_entity_enabling_my_entity_view'])) {
      drupal_set_message(t('Page manager module is unable to enable my_entity/%my_entity because some other module already has overridden with %callback.', array('%callback' => $callback)), 'error');
    }
  }

  // @todo override my_entity revision handler as well?
}

/**
 * Entry point for our overridden my_entity view.
 *
 * This function asks its assigned handlers who, if anyone, would like
 * to run with it. If no one does, it passes through to Drupal core's
 * my_entity view, which is my_entity_page_view().
 */
function my_entity_my_entity_view_page($my_entity) {
  // Load my task plugin
  $task = page_manager_get_task('my_entity_view');

  // Load the my_entity into a context.
  ctools_include('context');
  ctools_include('context-task-handler');

  // We need to mimic Drupal's behavior of setting the my_entity title here.
  drupal_set_title($my_entity->label);
  $uri = entity_uri('my_entity', $my_entity);
  // Set the my_entity path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  $contexts = ctools_context_handler_get_task_contexts($task, '', array($my_entity));

  $output = ctools_context_handler_render($task, '', $contexts, array($my_entity->id));
  if ($output != FALSE) {
    //my_entity_tag_new($my_entity);
    return $output;
  }

  $function = 'my_entity_page_view';
  foreach (module_implements('my_entity_override') as $module) {
    $call = $module . '_my_entity_override';
    if (($rc = $call('my_entity_view')) && function_exists($rc)) {
      $function = $rc;
      break;
    }
  }

  // Otherwise, fall back.
  return $function($my_entity);
}

/**
 * Callback to get arguments provided by this task handler.
 *
 * Since this is the my_entity view and there is no UI on the arguments, we
 * create dummy arguments that contain the needed data.
 */
function my_entity_my_entity_view_get_arguments($task, $subtask_id) {
  return array(
    array(
      'keyword' => 'my_entity',
      'identifier' => t('my_entity being viewed'),
      'id' => 1,
      'name' => 'entity_id:my_entity',
      'settings' => array(),
    ),
  );
}

/**
 * Callback to get context placeholders provided by this handler.
 */
function my_entity_my_entity_view_get_contexts($task, $subtask_id) {
  return ctools_context_get_placeholders_from_argument(my_entity_my_entity_view_get_arguments($task, $subtask_id));
}

/**
 * Callback to enable/disable the page from the UI.
 */
function my_entity_my_entity_view_enable($cache, $status) {
  variable_set('my_entity_my_entity_view_disabled', $status);

  // Set a global flag so that the menu routine knows it needs
  // to set a message if enabling cannot be done.
  if (!$status) {
    $GLOBALS['my_entity_enabling_my_entity_view'] = TRUE;
  }
}

/**
 * Callback to determine if a page is accessible.
 *
 * @param $task
 *   The task plugin.
 * @param $subtask_id
 *   The subtask id
 * @param $contexts
 *   The contexts loaded for the task.
 * @return
 *   TRUE if the current user can access the page.
 */
function my_entity_my_entity_view_access_check($task, $subtask_id, $contexts) {
  $context = reset($contexts);
  return my_entity_access('view', $context->data);
}


Is there an accordion-style menu module?

DHTML Menu is great and it should work for what you need. I haven't used the 7.x version yet but they have a stable release. Here is an excerpt about it from the module's project page:

... uses Javascript to reduce the number of page loads when using nested menus; this is particularly useful with Drupal's administration system.
Ordinarily in Drupal, in order to see the sub-items in a menu, you need to click the link of this item and wait for a full page load. After enabling DHTML Menu, clicking a menu link once will expand it to reveal its sub-items without reloading the page. A double-click on the item will load the page normally. Additionally, a cookie stores which menus are open and which are closed, so that the state of the menus remain consistent as you navigate around the site.


This did the trick.

function xyz_user_presave(&$edit, $account, $category) {
  if (!empty($edit['mail']) && (!empty($account->mail) && $account->mail != $edit['mail']) && !user_access('administer users') && !drupal_installation_attempted()) {
    $role_position = array_search('xyz', $account->roles);
    // Use !== or === here since $role_position may be zero or FALSE
    if ($role_position !== FALSE) {
      unset($account->roles[$role_position]);
      $edit['roles'] = $account->roles;
    }
  }
}

I still do not know what's wrong with the code in the initial post, but whatever...


How to render user profile edit form in block?

I would suggest creating a view that displays user content. You should be able to add any fields you want from the user profile to the view. Then add a new display to the view with the 'block' type.


How do I programmatically render a menu's label?

Here is the snippet to change the menu name:

 function example_preprocess_menu(&$variables) {
      $element = &$variables['items'];
      foreach ($element as &$item) {
        if ($item['original_link']->getMenuName() == 'menu-machine-name') {
        //For the menu label
       $menu = entity_load('menu', 'menu-machine-name');
          $menu_label = $menu->label();
          if ($item['title'] == 'Example menu') {
            $item['title'] = 'New menu name';
          }
        }
      }
    }


You need to use the metatag_context sub module of Metatag, which means you need the Context module.

I was thrown for a loop on this as well. It'll create a default Context for a few of these oddball situations. Your metatag information is then controlled through Context.

See source for export handling blog: http://cgit.drupalcode.org/metatag/tree/metatag_context/metatag_context.context.inc#n251


Check Login and display login page in views

In your view set the Access of the page display to role > authenticated user. This will present an Access Denied message to anonymous users.

You can then enable the Login Toboggan module and enable "Present login for on access denied (403)". After the user logs in, they will be taken back to the view page automatically.


Drupal installation not working/ what is .htaccess

in response to your "real" question, a quick search can broadly answer that, but basically it is configuration file to control access of locations on an Apache Web Server.


Is it possible to have a dynamic route as configure module page?

It is possible to use any route for the configure link, as long as all route parameters are satisfied (parameters can be specified via configure_parameters).

In the case of the above bug, the access check was failing, preventing the link from displaying.

The problem was solved in: ChecklistapiAccessCheck looks in the wrong place for 'checklist_id' and 'op'


Primary & Secondary links are the definition of the  hyperlinks often found in the main menu in Drupal 7

Menu System Documentation


Use BlockContent::getInstances

$blocks = $block_content->getInstances();

or the code of this method directly:

$blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties([
  'plugin' => 'block_content:' . $uuid,
]);


Check out theme_image():

foreach (array('width', 'height', 'alt', 'title') as $key) {
  if (isset($variables[$key])) {
    $attributes[$key] = $variables[$key];
  }
}
return '<img' . drupal_attributes($attributes) . ' />';

So you need to clean width and height as top level keys but also from the attributes array:

function mymodule_preprocess_image(&$variables) {
  unset(
    $variables['width'],
    $variables['height'],
    $variables['attributes']['width'],
    $variables['attributes']['height']
  );
}

And yes, in Drupal 7, Variable process functions can now be used for all theming hooks. Don't forget to clear your cache so the new preprocess function is picked up.


I guess the Parking slot 1, Parking slot 2, etc. are nodes or fieldable entities. Most likely those nodes (or entities) have a boolean field which indicates if the parking slot is reserved already. For the sake of this example,
I call it field_reserved.

In this case you need to implement in a custom module a hook_form_alter().
I am going to write a pseudo code.

function mymodule_form_alter($form, $form_state) {

  // Check if the form id is the id of your form.

  // Use entity query that selects the node ids  of the nodes that are reserved.

  //Store the result in some array (let's say reserved_slots array).

  // With a foreach loop, check each select option id against the reserved_slots array of ids.

  //If such option exists, unset it.
}

Hopefully this gives you some guidance.
If you need a complete snippet, you will have to provide more data about your setup, like machine name of the fields, etc.


Query and sort by field on entity referenced object

The answer by Clive is correct.
I  used this query for a project :

$query->sort('field_projets.entity.field_date_mise_en_prod', 'DESC');

'field_projets' is the field name of the entity reference field on my node.

And 'field_date_mise_en_prod' is the name of a date field belonging to the referenced entity .

You can also use this syntax on conditions.
Exemple :

$query->condition('field_tags.entity.name', 'cats');

You asking for a tag with the name 'cats'.


Undefined variable block...when trying to integrate a form into a block

In order for hook_block_view() to work properly you also need to implement hook_block_info(), which in your case would look something like this:

function ios_lang_checkbox_block_info() {
  return array(
    'ios_lang_checkbox' => array(
      'info' => t('Block Name'),
      'description' => t('Block description')
    )
  );
}

That will register a block called ios_lang_checkbox, which will become the $delta var when your implementation of hook_block_view() is invoked.

At the moment, when that function executes there's no $delta available (since one hasn't been defined), and hence $block is undefined when you return it. Usually one would write $block = array() at the start of the function to avoid this, but in your case that would actually just have masked the problem.

The signature for your form function is slightly wrong, that needs to be:

function ios_lang_checkbox_nameform($form, &$form_state) {

It won't actually affect anything on a form that simple, but it's a good practice to get into...eventually it will come back to bite you if you don't!

The other small issue is the name of the form function you're calling inside hook_block_view()...I suspect you mean it to be the same form that's available from the path defined in hook_menu(), in which case that line should be:

$block['content'] = drupal_get_form('ios_lang_checkbox_nameform');

Once you've made the changes, make sure to clear Drupal's caches...otherwise your new hook implementation won't get picked up.


Image field unlimited values doesn't save just the first image..the others disapear on save

Seems to be that is a bug from Drupal fixed in the last release (7.9) according the release note.


It was hard to find the information but I succeed:

Copy ckeditor.config.js from the ckeditor module ( sites/all/modules/contrib/ckeditor/ ) to your theme ( sites/all/themes/MYTHEME/ )
Edit the ckeditor profile configuration in Drupal ( admin/config/content/ckeditor/edit/Full ): in ADVANCE OPTION, set Load ckeditor.config.js from the theme path to YES
Modify the ckeditor.config.js from your theme to add your custom template file:

CKEDITOR.editorConfig = function(config) {

config.templates_files = [ Drupal.settings.basePath +   'sites/all/themes/MYTHEME/js/ckeditor.custom.templates.js' ];
//...continue the config file

Copy your image template to sites/all/themes/MYTHEME/ckeditor-tpl/
In your JS theme file ( sites/all/themes/MYTHEME/js/ ) create a file ckeditor.custom.templates.js as following:

CKEDITOR.addTemplates( 'default',
{
imagesPath: CKEDITOR_BASEPATH + '../../themes/boson/ckeditor-tpl/' ,
templates :
    [
        {
            title: 'My template',
            image: 'my-template.PNG',
            description: 'Your custom template.',
            html: 'Hello world!'
        },
    ]
});

it works well for me. Hope it will help someone.


How do I act after quantity change in cart?

You could use the Entity API type hooks (load, presave, update etc..) to act when the commerce_line_item is updated

e.g:

/**
 * Implements hook_entity_update
 */
function MYMODULE_entity_update($entity, $type){

  if($type == 'commerce_line_item'){
    // Do stuff with line item in $entity;
  }

}

You might have access to $entity->unchanged or similar in $entity which stores the entity content prior to the save. Useful for comparing quantity to see if it's changed!

dpm($entity); // for details.

You can also use hook_ENTITY_TYPE_update

/**
 * Implements hook_ENTITY_TYPE_update
 */
function MYMODULE_commerce_line_item_update($entity){

  dpm($entity);

}

The hooks for load, presave, insert, update and delete are available for all Commerce entity types.


How to get the active #comment-cid when a comment permalink is clicked?

Try to add a custom javascript file to in theme.info file

 jQuery(document).ready(function() {
    //get the current path
    var pathname = window.location.hash;
    jQuery(pathname).next().addClass('active-comment');
    //here add your custom animation
    jQuery('.active-comment').fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn().fadeOut().fadeIn();

});

here is a plugin to animate the background color of the wrapper :here

Hope this will Help You


Page Not Found for anonymous (clear cache fixes it)

Ask your sysadmin about the health and size of cache tables. Being logged in bypasses page cache. Clearing cache truncates them. Last time I've encountered similar effects, they were caused by a bad sector on server's HDD - when cache table grew enough to start using it, caches got all messed up. It was most visible with page cache.


Rules not marking all registrations to complete when commerce order is complete

Have you experienced the issue with the failed card? I run an event website with entity registration and commerce and we process an average of 20 registrations a day and haven't had that problem yet.

But if you want to be certain you could utilize hook_commerce_checkout_complete, look at the order payment details and check that the order has been marked paid successfully. If so, invoke the rule or use entity query to lookup all registrations related to the order_id and mark them complete.


As far as I understand your question,
after creating menu item entry within Views UI
you can go to chosen menu configuration (admin/structure/menu for D7) and set parent for your new entry as you would like.


There are visibility settings where, we can select which pages the block can be visible.
The same form has an underlying functionality to hide the block for the selected list or URLs.
Unfortunately, the same is not the case of Roles.
You can select which roles you want to display the block, but, you cannot select which Roles you want to hide the block.
Following code adds a Negate condition to Roles Visibility:
/* Negate the condition to decide visibility of which user roles to show/hide. */
function YOUR_MODULE_form_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['visibility']['user_role']['negate'] = [
        '#type' => 'radios',
        '#title' => '',
        '#default_value' => 0,
        '#options' => [
            t('Show for selected Roles'),
            t('Hide for selected Roles'),
        ],
    ];
}

This adds two radio buttons under the form: Roles.
Following is the screen shot for the same:

Reference:


Is Organic Groups 7.x ready for production?

I've used OG6 in the past and am starting to use OG7 now for a website.  I'd say in general, both with the 6 and 7 versions that the learning curve in figuring out how to use Organic Groups can be steep for a newbie, since it's a complicated module with a lot of features, and a lot of related, supporting modules like OG menu, OG Extras, etc.

Give yourself time to play with all of those.  Don't expect to setup your perfect site in a day if you've never used it before.  It may be that the 6 folks who reviewed the module on the site you referenced had such expectations.  Also, those are 6 reviews out of over 24,000 sites currently using OG.  :-)

My recommendation: do your own testing and make up your own mind before believing a review 100%.  Some of those reviews are probably quite valid, but OG is a useful module and may be able to do everything you want for your site.


How to delete a view programatically in D7?

Give a try to the following code to delete the view:

// Check the view id the one that you are looking for.
if ($view = views_get_view($name)) {
  // Delete the view if it is the one that you are looking for.
  views_delete_view($view);
}


Views 3 (D7) Attaching custom markup to individual view results

Try hook_views_pre_render() see docs and drupal_add_js().

Add the correct JS using drupal_add_js by injecting the JS file using hook_views_pre_render() to fire on the correct view.
Your JS will have to understand the default views output to re-theme / alter HTML output accordingly. Firebug or Chrome Developer tools can help you with that.
you can use $view->attachment_after to attach like a custom blob of HTML like

 so you can muck with this div on your Ajax callback. You can add the view attachment in the view_pre_render


Able to use custom variables in page.html.twig but not in menu.html.twig

The menu theme is declared using the variables key (see doc).

That means that only the keys present in the variables array can be passed to the template.

Any custom variable needs to be first added using hook_theme_registery_alter


is there anyway to populate nodes when type a custom content type value using node reference in drupal 7

You can select a View in Content Settings in "VIEWS - NODES THAT CAN BE REFERENCED".

Let that View return whatever field values you want to return.


You can add the element using the image theme hook:

$page['element_three'] = [
  '#theme' => 'image',
  '#uri' => $image_path,
  '#alt' => $title,
  '#title' => $title,
  '#width' => $width,
  '#height' => $height,
];


You can write this in javascript to avoid caching issues and use the users machine time.

https://drupal.org/project/timeago

http://momentjs.com/

http://timeago.yarp.com/

otherwise there is a patch here: https://drupal.org/node/2026545


Sharing settings.php isn't good practice at the best of times.

Instead, it would be better to make that file specific to your own machine, and exclude it from version control. Have the rest of your dev team do the same. Then the problem is mostly solved, and you'll find it impossible to accidentally overwrite a production site's settings.php as a bonus.

Regarding automatically updating when you change your password - I think you're out of luck.

The way drupal_http_request() uses the proxy vars means you need to provide URL, username and password in plaintext as variables (i.e. the $conf array). I may be wrong, but I don't think you can get at those system credentials through PHP. Perhaps there's an extension that provides it, but I haven't come across one before. I'm almost positive core PHP doesn't have anything useful anyway.


moving D8 from one sub-folder to another

I had to update the content links manually. I learned that for to create any link for the internal content i need to use relative links instead of an absolute link.

Thank You


Custom validation rules for content entity fields

list_string can have an allowed_values_callback instead of a list of allowed values, that allows you to return a dynamic list from that callback.

See callback_allowed_values_function(), which has pretty good documentation, that we've refined over multiple issues.

Make sure you're aware of the rules and limitations of what you can return.. for example that not passing an entity should always return all allowed values and passing one it can only limit those and not add more. And that returning new allowed values is not a problem, but not returning them anymore can be problematic as you might end up with data in your database that is no longer valid. The UI doesn't allow you to do that, for example.


How to prevent users from accessing content?

You want to uncheck the View published content permission for anonymous user. So yes you have found the right permission.


Mass image upload with Storage API and Services API

Still in early dev, but checkout  Storage API Populate:

  Storage API Populate provides a mechanism to move existing files
  within file/images fields into storage. The module requires the
  Storage API module.

  For a scenario where you have an existing site, without any Cloud/CDN
  support for assets and would like to use Storage API to manage the
  storage and serving of files.


Feeds Importer won't import autocomplete field

Found the bug... http://drupal.org/node/1426762


Is a node linked in any Panel (Drupal 7)?

You are looking for something along the lines of file_usage_list() I guess. I also assume that you are interested in the "Add content > Existing node" functionality of Panels.

You could implement your own function, with the following code:

function _panels_node_usage_list() {
  $result = db_query(
    "SELECT * FROM {panels_pane} WHERE type = 'node' AND subtype = 'node'"
  );
  $node_usage_list = array();
  foreach ($result as $pane) {
    $pane_configuration = unserialize($pane->configuration);
    $node_usage_list[$pane_configuration['nid']]++;
  }
  return $node_usage_list;
}

and then call this function from your own implementation of hook_node_access() where you can check if the nid of the node to be deleted is in the array returned by _panels_node_usage_list().

Good luck!


Programmatically creating a content type with file field in a custom module

This isn't so much an answer as it is an expansion on the previous answer.

I found these two links very helpful in figuring out what the system needs for custom fields to be added to your custom module node type.

Best: http://www.sitepoint.com/creating-a-new-drupal-node-type/

Good additional info: http://public-action.org/content/drupal-7-field-api-drupal-7-adding-custom-content-type-custom-fields-field-api

The problem I had was that these (and every other example I can find online) are very specific examples without enough documentation to help me figure out a solution to my own usage case.

What helped was tenken's comment to the OP about using the Features module to get the arrays for the custom fields.

So I downloaded the Features module and enabled it: https://drupal.org/project/features

Then I created the fields on my content type, using the admin interface in Drupal like you normally would, that I wanted the module to create. Then I browsed to Structure > Features > Create feature and put in a bogus name (I used "test") for the feature and then over in the components area click on "Field Instances" and check the boxes for the custom fields. The fields are all named something like node-[your node type machine name]-[field name], so in my case since I wanted an image field it was node-novel_section-field_image.

After selecting the custom fields for my node type I then just clicked on "Download feature" and saved the .tar file to my desktop, opened it, opened the "test" folder then viewed the test.features.field_base.inc and test.features.field_instance.inc to get the arrays I needed for my fields.

Then I just used the structure outlined by that first link I posted and after that it worked perfectly. For me.

I could not find any documentation on the array structures needed for things like image fields and taxonomy reference fields and it seemed all other tutorials and help requests online are focused on specific things like text fields.

Hopefully anyone having the same trouble I was having will see this and be able to make their setup work using these examples and the Features module like I did.

Thanks to tenken for pointing out this functionality of the Features module, I'd never used it and didn't know it would do that.


Allow groups of users to edit a single Webform

If you can group those users in a role, you can use the Content access module to allow them to edit the webform.

Furthermore you can set content access settings per node, so you can limit them to be able to edit only that one webform.


Drush Feature Update removing t() and l() function usages

Isn't this a simple as the PHP code being executed? The original feature is created so it supports any language by translating text with the "t" function. However, when the feature is activated, just the text - the executed PHP code - is written to the database (for the given langauge), and you can't ever get back the original PHP code. A feature update will just return the string in the database.


Does Drupal 7 Entity Translation Translate?

You need to edit your fields and make them translatable.

EDIT:

Ah, misunderstanding. Entity translations provides a user interface that allows you to translate entities. It doesn't translate itself.

What you are looking for in that case is Translation Management Tools*. It integrates with content translation, entity translation and more and allows to send text to a translator and save the translation in the correct place. There is a large list of supported translators, including a simple export/import, translation agencies, a local translator and Microsoft Translator, which is a machine translator and probably what you are looking for.

It's goal is to facilitate the management of a multilingual site with overviews, bulk operations, configurable review processes and a flexible, extendable architecture. It is, however, a new and large project, currently only available as an alpha and not every subsystem is finished. Notably, Microsoft Translator is currently broken because they changed their API, see http://drupal.org/node/1574516.

*Disclaimer: I am the maintainer of that project.


You can use symlink for creating multiple urls you want. I try this and created multiple with pathauto too.


Add field to display in views using a custom table

For your custom table you need to add custom field handler for views.
Check out below link for example code.

https://gist.github.com/juampynr/5816530

Hope this will help.


How can nested subdirectories and symbolic links be used without conflict with a multi-site Drupal installation?

Are you using just one rewrite? I have this exact setup, and I take care of it with a separate rewrite for each sub-directory. If you just use the default index.php rewrite, the path gets rewritten back to the default, like drupal.drupalsite.com/index.php?q=/campus/news which is where the 404 comes from. I also use aliases in the server level config instead of symbolic links. It makes things cleaner. (Alias /campus/bus /var/www/html/whatever)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /campus/bus/
RewriteRule ^(.)$ /campus/bus/?q=$1  [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /campus/news/
RewriteRule ^(.)$ /campus/news/?q=$1  [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /
RewriteRule ^(.*)$ ?q=$1  [L,QSA]


remove the

/* position: absolute; */
/* bottom: 0; */
/* right: 0; */

from .flex-direction-nav


Is it acceptable to change the vid column of a term programmatically in the database?

Database
It's possible to do a lot of things in Drupal simply by making SQL queries, either through Drupal or externally. Generally, you never want to take this approach. There are some cases where it can work just fine, but most of the time there is no reason to do it this way.
API
Drupal has a rich API, this is true for Drupal 6, 7 and 8, as they has always been a key feature in Drupal. In your concreate example, you could use taxonomy_term_load and taxonomy_term_save to facilitate an update of a term. Doing it this way, you can edit any data part including the vid. Just because you do it with API's doing forbidden things wont just automatically work, but the chance of things going well is drastically improved.
In this concrete example the API doesn't do anything that is necessarily needed. It sets some internal data on the term and invoke hooks letter module know that is has been updated.
You should note that things can break, if the term you want to change is part of a hierarchy. Things can also break for nodes referencing the term, if the field is not allowed to reference terms in the new vocabulary.
Migration
Migration of data is the bullet proof solution, and unless you have a huge data set, it can be developed and executed pretty easily. The idea is to create a new term and migrate the content you want to migrate and then delete the old term. As an update hook, sample code could look like this:
/**
 * Put in modules .install file, replace xxxx with 7000 or higher
 */
function MODULE_NAME_update_XXXX(&$sandbox) {
  $term = taxonomy_term_load(CONSTANT_WITH_TID);
  $new_term = clone $term;
  unset($new_term->tid);
  unset($new_term->tid);
  $new_term->vid = CONSTANT_WITH_VID;
  taxonomy_term_save($term);
  // Find all nodes we want to update and update them.
  // If there is a lot of nodes, can use $sandbox to make this a batch job.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->fieldCondition('field_which_is_term_reference', 'tid', $term->tid);
  $result = $query->execute();
  foreach (node_load_multiple(array_keys($result['node'])) as $node) {
    $node->field_which_is_term_reference[LANGUAGE_NONE][0]['tid'] = $term->tid;
    node_save($node);
  }
  // Migration all done - delete the old term.
  taxonomy_term_delete($term->tid);
}

Please note that the above code is pure example code, written by heart. Might have syntax error or other errors and makes a lot of assumptions. This is just to illustrate an idea and demonstrate that a migration might not be a big deal.


Can I get the raw value of arbitrary tokens?

Garrett,

From your question I can see that you have appended ":raw" to the list of tokens that you are using.

I think that will be "-raw" instead of ":raw". As example, [user:name-raw] instead of [user:name:raw].


Whats causing Drupal to freeze when creating/editing a mini-panel?

By the description of your problem, it seems to being caused by a Javascript error.

Try to check with Chrome DevTools, Firebug or the debug tool of your preference on the browser, go to "Console" tab and look for Javascripts errors or maybe on the "Network" panel to check for XHR (ajax) problems.


Figured it out, you just add "shareThis" to your content type you want this to show in a slide show, and since we are showing the whole content it will show with the rest of the node.


node API hook that can be used to alter fields before loaded by Views?

There are multiple ways in which this could be achieved:

Override the field itself in your theme with template_preprocess_field().
If the customization is more towards the markup, you can directly achieve that by overriding the field template.
Or you could just write a field formatter for this field, and select it in the field settings of the views and the view-mode (manage display) of your content type.


This is not supported and could be a security issue because it would allow people to use tokens to pry into information available in other entities.


where is the source code for "Powered by Drupal"

Here's the API documentation for all your needs:

theme_system_powered_by()
system_block_info()
system_block_view()

Also, please note that modifying the output of theme_system_powered_by() should be done using a theme hook from your theme code. If you wonder how to achieve this, this might be a relevant article for you.


Why does the download page recommend the previous version?

Yes, Drupal is under development. See
 http://drupal.org/core/release-cycle

API freeze was in July, now API completion phase.


Is there some way to arbitrarily set the active trail?

If you're using Drupal 7.9 or later you can use the menu_tree_set_path() function, e.g.

menu_tree_set_path('main-menu', 'performances');


Filter for all terms in a "dynamic vocabulary"

I believe contextual filters under the advanced options in your view is what you are looking for. You can add the term reference field there and then dynamically filter the view from the url with either the term name or term id or both depending on the options you select.


I'm assuming that you're using Drupal 7. Many ways to do this, one way is to implement hook_node_view


Finally I have solved the issue thanks to the comments I received on my question. Here is the solution I found:

namespace Drupal\my_custom_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {
    if ($this->account->isAnonymous()
      && \Drupal::service('path.current')->getPath() != '/cas'
      && \Drupal::service('path.current')->getPath() != '/casservice') {
      $response = new RedirectResponse('/cas', 301);
      $event->setResponse($response);
    }
    return;
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAuthStatus', 100];
    return $events;
  }

}

In short, the issue was related with the path checking and the RedirectResponse object management.


Try this :

function changeme_mail($key, &$message, $params) {
  switch ($key) {
    case 'information':
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
    break;
    }
}

$message['body'] is supposed to be an array as defined here so I changed $message['body'] to $message['body'][]


How to enable Node editing in full mode?

Yes there is a module which can enable this functionality - Editablefields.

Module page says itself --

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).

I have used this module for edit fields at views not at node, but I am sure you can achieve your requirement.


That is because it is a block provided by a view.
Look at the block edit page url, it usually gives you a hint wich module provides the block: "admin/structure/block/manage/views/what_we_offer-block"...


How to change the default mail template for subscriptions module

There is no template but you can solve this by adding the mail_edit module to your site. Here's the notes from the documentation:

http://drupal.org/node/344030#Configuration

(scroll down to "Mail Templates")

  If you have installed and enabled the mail_edit module then you can go
  to admin/build/mail_edit to edit the mail templates.


Impossible to create content or edit image styles after Backup/Restore

How To Update Drupal Core

Follow these instructions:

Make a backup of your Drupal instance (database).
Download the latest release of your current Drupal version.
Extract the [tar ball or zip] Drupal package.
Set your site on maintenance mode
Delete all the files & folders inside your original Drupal instance
except for /sites and its sub-folders. This assumes that all of your
custom work - including themes - is in the recommended spot - the
/sites folder tree. If you have made custom changes elsewhere you
will need to either preserve them or plan to replace them later.
Copy all the folders and files except /sites from inside the
extracted Drupal package [tar ball or zip package] into your
original Drupal instance location.
Some updates do not include changes to setting.php and some do. See
There is a way - Comment below for more on this. If the update
release includes changes to settings.php you will need to replace
your old settings.php in .../sites/default/ with the new one, and
then edit the site-specific entries (eg database name, user, and
password) in the setting file.
If you have modified files such as .htaccess or robots.txt re-apply
those changes to the new files.
If you have a favicon.ico file that was deleted replace it too
Login to your site as administrator or as user no 1
Run update.php by navigating to
 http://...yourdrupalsitename/update.php and follow the process to
 update your Drupal instance
Disable maintenance mode


Show video thumbnail and download link in view

Add field_file_vid again, check mark exclude from display and this time don't use URL to File as formatter, use a different formatter that renders the video.

Rearrange the fields

so that this new field is above the original field.

Now in your original field's rewrite results, use this as your 3rd line:

{{ field_file_vid_1 }}


Custom Entity: define a view in entity reference field

The handler settings are part of the base field itself, rather than being a setting for the form display.

This should work:

$fields['user'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('User account'))
  ->setDescription(t('The user account this profile is connected to'))
  ->setSetting('target_type','user')
  ->setSetting('handler', 'views')
  ->setSetting('handler_settings', [
    'view_name' => 'users_without_profile',
    'display_name' => 'entity_reference_1',
    'arguments' => [],
  ])
  ...


Views PHP: how to get the `end-date` value within `Global(PHP)`?

$time = $timeEntry['raw']['value'] == Start Date

$time = $timeEntry['raw']['value2']== End Date


Remove entity type without module uninstall

The argument for entityDefinitionUpdateManager->uninstallEntityType() is an EntityTypeInterface, not a string.

Drupal stores the last known state of an entity type, you can get it like this:

$entity_update_manager = \Drupal::entityDefinitionUpdateManager();
$entity_type = $entity_update_manager->getEntityType('your_entity_type_id');
$entity_update_manager->uninstallEntityType($entity_type);

Note that this is using the enitty definitions update manager to get the entity type definition, not the runtime entity type manager.

The field definitions are also read from state and both the entity type and field definitions are purged afterwards.


should be:
InsertController::addMovie

Needs a double-colon.
Yours is single.


Filtering PrivateMsg types by "sent" or "inbox"

From the page that you linked to:

// Replace 'inbox' with 'sent' to display sent messages or 'list' to display all messages.
$query = _privatemsg_assemble_query('list', $user, 'inbox');

Note that the privatemsg_filter module needs to be enabled for that to work.


Customize Search Terms search criteria of the view

Select Containg any word operator in expose filter settings of Title field.


Photos in views taking a long time to load

If you can see the images loading one by one then this doesn't have anything to do with the View rendering slowly.

Slow running PHP generally means you have to wait longer before anything displays, not that individual parts of the page render slowly.

Slow loading images means the file size is large or you have a bad internet connection between you and the server.

You've mentioned that you're using CCK so I assume you're using Drupal 6.

Might I recommend using imagecache to pre-process the images to be scaled on the server to the right dimensions before they are sent to the user.

http://drupal.org/project/imagecache

Instead of printing the image tag directly, setup an imagecache preset in Drupal then you call theme() to generate the image markup.

Example:

<?php
  print theme('imagecache', 'mypresetname', 'path/to/file.jpg');
?>

Documentation on the theme function can be found here: http://drupalcontrib.org/api/drupal/contributions!imagecache!imagecache.module/function/theme_imagecache/6


How to redirect to a specifi page of a view?

The solution has two parts:
1. The button that takes to my form in 'Add' mode was coded this way: Ajouter (/services being the first tab I mentioned).
So I removed the ?destination=services
2. Looking at the 'Routes info' provided by Devel, I got that:

So i changed my code to $form_state->setRedirect('view.services.page_2', ['arg_0' => $iSeliste]);  (thanks to the last comment of this page)

And now it works!


Using db_select to only get the latest nodes with a certain field value

You might try something like :

$query = db_select('node', 'n');
$query->join('content_type_nodetype', 'ct', 'ct.nid = n.nid');
$query->groupBy('field_someid_value');
$query->addExpression('MAX(n.nid)', 'nid');

The 'nid' order must follow the 'created' order so you won't need to order the results. Just taking the biggest nid for each field_someid_value should do the job.


Part 1 - Understanding the problem

I'm not sure if you won't run into other problems in trying to get this to work in D8 (as per the current status of the Rules module for D8), but IMO the first issue you need to resolve is that "...Cannot set a list with a non-array value ..." (as contained in your error message).

It seems to me that you should use something like what in D7 is called "List contains item" as your Rules Condition. For way more details on that, refer to the answer to the (D7 related) question about "Loop through all entities with rules".

Part 2 - More info that may help to get it to work

Your issue appears to be related to the (fixed) issue (= a task, not a bug ...), from Klausi, about "Support multiple contexts in the UI" which states:

  Currently we only use a simple textfield for contexts in conditions and actions. Conditions such as the UserHasRole condition have their Roles context defined as multiple, which means the user should specify more than one value in a text field. A default implementation could just display a textarea where one line is one item in the list.

The fix for this issue appears to be included in this pull request.

Disclaimer: I have not QA-reviewed this (yet) (but that's what I would go for to get it to work).


How to add extra data to a programmatically created node

I found this can easily be done using the Features module. Now i could create the the fields manually and then export them using features and copy the export to my custom module.


Select all nodes, where date is greater then current date and repeat event option is empty

Right now your rrule condition is a singleton of its "OR" group. You need to add all the other conditions to an "AND" group and place that group as a sibling to the rrule condition in the "OR" group.


You can set each content type to default to create a new revision; if you edit a content type you'll see something like this:

Select the 'Create new revision' checkbox and save the form; when you add/edit content of that type the 'Create new revision' option will be pre-selected.

As far as diffing revisions goes, you can install the Diff module:

  This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.


Media Gallery not using lightbox and required libraries are in place. What is wrong?

As Bala Varadarajan suggested. I gave sites/all/libraries/colorbox/ and all its contents full Read/Write permissions.

The lightbox is working now.


All links point to the old site after migration

For sites being localized, you have to edit every language:
/admin/config/regional/language
It's because there's a "domain" field that is left with the wrong URL in the database.
That solved my case of moving from subdomain beta.mysite.com to www.mysite.com


Views Filter Criteria "Now" not working on webform submitted data field:event date

I don't really understand the problem. When a date isn't a date anymore and you can use php you can just convert it back to a date.

You even almost use the correct function.

$submittedDate = $row>value_1;

$Cdate = date('Y-m-d');
$Sdate = date_format(date_create($submittedDate), 'Y-m-d');

if ($Sdate == $Cdate) {
    return TRUE;
}

Shouldn't that do the trick?


I ended up making some modifications to the Drupal CSV module (code). The module code demonstrates that you can stream information directly to the client with header() designations. From what I was able to find, you aren't able to use form headers within form callbacks. An alternative method involved passing information with sessioning to an empty page (that doesn't have header restrictions). This had several undesirable consequences:

1.) Session information is saved temporarily server-side, increases time to load to client due to having to write twice.

2.) Finite memory allotment for sessions.

The solution below does not have these limitations:

<?php

function test_download_form($form, &$form_state) {

  $form['form_wrapper'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['form_wrapper']['download_submit'] = array(
    '#type' => 'submit',
    '#value' => 'test download',
    '#name' => 'retrieve',
  );

  return $form;
}

function test_download_form_submit($form, &$form_state) {
  $characters = 'ACGT';
  $randomString = '';
  $n = 50000000;

  for ($i = 0; $i < $n; $i++) {
    $index = rand(0, strlen($characters) - 1);
    $randomString .= $characters[$index];
  }

  //https://git.drupalcode.org/project/csv/blob/7.x-1.x/csv.module
  drupal_add_http_header('Content-Type', 'text; charset=utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment; filename="test_header_method.txt"');
  $fp = fopen('php://output', 'w');
  fwrite($fp, $randomString);
  fclose($fp);
  drupal_exit();
}


Remove datatype attribute from meta about tag

Apparently the meta tag isn't the problem. The problem is the validation service and how you use it. After some digging I found this article. The author suggest using a different validation type namely: http://validator.w3.org/nu/ with the following preset set in the additional options: "HTML5 + SVG 1.1 + MathML 2.0 + RDFa 1.1 + Microdata". This will validate said meta tags without any errors.


how to theme the read more link using fields mode in views,

You should be making any theme changes in a sub theme, rather than editing the actual theme files. This is so all of your changes are not wiped out when an update is available for corporate clean.

Please read https://www.drupal.org/node/225125 for more information on sub theming.

As for the changes to be made to your stylesheet, open your style.css in an editor such as notepad++ and add the following lines (if align left is what you need)

.more-link {
  text-align:left;
}


Try this sandbox which reimplements Wishlists as orders. It won't work out of the box since it only hooks into the main add to cart form, so you'd need to add that in... but it's an order so you can theme it like a regular cart/order form.


How to translate taxonomy terms displayed via an exposed filter in views?

Editing the View, try to add a new Filter Criteria and look for one you want to translate. There should be a duplicate entry, but the second indicates: (translated). You should use add this (exposed) filter, and delete the other one.


As answered by @dicix, Drupal will not return the correct Cache-Control headers to Varnish without "Page Cache" being enabled in the Drupal Performance configuration.

The problem I ran into with having both the Drupal Page Cache and Varnish at the same time is that it potentially increases the delay before stale content is refreshed to a maximum of both TTLs. For example, having a max-age of 5min could result in the stale content sticking around and being served for up to 10 minutes (or 15 minutes if Varnish doesn't reset the cache-control header given to the browser to something less).

My solution was to set "Cache pages for anonymous users" to be on in the Drupal Performance settings with a reasonable "Expiration of cached pages" of 5min. I then added the following to my settings.php to prevent Drupal from actually caching any page content:

// Use the fake cache for pages since we are caching anonymous HTML with Varnish
if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
$conf['cache_class_cache_page'] = 'DrupalFakeCache';

The DrupalFakeCache just provides stubs that don't store anything or return anything.

Reference: Suppress caching (for development) or to use an external page cache


Using hook_menu() and hook_permission() to control access

Quick and dirty, you could do something like this:

function YOURMODULE_menu() {

  $items=array();

  $items['YOURMODULE/register/ajax'] = array(
    'page callback' => 'YOURMODULE_register_ajax',
    'access callback' => 'YOURMODULE_access_ajax',
    'type' => MENU_CALLBACK,
  );

  // other $items here...

}

and then define you own access function for ajax like this:

function YOURMODULE_access_ajax() {

  if (user_is_logged_in() && $_SERVER['REQUEST_METHOD']=='POST') {
    return TRUE;
  } else {
    return FALSE;
  }

}

which will grant access to the path only if the user is logged in and is using POST to access it.  The key here is when you surf around, you are using GET, but when using AJAX, most of the time at least, you are using POST.  Now, if you wanted to get more fancy other than just if the user is logged in, you could do more with user_access() in there instead of the simple user_is_logged_in().

IF however, you are using GET for your AJAX, you can in your page callback check the parameters and if they don't validate, return MENU_NOT_FOUND; or return MENU_ACCESS_DENIED; instead of the drupal_json() stuff.


To fix this I uninstalled the module and created my own javascript function. Here I had the same problem. Making me realize the problem was caching in some form. The answer to the question was simply adding a query of the current date to the url.
For more informatie: Views rest export does not update


Show the list of all users who edited a node in Drupal 7

So you thought that part would be closed source ? No!
Check http://drupalcode.org/project/drupalorg.git/blob/refs/heads/7.x-3.x:/drupalorg_handbook/drupalorg_handbook.module which adds this functionality to book nodes. This module was built for drupal.org but it's not that difficult to get it modified for your needs!

If you want to do this in Views,

Create a view with Content Revisions in under "Show". uncheck page display,check 'make a block', and click continue and edit. You will be taken to Views UI. Now, remove existing fields and add a new relationship to Content: Author.
Add new field to user name from the just-added relationship.
Add new contextual filter to the node ID. Set the default action to take argument from URL. Then, expand click on Query settings and enable Distinct.
Give the block a title and admin name.
Place block where you want.
Enjoy!


db_select returns empty array, BUT the raw query returns records...?

It's impossible to troubleshoot such a query without access to your environment.

The Devel module has a query inspection tool (Display query log in the Devel settings). that can assist you in determining what query was sent to your database. Use that to determine the exact query sent to your DB and  how it differs from the query you're sending to your SQL client.


Entity Print Module: Create PDF from HTML

If you want to send the PDF directly to the user then you can do something like this:

// Get your HTML from Solr.
$html = $this->getHtmlFromSolr();

$print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');

$print_engine->addPage($html);
$print_engine->send('mydocument.pdf');


"View" with article shown according to detection/selection language

When 'FR' detected on Url default language of website will be changed So you have to Set it to  Default Site Language


the context module allows you to highlight a menu item if certain condition (like a path) has been met.


Organize node file attachments into groups

You can use Field group module. Create multi-value field group, with single-value Group title sub-field and multi-value File field inside. That's pretty much all.


Sure it is  possible but you'll have to write quite a bunch of custom code to accomplish this.

First let's take a look at how a node belongs to a group. This is done through the GroupContent entity.

Before we can actually relate a node to a group, we'd have to install the entity to the group type. This can be done by going to:

Groups -> Group types -> Set available content (can be found via the Operations action button).

First we want to add the possibility to choose one or many groups the node being created can belong to. So we'll have to determine if the node we are trying to add is first installed and then get the groups.

Here is a very simplified example on how to do that by using altering the node and then finding out which group types the current node type is installed to, finally getting the groups and exposing them as checkboxes.

It does not currently care about the user actually having access to that group yet.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_group_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();

  $groupPluginManager = \Drupal::service('plugin.manager.group_content_enabler');

  // Get the group types this node type is installed to.
  $plugin_id = 'group_node:' . $node->getType();
  $groupTypes = $groupPluginManager->getGroupContentTypeIds($plugin_id);

  // This node is not installed to any group types.
  if (empty($groupTypes)) {
    return;
  }

  // Normalize group type ids to just the type name
  $groupTypes = array_map(function($groupType) {
    return explode('-', $groupType)[0];
  }, $groupTypes);

  // Get groups...
  // @TODO: Sort, group the groups to its group type?
  $query = \Drupal::entityQuery('group');
  $query->condition('type', $groupTypes, 'IN');
  $groups_ids = $query->execute();

  // ugh... no groups though?
  if (empty($groups_ids)) {
    return;
  }

  // Create a checkboxes with all groups without any grouping of type
  $groups = \Drupal\group\Entity\Group::loadMultiple($groups_ids);
  $options = [];

  foreach ($groups as $group) {
    $options[$group->id()] = $group->label();
  }

  $form['groups'] = [
    '#type' => 'checkboxes',
    '#title' => 'Attach to group',
    '#options' => $options,
  ];

 foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'custom_group_submit_handler';
    }
  }

}

So we have a list of groups on the node form, how do we actually relate them to the checked groups? We added a submit handler custom_group_submit_handler Let's write that to, again very simplified:

function custom_group_submit_handler(&$form, FormStateInterface $form_state) {

  $node = $form_state->getFormObject()->getEntity();
  $groups = $form_state->getValue('groups');

  // Iterate through each submitted group
  foreach ($groups as $group) {
    $groupEntity = Group::load($group);

    // Assemble the type.
    $type = $groupEntity->getGroupType()->id() . '-group_node-' . $node->getType();

    // Create the relation.
    $groupContent = GroupContent::create([
      'gid' => $group,
      'entity_id' => $node->id(),
      'type' => $type,
    ]);
    $groupContent->save();
  }
}

This took a bit longer to write than I expected, so therefore there are some details you will have to implement yourself, like:

Take group access and permission under consideration
You'd most likely want to clean up the code and move to a more object-oriented approach
You want to handle both add/edit and deletion for the node relation to a group.
You want to make sure the node is not already related to the group.

etc.

Hopefully this is an start to get you further on your objective!


What is the correct way to update my cached block when a node of a given type is saved or updated?

As @Clive commented you need a node list cache tag.

Put the slides and the cache tag when you invoke the template in the build array (not in a hook_theme(), this hook is only called when you install the module):

class SliderBlock extends BlockBase {
  public function build() {
    $build = [
     '#theme' => 'slider_block',
     '#slides' => getSlides(),
     '#cache' => ['tags' => ['node_list']],
    ];
    return $build;
  }
}

Put a TODO annotation in your code to change the list tag to a content type specific node_list:slides, once you have updated to Drupal 8.9.x. See this change record: Added an ENTITY_TYPE_list:BUNDLE cache tag.


How to modify template.php in bootstrap theme, to add a class tag to menu li tag?

Whenever in a theming guide you see a reference to template.php without a context, it should (and in official documentation does) mean the template.php in the root directory of a theme / subtheme you are developing.

In your case it means ./bootstrapMYSUBTHEME/template.php

Never hack your base theme. Your changes will be lost and gone if someone will decide to upgrade it. And if you will upgrade it, you will have to re-write them into new version after each upgrade. Waste of time, subthemes are there exactly to avoid that burden.


How do I remove a menu item on a module?

This is an option in a form. You can use hook form alter in your custom module to hide it. For example

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'SOME_FORM_ID') {
    // you need to find out the form id . You can do so by adding a
    // print line or (dpm($form_id)) in the ..._form function in the Course module.
    $form['course']['duration']['#access'] = FALSE;
   }
 }


Module development - integrating custom content types

One way is to create an export of a CCK content type to use in the module. For an example of this method see How to create a CCK content type and fields from a module.

Another exported CCK example


Should I use t() in hook_update_N() or admin UI in a custom module?

Ever hear the expression "You Play Like You Practice"? If you get in the habit of NOT using t() for strings that are translatable just because it's only for your site ("practice"), then when it counts (i.e. "play") you will probably also leave out t(), because that's what you're used to.
There is really no downside to doing it correctly here. You're not saving anything or making any measurable difference in performance. The upside is that if you do it the same everywhere, you're not going to introduce a bug by leaving off t() where it is needed, and you can then also use the automated coding standards tools to check your code without seeing a lot of fails from your missing t() functions - that keeps these many fails from obscuring the few real problems you might have.


Omega subtheme - Dropdown menus not working properly

The usual behavior is for sub-menus to only expand when you are on the parent item; so if you have a tree like the one below, you would only see a dropdown containing "Child" when you are on "Parent":

Home

Parent

Child
Child
Child

SOLUTION:

Go into the menu list links  which is admin/structure/menu/manage/main-menu for the main menu and edit the item you want expanded ("Parent" in this case)
Check the checkbox "Show as expanded"

That item will now be expanded no matter where you are on the site.


The selection_handler element property allows to specify a plugin id of a class that would override the default selection handler for EntityAutocompleteMatcher. A separate plugin would be able to build a different Entity Query.

Create a plugin of EntityReferenceSelection type. This should be a derivative of the DefaultSelection plugin similar to TermSelection.

Then you can override entityQueryAlter to add additional conditions to the entity query.


Using drush to run a local script on a remote site

Nope, what you want to do is not supported.  When you run drush @foo scr, it causes Drush to run your scr command on the remote system.  The scr command on the remote system will then look for the script it wants to run on its own filesystem.  In order to make this work, you'll need to somehow get your script on the remote system, and then run it with your remote scr command.

Note that this is different than the drush php-eval command, which takes the php code to run on the commandline.  So, in theory, you could passing your php over on the commandline rather than in a file; however, in practice you may find this to be problematic due to the fact that bash is going to process your text, so you'll have to make sure that everything is properly escaped.  Moving the script to execute to the target machine will be more reliable for any nontrivial script.


Check db_merge status whether inserted or updated

MergeQuery::execute() returns MergeQuery::STATUS_INSERT when the data was inserted in the database table, and MergeQuery::STATUS_UPDATE when a row was updated.

MergeQuery is the class of the object returned from db_merge().

public function execute() {
  if (!count($this->condition)) {
    throw new InvalidMergeQueryException(t('Invalid merge query: no conditions'));
  }
  $select = $this->connection->select($this->conditionTable)
    ->condition($this->condition);
  $select->addExpression('1');
  if (!$select->execute()->fetchField()) {
    try {
      $insert = $this->connection->insert($this->table)->fields($this->insertFields);
      if ($this->defaultFields) {
        $insert->useDefaults($this->defaultFields);
      }
      $insert->execute();
      return self::STATUS_INSERT;
    }
    catch (Exception $e) {
      // The insert query failed, maybe it's because a racing insert query
      // beat us in inserting the same row. Retry the select query, if it
      // returns a row, ignore the error and continue with the update
      // query below.
      if (!$select->execute()->fetchField()) {
        throw $e;
      }
    }
  }
  if ($this->needsUpdate) {
    $update = $this->connection->update($this->table)
      ->fields($this->updateFields)
      ->condition($this->condition);
    if ($this->expressionFields) {
      foreach ($this->expressionFields as $field => $data) {
        $update->expression($field, $data['expression'], $data['arguments']);
      }
    }
    $update->execute();
    return self::STATUS_UPDATE;
  }
}


How to get node's view mode in hook_page_attachments?

To attach a library only when a node in a certain view mode is displayed you can use hook_entity_view/hook_ENTITY_TYPE_view like following.

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function MYMODULE_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $node = $entity;
  if ($node->bundle() === 'page') {
    if ($view_mode === 'full') {
      $build['#attached']['library'][] = 'MYMODULE/foo';
    }
    elseif ($view_mode === 'default') {
      $build['#attached']['library'][] = 'MYMODULE/bar';
    }
  }
}


How to notify users when a new comment is posted in the same page as they did?

Have a look at this rule (in Rules export format), which does what you're asking for:

{ "rules_notify_commentors_about_new_comment" : {
    "LABEL" : "Notify commentors about new comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "comment" ],
    "ON" : { "comment_insert" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "users_that_commented" : "Users that commented" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "comment:node:comments" ] },
          "ITEM" : { "current_comment_item" : "Current comment item" },
          "DO" : [
            { "list_add" : {
                "list" : [ "users-that-commented" ],
                "item" : [ "current-comment-item:author" ],
                "unique" : "1"
              }
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users-that-commented" ] },
          "ITEM" : { "current_comment_author" : "Current comment author" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : {
                      "data" : [ "current-comment-author:field-accept-boolean" ],
                      "value" : "1"
                    }
                  },
                  "DO" : [
                    { "mail" : {
                        "to" : [ "current-comment-author:mail" ],
                        "subject" : "New comment to node with id [comment:node:nid]",
                        "message" : "There is a new comment added to the node with id [comment:node:nid]",
                        "language" : [ "" ]
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

The only additional module needed is the Conditional Rules module, while it does use a few of the more advanced techniques available in the Rules module.

If you're familiar with reading/digesting Rules in Rules export format, I'd hope the rule is self explaining. If not here is a summary of the above rule:

Rules Event: obvious ... after saving a new comment.
Rules Conditions: feel free to add whatever fits (eg limit to selected content types only, like "Projects" in this specific question).
Rules Actions:

Add a variable "users_that_commented" (= a list of users).
Loop over all existing comments, and for each comment author, add that author to the list of users (= users_that_commented). Note the "unique" that is turned on (we do not want duplicates in that list of users).
Loop over the list of users (= users_that_commented ... again, which we just created and populated). And for each user in that list, do your thing, in this case "send an eMail", provided the field field_accept_boolean is TRUE (which you can check if you have the Conditional Rules module enabled). The "To" value is crucial here, the body, the from, the title, etc is up to your own imagination.  If you don't want to use the Conditional Rules module, you could also rework the Rules Action withn the last Rules Loop to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

If you want, just import the above rule in your own site (using the Rules UI), after you enabled the Conditional Rules module, and after replacing the field name of field_accept_boolean to fit the machine name of your own field.

That's really all it takes ... a Rules variable, Rules lists and loops, and Conditional Rules.

PS: There is one minor improvement of this rule I can think of (if perfect is not good enough) ... After anybody finds out what that may be, and after the question details are corrected about that also, I'd be happy to update my answer (= change 1 detail in the rule) to also implement that.


Entity reference views with Exposed filters

I don't have drupal on me atm to try this out. So consider this an educated guess.

in RELATIONSHIP add student_id referenced entity and click on force relationship.

Then hope that in filters, there is a new option to add referenced entity.


How do I add Google Scholar meta tags to a custom content type?

There is a module that allows adding Google Scholar meta tags: https://www.drupal.org/project/metatag_google_scholar . However, it is only available for Drupal 8.

I post this answer anyway, in case it might be useful (as an inspiration for a backport, for instance).


How to Implement Modal AJAX Form Pagination

To implement this I went down a similar route as the "Add another item" functionality on field api fields. For reference, this is done in WidgetBase.php.

Firstly, I copied over a couple of static functions to get and set values inside storage:

/**
 * {@inheritdoc}
 */
public static function getModalState(FormStateInterface $form_state) {
  return NestedArray::getValue($form_state->getStorage(), ['search_results']);
}

/**
 * {@inheritdoc}
 */
public static function setModalState(FormStateInterface $form_state, array $field_state) {
  NestedArray::setValue($form_state->getStorage(), ['search_results'], $field_state);
}

Then in buildForm() I added this to intialise the storage if it wasn't set yet.

if (!static::getModalState($form_state)) {
  $field_state = array(
    'page' => 1,
  );
  static::setModalState($form_state, $field_state);
}

And then use the storage to get the page parameter for my search:

$modal_state = static::getModalState($form_state);
$page = $modal_state['page'];
$search_response = $this->getSearchResults($page);

The crucial part of the implementation was separating the increment in the page variable from the ajax handler and putting it into the submit handler. So for the "Next" button:

// Add "next page" pager.
$form['next'] = [
  '#type' => 'submit',
  '#value' => $this->t('Next'),
  '#submit' => ['::nextPageSubmit'],
  '#ajax' => array(
    'callback' => '::searchAjax',
    'wrapper' => self::AJAX_WRAPPER_ID,
    'effect' => 'fade',
  ),
];

And the submit handler

/**
 * Submission handler for the "Next page" button.
 *
 * @param array $form
 *   The form.
 * @param FormStateInterface $form_state
 *   The form state.
 */
public function nextPageSubmit(array $form, FormStateInterface $form_state) {
  // Increment the page count.
  $modal_state = self::getModalState($form_state);
  $modal_state['page']++;
  self::setModalState($form_state, $modal_state);

  $form_state->setRebuild();
}

My ajax callback is then the same for searching, and paginating.

I also added a submit handler to the search button to reset the page back to 1.

The full source code for the form in this state can be found at https://github.com/acbramley/embridge/blob/2a561c9c388ccf715f93727cf136e50fc02163c9/src/Form/EmbridgeSearchForm.php

These code snippets are essentially the guts of what I needed to get the pagination working.


Redeclare issue user_has_role following upgrade from Drupal 7.34 to Drupal 7.36

The user_has_role() function has been introduced with Drupal 7.36, as stated here, and detailed here.

Following information given by the error message you received we see that:

the function is primarily declared in modules/user/user.module:863: looking at the code of the user module confirm this, ok
the new declaration is said to happen through modules/php/php.module(80): again, looking at the code of the php module confirms that line 80 executes eval('?> . $code);, ok
so the culpry supplemental declaration should be found at line 23 of the PHP content of a field which uses a format where the (not so usual) PHP evaluator filter has been enabled

IMO you should:

review all of your defined text formats, in order to select which of them have PHP evaluator filter enabled
from this reduced list, look for any node or block using these text formats (should not be as many)
then review the corresponding contents, where you'll probably find that somebody had created its own user_has_role() function for its needs, since it didn't exist yet before 7.36

HTH


How to call custom javascript function defined in js file from .module file

I have faced same kind of issue few days ago and I have resolved it by adding type as module to the script tag. All script with type=module have differ attribute. It download such js parallel with loading of other page and then run them in order but after the parsing is done.

This might help you:

<script language='javascript' type='module'>


Using behat to create nodes and testing user owns them

In the example in features/api.feature you'll find how to do this:

  Scenario: Create nodes with specific authorship
    Given users:
    | name     | mail            | status |
    | Joe User | joe@example.com | 1      |
    And "article" nodes:
    | title          | author   | body             | promote |
    | Article by Joe | Joe User | PLACEHOLDER BODY | 1       |
    When I am logged in as a user with the "administrator" role
    And I am on the homepage
    And I follow "Article by Joe"
    Then I should see the link "Joe User"


You will have to override the access callback used for your view pages using an hook_menu_alter implementation (from a custom module) to use a custom one that will do the MAC address check.

Assuming the MAC address is provided as an HTTP header, this would look like.

/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter($items) {
  if (!isset($items['protected/view/path']['access arguments'])) {
    $items['protected/view/path']['access arguments'] = array($items['protected/view/path']['access callback']);
  }
  else {
    array_push($items['protected/view/path']['access arguments'], $items['protected/view/path']['access callback']);
  }
  $items['protected/view/path']['access callback'] = 'MODULE_menu_access';
}

/**
 * Return whether or not the request contains an authorized MAC address header.
 */
function MODULE_menu_access() {
  $mac_address = $_SERVER['HTTP_MAC_ADDRESS'];

  // Validate the MAC address.
  if (!MODULE_mac_is_authorized($mac_address)) {
    return false;
  }

  // Return the result of the original access callback
  $args = func_get_args();
  $access_callback = array_pop($args);
  return call_user_func_array($access_callback, $args);
}


Does the Node processor mapping require a unique identifier for the GUID or is this not mandatory?
You do not need to have a unique identifier to import data, but you might get duplicate data if you do not use a unique identifier.  From your question I assume you are interacting with the API in the feeds fetcher. Can you get "duplicate" results when using the API? Or, is each import ALWAYS  creating new nodes?
Xpath
Use //content/text() to return the json text {"appointmentSet":[{"appts":[]}],"bookingAllowed":false,"maxBookAheadPeriod":25}


Rules won't let me change some node properties

You appear to be attempting to break the rules regarding node creation.  You could probably do it by writing a module but why?

If all you want to do is have a fresh copy of a node with similar field values, consider using Node Clone which is a re-write of one that used to exist called "Edit As New", apparently.  Or maybe Replicate.


/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  array_unshift($form['#validate'],'my_first_custom_validation' );
  $form['#validate'][] = 'my_last_custom_validation';

}

function my_first_custom_validation(&$form, &$form_state){
  if(isset($form_state['values']['mail'])){
    if($user = user_load_by_mail($form_state['values']['mail'])){
      rules_invoke_component('rules_send_email_to_user', $user);
    }
  }
}

Hook into register form using hook form alter
Add custom validation handler to the top of submit handlers (must execute first before any other submit handler )
In the handler function  try to load user by email using user_load_by_mail
If true send the email using drupal_mail or rules then redirect to same page or any page to stop the execution.

The only problem with this code that the validation error still showing , I could not find way to stop drupal from execute the rest of validation handlers


Sounds like a common mistake with views.

On you filter's settings, under More make sure you have the Filter identifier set with the same name, in both your page and your block.


How do I pass a theme variable from a template to another?

The solution I am working with is to use drupal_static(); simplified essentials in code below - take care with the &ampersands. It is giving me control where I need it.

So, using this approach, I can - taking their global context into account -  per field, set variables in the usual way e.g. in mytheme_preprocess_field() subsequently to be used in a related template like field--node--title--agenda.html.twig

function mytheme_preprocess_simplenews_newsletter_body(&$variables) {
  // prepare to alter static var ...
  // get a reference binding to static var
  $var = &myvariable_function();
  // alter static var
  $var = 'simplenews_newsletter';
}

function mytheme_preprocess_field(&$variables, $hook) {
  // prepare to read static var
  // assign static var
  $var = myvariable_function();
  // $element is the render array for the field
  $element = $variables['element'];
  // filter those cases where it matters that we're theming a newsletter
  if ($element['#view_mode'] == 'email_html' and $var == 'simplenews_newsletter') {
    // Do stuff here like setting a variable for twig ...
    $variables['summons'] = 'some text';
  }
}
function &myvariable_function() {
  $var = &drupal_static(__FUNCTION__);
  if (!isset($var)) {
    // generate contents of static variable
    $var =  'initial_value';
  }
  return $var;
}

I am sure that there are other ways of communicating common context between different levels of a page's render hierarchy. Let me know how you'd do it.


How to prevent duplicate URL patterns and not have "-#" appended to the URL alias?

As Clive mentions, Pathauto does not have a configuration to disable uniquification (suffixing "-#").

If you look through the main function that builds paths, pathauto_create_alias() you can see that the only way to prevent pathauto_alias_uniquify($alias, $source, $language) from running would be to trigger one of the scenarios in which pathauto gives up on alias creation (e.g. empty pattern, updating an existing alias, etc.) which wouldn't help where you need it still generated in some cases.

Your best bet to cover this scenario is to have a custom node validation function execute pathauto_create_alias()'s logic with $op = 'return' to see what the generated alias would be  before generation, and throw back errors upon duplicate uniquified paths.


For input, saving to the DB, Database API takes care of it, automatically prevents SQL injection when using dynamic query. Since your code is using dynamic query, you're all good.

If you were to use static query you have to make sure you use placeholders as the docs mention.

For output, to prevent XSS, you'll want to use a template file, and print your value via Twig. Which auto escapes everything by default. If you don't use Twig, then you need to use the appropriate API function.


Is there a submit handler for custom fields?

You can use hook_field_update in your module where you define your field..

  Define custom update behavior for this module's field data.

  This hook is invoked from field_attach_update() on the module that
  defines a field, during the process of updating an entity object
  (node, taxonomy term, etc.). It is invoked just before the data for
  this field on the particular entity object is updated into field
  storage. Only field modules that are storing or tracking information
  outside the standard field storage mechanism need to implement this
  hook.


From what I've read, going from D5 -> D6 -> D7 can be a pretty involved task.

These two pages suggest you may want to start with a clean install of D7, recreating your content types and  Views, then using Migrate module or a custom script to migrate the content/users. (The migration path from CCK to the Drupal 7 Fields is discussed here: http://drupal.org/node/1144136.)

http://drupal.org/upgrade
http://quicksketch.org/node/5739

I don't know how complex your setup is (how many Views, content types, and modules you have), but it's probably the case you are going to need a fair amount of work to bring your site into Drupal 7.

The related question is https://drupal.stackexchange.com/questions/1420/migration-from-drupal-5-to-7.


Photo-swipe is not loading in my website

I am using the Juicebox module in my Drupal 7 site for swiping.  With my iPhone 4, it is working super. I have tried other solutions, without luck.  The free version of Juicebox allows you to place 50 pics in a box.


How to get new password by mail instead of password reset url (Forgot password)

You can use Recovery Password (Email New Password) module.

  Recovery Password module makes it possible for Drupal to send any
  random generated password(new password) by email instead of URL to the
  user.

Refer to the module page for detailed description. Feel free to contact me, in case of any issue. I'm maintainer of this module.


How can I route automated emails through an email function in my module?

I think this is what you're looking for:

http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7

"hook_mail_alter() allows modification of email messages created and sent with drupal_mail()... All core modules use drupal_mail() for messaging, it is best practice but not mandatory in contributed modules."


Is there any way to create a discount that only discounts one product in an order?

With the offer types defined in Commerce Discount / Commerce Discount Extra, there isn't much you can do. The closest ones to what you've described are the per-quantity % off discounts, but as you've discovered, you have to specify either a target product or product category. If you're using a taxonomy configuration that allows the per-quantity category discount (i.e. you have a term reference field on your product display nodes that you can target in the "Products in these offer categories" field), then you can configure this by just identifying every product category in a comma separated list. Otherwise this is going to require custom code.

Since your requirement is also to tie this to a coupon code, you're going to have to write that custom code as a custom offer type. It could be that you simply copy the per-quantiy product discount and change the matching logic to allow discounting any product on the order, but I gotta be honest ... that code is hairy. I wrote the current implementation, and I'm sure it would take even me a full day just to remember what's going on in there and try out some potential solutions.

That said, you could try to "hack" it using existing pieces. Basically ... you could create a new taxonomy vocabulary with a term that identifies products that are eligible for the free product offer. You can then add a term reference to that vocabulary on every product display and select the term for them. You're basically creating a global product category that all of your products are assigned to ... and you can then hide the term from the UI so customers never see it. This may actually be a preferable solution in the future anyways, as the merchant may end up wanting to restrict certain products from these coupons. Give it a go, let us know how it turned out!


Is there an alternative to the Node reference, and the Feeds modules?

There is a patch in the works that adds Feeds support for Entity reference fields.

References will most likely be deprecated in favour of Entity Reference in the near future, so this is a good option once it gets finalized.


Change default text (-Any-) of select option in Exposed View Filter

If you use the Better Exposed Filters module you can do this using the views interface. Changed exposed form style to   'better exposed filters' and adjust the settings

  The Better Exposed Filters module replaces the Views' default single- or multi-select boxes with radio buttons or checkboxes, respectively. Description fields and Select All/None links can be added to exposed filters to make for a better user experience.


You will need the Services module, together with the REST Server submodule.

The two will allow you to create a new "server" and configure which entities can be retrieved via REST, what the authentication should be and which exactly calls are allowed (get, post, delete, etc.).


Looking for Acquia Dev Desktop database settings

In the case of Windows 8, Acquia Dev Desktop 2 generates the settings file in this location:

C:\Users\\[user]\\.acquia\DevDesktop\DrupalSettings\loc_Testing_local.inc


How to determine where the CCK fields are stored in database?

You want the content_node_field_instance table. As that table defines each "instance" of a field on different content types. For the field configurations (global configs, independent of instance configs) you want the content_node_field table.

Similarly in Drupal 7 there's field_config table for global field configurations, and field_config_instance table for each instance of a field with content types.


The cleanest solution would be to hide a field that has no content.

Go into the configuration of each field you output on the view and under No results behaviour check hide if empty


To understand what may be going wrong in your attempt it would help to clarify a few things about which modules do what.

Your menus are handled by either core menu or another of the menu modules that build upon it.  They display links and and any selection reroutes the browser to a new URL.
Views is a User interface to query the database in which all of your content is held.  If you select the settings tab in the main views page you can set the actual SQL query to be displayed in the preview area.  This is helpful in understanding what is being searched for in your settings, although you will need some understanding of queries to make sense of it.  A view is called either by using the defined path in the URL or by placing the view in a panel (Which you have done here).
Panels is primarily a module to handle the display of content. However, it works very closely with Page Manager module.
Page Manager intercepts URL requests and acts upon them in accordance with rules you establish for selection and contexts.  Panels and Page Manager collaborate together and switch between themselves regardless of where you start in the UI.

When you select a menu item it is requesting that the browser go to a specified URL (menu).  That URL request should be requesting the panel page (panels and page manager) which in turn is requesting the view that you have placed in it (Views). For your example, once the request  is made menus, panels and page manager are done.  Your real issue is with the views, so you must focus on the view module and your definition.

In order to help the view distinguish between various levels of content you can add a field to the content type that defines its level. You can then expose that field to views by selecting it as a filter and setting the value you want for that article.  You can create multiple view pages within the View definition to address different filter settings needed for placement in each of your panel regions. By categorizing the menu-selection/articles and providing separate view pages (within the same View definition) you can refine your control of the displayed content.

You can also limit the number of articles displayed by a view by selecting the options under pager in the view definition page and telling how many pages/articles to display.

You can learn more about Views at nodeone.se


cannot validate custom field widget for user profile field when editing node

I got around it by attaching the validation in hook_form_alter:

function referrer_widget_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "user_profile_form") {
        $form["field_who_referred_you"]["#element_validate"] = array('referrer_widget_field_widget_validate');
    }
}


To select multiple items with "Autocomplete (tags style)", you must enter a comma-separated list in the text box. Otherwise, if you want to enter the values in separate text boxes, use the plain "Autocomplete" widget type.


How to change the e-mail output of a Entity type field in a webform

Because I was in quite a hurry, I ended up creating hidden fields in my form for date and location. Using javascript I fetch the information from the Select field and add them to these hidden field. This way this information is send with the submission.
Not the prettiest way to do it but it works.