How to create main links like home ,services programatically?

// You can use the following code to create a menu.

// Path.
$path = 'admin/structure/menu/manage/';
// Title of your menu.
$menu['title'] = 'My Another Menu';
// Description.
$menu['description'] = 'My Another Menu';

// Manu name like navigation, management which we have in drupal.
$menu_name = 'custommenu';
$menu['menu_name'] = $menu_name;

// Link title.
$link['link_title'] = 'My Another Menu';
// Link path.
$link['link_path'] = $path . $menu_name;
// Router path.
$link['router_path'] = $path;
// Module name.
$link['module'] = 'menu';
$link['plid'] = 0;

// Saves a menu link.
menu_link_save($link);
// Saves a custom menu.
menu_save($menu);

// After creating main menu. You can create links under it.
// Use the below code to create custom links.

$item_link = array(
  'link_path' => '<front>',
  'link_title' => 'Test link',
  'menu_name' => 'custommenu',
  'weight' => 0,
  'expanded' => 1,
);
// Creates custom link under main menu.
menu_link_save($item_link);


How do you update the default value for a field programmatically?

The field_update_instance() function is the standard method

  Updates an instance of a field.

You can take the array returned by field_info_instance(), make your changes, then pass it back to field_update_instance() and the changes will be saved.


Counter is always set to 1 and not incrementing

The problem is that you failed to grasp how HTTP is basically stateless.

static $counter = 0;

This value will be kept during one run. But one run is one page load. Obviously, it will be fresh and new at all page loads - ie all article reads.

If you need to keep value in one user session, see Session API, that's what it is for.

If you don't need any extra functionalities, just use $_SESSION['mymodule_counter']. If you want to make sure session is started, use drupal_session_start()


Autocomplete won't work for entity reference field unless User > Administer Users permission is granted

The endpoint that provides AJAX entity reference completion (system.entity_autocomplete in system.routing.yml) is configured with with requirements._access: 'TRUE' property. This should make the /entity_reference_autocomplete/%/%/% path accessible to any user.

As such, check for any module that might be modifying its permissions.


How to limit a user to one vote when using Rate module?

I don't remember this feature in Rate. I don't know the module well enough to know if you can set that user can vote only once per node, but you can just alter the render. You should probably go for a custom module and implements HOOK_preprocess_HOOK.

/**
 * Implements hook_preprocess_HOOK().
 */
function MODULE_preprocess_rate_widget(&$vars) {
global $user;
// if user have voted
// then alter the render
// else nervermind
}

Hope that help.


Create migration stubs of entities for a multiple value reference field?

Yes. This use scenario is covered by migration_lookup plugin with its stub_id property and making sure it's referenced migration (in your case, a user migration sourced from the JSON array) has defined all the required fields via the default_value plugin such that migration_lookup can rely on it to stub out a user before the stub_id migration can be run on its own to fill in fields for each referenced entity.


There's not a direct function that I'm aware of. But you can query the views_display DB table, indirectly to retrieve your view as the path data is serialized information:

function get_view_from_path($path) {
  $page_views = db_select('views_display','vd');
  $page_views->join('views_view', 'vv', 'vv.vid = vd.vid');
  $page_views = $page_views->fields('vd')
    ->fields('vv')
    ->condition('display_plugin', 'page')
    ->execute();

  foreach ($page_views as $view) {
    $options = unserialize($view->display_options);
    if ($options['path'] == $path) {
      return views_get_view($view->name);
    }
  }
  return FALSE;
}

if ($my_view = get_view_from_path('my-view-path')) {
  // @TODO: Look @ $my_view->display["page"]->display_title
  // $my_view->display["page"]->display_options['header']
  // for title & header data.
}


Or would you rather make one type with all possible fields merged onto
  one form, then tweak the suggestion template so that irrelevant parts
  are /shown/hidden upon changing a dropdown menu that specifies the
  subclass?

If you're going the single-type route, here are two tips: Drupal Forms API supports conditions, check the docs; it might be useful to take a look at the Prepopulate module.


Try these.

1) You may have changed the Navigation block settings:(Administration -> Structure -> Blocks -> 'Navigation'). Configure the 'Navigation' block under 'Content types'.

2) Configure :structure>menus>navigation>listlinks (if you are using Bartik theme).

Reference: http://drupal.org/node/1166416, http://drupal.org/node/1094238


Getting the number of Flood events within threshold?

The only way to do that with the default FloodInterface would be to use the isAllowed method and adjust the threshold to the number of allowed attempts.

From a hook_form_alter() you could do something similar to this, where 'my_trigger' is the name of the event that is registered, such as 'contact' for the contact form or 'user.failed_login_ip' and 'user.failed_login_user' for user login. 5 would be the maximum number of times the event could have been registered in 3600 seconds.

<?php

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Hide element if over the number of allowed attempts
  if (!\Drupal::flood()->isAllowed('my_trigger', 5, 3600)) {
    $form['my_element']['#access'] = FALSE;
  }
}


Disable menu cache for hook_menu() implementation

Good conversation about other things in this code sample, but to make a page loaded through a menu callback skip cache, you can try drupal_page_is_cacheable(FALSE). See: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_page_is_cacheable/7.x


Views - Combining Fields into a single link?

You can add the 4 fields in this order:

nid
first name
middle name
last name

For the first 3 fields, check the "Exclude from display" checkbox.

For the 4th field, in the rewrite results section, check the "Rewrite the output of this field", then in the "Text" text area use the replacement patterns for the other fields to join them together.

It will be something like this:

[field_first_name] [field_middle_name] [field_last_name]

Then also check the "Output this field as a link" checkbox and for the "Link path" you can again use the replacement patterns (expand the fieldset to see the available replacement tokens).

It will be something like:

node/[nid]


How to debug a variable in a controller class (var_dump)

OK, I'm going to be that guy. Do yourself a favour and set up Xdebug, hacks like var_dump() or var_export() are very bad practice and sooner or later you will forget to remove some of those statements and it will end up in production. Also it takes one single click to set up a breakpoint, as opposed to writing a var_dump()  or var_export() statement. Not to mention that the amount of information you can get by using a debugger is vastly more comprehensive.


Restrict content access by user language

I managed to solve this over the weekend, thought I'd share my solution if someone has the same problem.

TL;DR.

In my setup I use the contrib module Content Access. Basic configuration; In the System user preferences I deny access content to anonymous users, and in the Access Control settings for each content-type (admin/content/node-type/[type]/access) I disable View access for authenticated user. This way Content Access module will control exactly which role or which user can view/update/delete any content, even down on an individual node level.

I then wrote my own module that implemented the ACL api. It was a bit tricky to learn the node access system, and even more so with the complete lack of ACL module documentation/tutorials, but when I figured it out the module works really well.

The module utilizes Translation Access (i18n_access module) for deciding the user language access permissions. Translation Access provides access control for Edit/Delete, but not for Viewing content. If that would have been the case, this module would not have been necessary...

So first I added a custom submit handler to the default permissions rebuild form

/**
 * Rebuild all permission when using the standard form
 */
function mymodule_form_node_configure_rebuild_confirm_alter(&$form, &$form_state) {
    array_unshift($form['#submit'], 'mymodule_rebuild_permissions_submit_handler');
}

/**
 * Route submit function through custom handler to get rid of unwanted $form arguments
 */
function mymodule_rebuild_permissions_submit_handler() {
    mymodule_rebuild_permissions();
    drupal_set_message(t('Language permissions have been rebuilt.'));
}

Now this is where the fun begins, I created a "rebuild permissions" function that iterates all nodes restricted by language (in my case, all nodes). If a uid is provided, permissions will be rebuilt for that user only.

/**
 * Rebuilds permissions for all nodes and users, or only for a specified user
 */
function mymodule_rebuild_permissions($uid = null) {
    //Select the nodes to apply language restriction on
    $nodes = db_query("SELECT nid, language FROM {node}");
    while($node = db_fetch_object($nodes)) {
        $acl_id = mymodule_get_node_acl($node);
        if(!$uid) {
            mymodule_update_user_access_all($acl_id, $node);
        } else {
            mymodule_update_user_access($acl_id, $node, $uid);
        }
    }
}

As seen above we need a function to retrieve/create the ACL id of the node

/**
 * Gets the node ACL id
 */
function mymodule_get_node_acl($node) {
    $module = 'mymodule';
    $acl_name = $module.'_'.$node->nid;
    //Get the ACL for this node
    $acl_id = acl_get_id_by_name($module, $acl_name);
    //If it doesn't exist, create new ACL
    if(!$acl_id){
        $acl_id = acl_create_new_acl($module, $acl_name);
        // View = 1, Update = 0, Delete = 0, Priority = 0
        acl_node_add_acl($node->nid, $acl_id, 1, 0, 0, 0);
    }
    return $acl_id;
}

As well as for updating user permissions

/**
 * Update language permissions for all users
 */
function mymodule_update_user_access_all($acl_id, $node) {
    $users = db_query("SELECT uid FROM {users} WHERE uid > 1");
    while($user = db_fetch_object($users)) {
        mymodule_update_user_access($acl_id, $node, $user->uid);
    }
}

/**
 * Updates language permissions for a specific user
 */
function mymodule_update_user_access($acl_id, $node, $uid) {
    //Remove from list
    acl_remove_user($acl_id, $uid);
    //Add again if user has permissions
    if(mymodule_node_access($node, $uid)) {
        acl_add_user($acl_id, $uid);
    }
}

Check if the user has role and language access

function mymodule_node_access($node, $uid) {
    //Get the user roles
    $user_roles = user_load($uid)->roles;
    //Get the content access roles
    $node_roles = content_access_get_per_node_settings($node);

    //Check if user has permission to view node
    $node_access = false;
    if(isset($node_roles['view'])) {
        foreach($node_roles['view'] as $role) {
            if(isset($user_roles[$role])) {
                $node_access = true;
            }
        }
    }
    //Check i18n selected languages
    $perm = db_result(db_query("SELECT perm FROM {i18n_access} WHERE uid = %d", $uid));
    $user_languages = $perm ? explode(', ', $perm) : array();
    $lang_access = in_array($node->language, $user_languages) || $node->language == '';
    //Return true if we have both node and language access
    return $node_access && $lang_access;
}

Obviously we have to update access control when inserting/updating nodes and users

/**
 * Implementation of hook_nodeapi()
 */
function mymodule_nodeapi(&$node, $op) {

    if($op == 'insert' || $op == 'update') {
        $acl_id = mymodule_get_node_acl($node);
        mymodule_update_user_access_all($acl_id, $node);
        if($op == 'insert') {
            node_access_rebuild();
        }
    }
}

/**
 * Implementation of hook_user()
 */
function mymodule_user($op, &$edit, &$account) {
    if($op == 'after_update') {
        mymodule_rebuild_permissions($account->uid);
    }
}

Finally these functions had to be included to make the ACL api work

/**
 * Implementation of ACL hook hook_enabled()
 */
function mymodule_enabled() {
    return !mymodule_disabling();
}

/**
 * Implementation of hook_disable().
 */
function mymodule_disable() {
    mymodule_disabling(TRUE);
}

/**
 * Remembers if we have disabled access.
 */
function mymodule_disabling($set = NULL) {
    static $disabling = FALSE;

    if (isset($set)) {
        $disabling = $set;
    }
    return $disabling;
}

...and that's it!

Don't forget to rebuild permissions before anything (/admin/content/node-settings)


In Drupal 7 how to expose TID (term id) as a selectable field on the manage display section of the taxonomy page?

You can use Display suite, and create a custom field.

Install ds and ds_extras.
Configure ds_extras to enable custom fields.
Activate a display suite layout for your taxonomy term display.
Create a custom field, where you can put the tid as a token.


It sounds like you're wanting to index a Views page in the search result. There's similar question been asked already if that's the case. A solution wasn't marked but the search by page module was mentioned. It has a submodule that allows you to index any arbitrary path on your site.


Change content of $page['content'] variable

You can use hook_page_alter to add them into the content array:

function YOUR_MODULE_page_alter(&$page) {

  // Check if this is the correct page.
  if(!isset($page['content']['system_main']['#form_id']) || $page['content']['system_main']['#form_id'] != 'user_login') return;

  // Add links.
  $page['content']['system_main']['register'] = array(
    '#markup' => '
NO ACCOUNT? REGISTER
',
    '#weight' => 20
  );
  $page['content']['system_main']['password'] = array(
    '#markup' => '
FORGOT PASSWORD?
',
    '#weight' => 21
  );

}

Another option here would be to use hook_form_alter instead. Although hook_form_FORM_ID_alter may well be the most efficient option as it will only run for this specific form removing any overhead from other pages.


How do I include JavaScript on a single page in a way that is amenable to scale

Following Steps will make working with External JavaScript libraries in Drupal 8 absolutely clear (including how to conditionally load it in specific pages):

Step 1:
Place the JavaScript file in your theme or module inside a folder called js. After this step your folder structure must look like :

my-theme/js/my-script.js

Step 2:
If your theme already has a my-theme.libraries.yml file open it, if not create it.

In Drupal 8 Libraries are simply collections of CSS or JS files bundled together under a uniquely identified library name.

In this step we need to include the JS file that we created in step 1 in our library. we do it by adding following lines of code in our my-theme.libraries.yml file.

my-library:
  js:
    js/my-script.js: {}

Now we have an asset library called my-theme/my-library which can be loaded to our site in several ways.

Step 3:
Final step is to load the library in our site. This can be done in 4 specific ways:

Way 1:
Attach library globally via theme-name.info.yml file

Libraries can be specified in the theme-name.info.yml file by adding it to the libraries property, like this:

name: my-theme
type: theme
description: my theme
package: other
core: 8.x
libraries:
  - my-theme/global-effects
  - my-theme/my-library

base theme: stable

Any libraries specified here in the themename.info.yml file will be made available on evey page.

Way 2:
Using hook_page_attachments_alter in theme-name.theme file.

Following lines of code will attach our library only to the node listing page.

function mytheme_page_attachments_alter(&$page){
  $path = $current_path = \Drupal::service('path.current')->getPath();
  if($path == '/node') {
    $page['#attached']['library'][] = 'my-theme/my-library';
  }
}

Way 3:
Another useful way to conditionally add a library is by using a preprocess function like hook_preprocess_page().

Here's another example of restricting our asset libray to the front page

function mytheme_preprocess_page(&$variables){
  if ($variables['is_front'] == TRUE) {
    $variables['#attached']['library'][] = 'my-theme/my-library';
  }
}

Way 4:
Asset libraries can also be attached from within a Twig template using the attach_library function. Anytime that template is used the corresponding library will be attached in accordance with any template-specific conditions.

In order to see this in action, we need to create or modify a template in our theme. In this example let us modify node.html.twig template to attach our library only if node.id == 1 with following lines of code

{% if node.id == 1 %}
  {{ attach_library('my-theme/my-library') }}
{% endif %}

With this in place, visiting node 1 in our site, we will be able to see our library in action.


Term reference is not available as a contextual filter for a View. Why not?

As mentioned in Niall's comment, you will want to add the taxonomy relationship. In a view that I created recently, I used the Content: Taxonomy terms on node relationship. Once I added it, Content: Has taxonomy term became an available option under Filter criteria.

That is only one way of doing it. There are a few different taxonomy relationships which serve unique purposes. I'd experiment with them to see what fits your needs.


Adding Paypal Express Checkout for multiple domains

This functionality is not currently in the Paypal EC module.  Please see https://www.drupal.org/node/2130605 for more information.

Basically, the rule that is created by enabling the Paypal EC module is hard coded into the .module file, making it impossible to use more than one instance without patching the module.


views_get_view_result() how to retrieve a specific pager (pagination) page?

I think I have it figured out:

$myview = views_get_view('MYVIEW');
$myview->set_display('MYDISPLAY');
$myview->set_current_page(3); // Get the pagination page 3
$myview->pre_execute();
$myview->execute();

dpm($myview->result); // You need Devel module for using dpm()


You specify the menu_name parameter.

From the devel module:

$items['devel/cache/clear'] = array(
  'title' => 'Empty cache',
  'page callback' => 'devel_cache_clear',
  'description' => 'Clear the CSS cache and all database cache tables which store page, node, theme and variable caches.',
  'access arguments' => array('access devel information'),
  'menu_name' => 'devel',
);


How do I create a filter based on the current user's role in a search_api based view?

Thanks to @prkos reminding me that this is a regular node access setup issue. This was solved when I found this issue in the search_api queue about incompatibility with "View All Unpublshed content"


Is there a way to alter a form, implemented by another module, using a class?

Drupal core code still uses hook_form_alter() (or hook_form_BASE_FORM_ID_alter(), or hook_form_FORM_ID_alter()) for that purpose.
You could alter a route and change the form associated with that route, but this would mean that:

You would need to keep track of the form class that was associated to that route before you changed it; in this way, you would be able to let the previous class add its own form fields
You would need to alter all the routes using that form class, in order to make Drupal use your class

The closer I could see used from Drupal code, which means the code would be in a class, is what the Content moderation module does in content_moderation_form_alter().

function content_moderation_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  \Drupal::service('class_resolver')
    ->getInstanceFromDefinition(EntityTypeInfo::class)
    ->formAlter($form, $form_state, $form_id);
}

Using that, you have the pro of using object-oriented code, allow other modules to extend the same form without complicating your code, and without interfering with code used from other modules.

Since the Drupal API page doesn't link the EntityTypeInfo class, it's the class defined in core/modules/content_moderation/src/EntityTypeInfo.php.

The relevant code is the following one, which shows how a class method is used as form submission handler.

  /**
   * Alters bundle forms to enforce revision handling.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param string $form_id
   *   The form id.
   *
   * @see hook_form_alter()
   */
  public function formAlter(array &$form, FormStateInterface $form_state, $form_id) {
    $form_object = $form_state->getFormObject();
    if ($form_object instanceof BundleEntityFormBase) {
      $type = $form_object->getEntity()->getEntityType();
      if ($this->moderationInfo->canModerateEntitiesOfEntityType($type)) {
        $this->entityTypeManager->getHandler($type->getBundleOf(), 'moderation')->enforceRevisionsBundleFormAlter($form, $form_state, $form_id);
      }
    }
    elseif ($form_object instanceof ContentEntityFormInterface) {
      $entity = $form_object->getEntity();
      if ($this->moderationInfo->isModeratedEntity($entity)) {
        $this->entityTypeManager
          ->getHandler($entity->getEntityTypeId(), 'moderation')
          ->enforceRevisionsEntityFormAlter($form, $form_state, $form_id);
        // Submit handler to redirect to the latest version, if available.
        $form['actions']['submit']['#submit'][] = [EntityTypeInfo::class, 'bundleFormRedirect'];
      }
    }
  }

This is the form submission handler that method is using.

  /**
   * Redirect content entity edit forms on save, if there is a forward revision.
   *
   * When saving their changes, editors should see those changes displayed on
   * the next page.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public static function bundleFormRedirect(array &$form, FormStateInterface $form_state) {
    /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_state->getFormObject()->getEntity();

    $moderation_info = \Drupal::getContainer()->get('content_moderation.moderation_information');
    if ($moderation_info->hasForwardRevision($entity) && $entity->hasLinkTemplate('latest-version')) {
      $entity_type_id = $entity->getEntityTypeId();
      $form_state->setRedirect("entity.$entity_type_id.latest_version", [$entity_type_id => $entity->id()]);
    }
  }

As you see, it's not the same as extending FormBase, but it's more OOP than using plain functions.


Removing the upload button in managed files

The work to separate out the managed_file element is done in file_managed_file_process(), which is the default #process function for that type of element.

To hide the upload button you need to implement your own simple #process function for the element:

function MYMODULE_my_form($form, &$form_state) {
  $form['image'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#upload_location' => 'public://my-files/',
    '#process' => array('MYMODULE_my_file_element_process')
  );

  return $form;
}

function MYMODULE_my_file_element_process($element, &$form_state, $form) {
  $element = file_managed_file_process($element, $form_state, $form);
  $element['upload_button']['#access'] = FALSE;
  return $element;
}


Create user programatically after e-mail verification

you don't get private keys from the database because Drupal doesn't store them.

try looking up in settings.php for the $drupal_hash_salt variable. that's the one used to encode/decode strings.

hope this helps.

cheers


Copied from BlockContent::postSave():

// Invalidate the block cache to update custom block-based derivatives.
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();


There is a Quiz module, that looks awesome: https://www.drupal.org/project/quiz

The Quiz module lets you create graded assessments in Drupal. A Quiz
is given as a series of questions. Answers are then stored in the
database. Scores and results are displayed during or after the quiz.

A simpler option might be the Peekaboo module: https://www.drupal.org/project/peekaboo

Use cases: ... Fields that reveal more information
Peekaboo can also be used purely for the Ajax functionality as a gimmick to reveal more information.


How to rebuild images using Imagemagick?

This issue sometimes occurs when the original files are too large, causing memory exhaustion on the server during thumbnail creation.  Since the thumbnail creation on an image style cache flush is generated in a serial queue, just one high res image can prevent all the other image style thumbnails from being generated.

Steps to check and attempt to resolve this include:

After immediately trying to reset/flush the image style cache, check your apache and php logs on the server itself (as the memory exhaustion errors don't typically appear in the Drupal watchdog logs).
If you in fact encounter the memory exhaustion error, try increasing the server's memory limit.  See https://stackoverflow.com/questions/3534274/php-memory-exhausted
If after bumping the memory limit you continue to encounter this error, spot check some of the original images- determine the actual pixel dimensions of each image as well as the pixel density and/or dpi.  If either is significantly large, you may want to download the original images, batch process/resave at a more reasonable size, and upload back to the server; then trigger the image style flush/thumbnail regeneration again.
If #3 resolves the issue, you may want to apply max width/height to the image upload field config itself to prevent content managers from uploading enormous images in the future too. Note: Depending on your settings, this approach may result in saving a downsized version of the original image, if the original image exceeds maximum dimensions; or result in a warning to the content manager prompting them to upload a smaller image.
In conjunction with the max width & height options, you may also want to change the jpeg quality of the images generated for the image styles.  While signed in as an admin, go to Configuration > Media > Image Toolkit (/admin/config/media/image-toolkit)


Can there be content sent the a vanilla Drupal 8 sites' views that isn't a node?

You don't import things into a View; you configure a View with certain criteria, and that basically runs a query against the database, the results of which are formatted and rendered according to the rest of the View config.

It's not restricted to nodes, many entity types and pseudo-entity types can be queried, as Views is very extensible.

You mention importing xml into views - in reality that happens by 2 separate processes - importing XML and creating content/entities from it, then setting up a View to display that content.

Don't think of a View as a container. It's essentially a sophisticated HTML report builder that knows how to get and format Drupal data.


How to remove "site email address on behalf of" and just keep the sender email address in "from:" part of a mail from drupal 7

Well you can write a simple module, and in your module insert this function. Here is where i got the idea

function yourmodule_mail_alter(&$message)
{
    $message['headers']['Sender'] = $message['headers']['From'];
}

If you want to go with quick sketch comment, in the link to completely get rid of the headers use

<?php
function mymodule_mail_alter(&$message) {
  unset($message['headers']['Sender']);
  unset($message['headers']['Errors-To']);
  unset($message['headers']['Return-Path']);
}
?>

There is also a module that can help out with this mail headers

  Control and modify any (almost any) mail header. Mail Headers allows
  you to:


Yes.

Go to the pane where you want the logo or site name. Click on the 'Add content' gear wheel and then you'll find the site name and logo under the 'Page elements' section.


kpr() in my form validation and submit function is not being called

Everything that is output with drupal_set_message() (the function that kpr() uses to output the message) could not be visible from the browser if code redirects the user to another page after drupal_set_message() is called and before the page is rendered. After a form is submitted, the users are redirected to a page whose URL is set in $form_state['redirect'] or $_GET['destination']; the latter takes the precedence over the former.
To avoid the users are redirected after the form is submitted, you can:

Set $form_state['rebuild'] to TRUE
Set $form_state['redirect'] to FALSE

Setting $form_state['no_redirect'] to TRUE would have the same effect, but form builder functions, form validation handlers, and form submission handlers should never set $form_state['no_redirect'].

A preferred method would be calling watchdog(). If you have the Database Logging module enable, then the message output from the module will be visible in admin/reports/dblog.

For debugging messages, you can call watchdog() passing WATCHDOG_DEBUG as value for the $severity parameter.

References

drupal_redirect_form()


The submodule 'Organic groups field access' of the OG project should be able to help you manage file access based on Organic Group permissions.

You can create private Organic Groups by enabling the OG submodule 'Organic groups access control'.

Depending on the useless: Make sure to add a 'Group visibility' field to the Group bundle or a Group Content visibility to the group content bundle at admin/config/group/fields.


How to display a View Block based on number of characters in Body?

You can use the Views Conditional module. Configure your field to Exclude from display and Apply

Then add the Views: Views Conditional field and configure like this (but with your condition) and Apply

EDIT (after No Sssweat comment):You can combine in your view the Views Field View module to embed a view (your block if you want) as a field in the view.


The errors output to Apache are often somewhat cryptic.

You probably want to check the Drupal Reports page, dblog, and the Apache logs.

This sounds like one of the new updates has a problem in the .install or cannot be loaded (permission problems, although that comes proper from Drupal, I never had that problem on an upgrade.)

To test whether the PHP code is invalid, you can run

 php <filename>

The update.php will generate some errors, but it should not tell you it cannot parse it. All the module .install should not generate any errors (a very few modules have code outside functions and those will generate errors, but again no syntax error.) Those syntax error are reported by Apache.


Query custom node by user Entity Reference

The column name for an entity reference field is target_id, so your code should be:

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node', '=')
  ->fieldCondition('field_marketer', 'target_id', $user->uid, '=');

$entities = $query->execute();


Drupal files folder owner/group for CentOS?

I faced with this issue before, it was because of SELinux on CentOS, So you should try to Disable SELinux on Centos

  From the command line, you can edit the /etc/sysconfig/selinux file.
  This file is a symlink to /etc/selinux/config. The configuration file
  is self-explanatory. Changing the value of SELINUX or SELINUXTYPE
  changes the state of SELinux and the name of the policy to be used the
  next time the system boots.

[root@host2a ~]# cat /etc/sysconfig/selinux
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#       enforcing - SELinux security policy is enforced.
#       permissive - SELinux prints warnings instead of enforcing.
#       disabled - SELinux is fully disabled.
SELINUX=permissive
# SELINUXTYPE= type of policy in use. Possible values are:
#       targeted - Only targeted network daemons are protected.
#       strict - Full SELinux protection.
SELINUXTYPE=targeted

# SETLOCALDEFS= Check local definition changes
SETLOCALDEFS=0

Change it from SELINUX=permissive to SELINUX=disabled

Once you have saved the changes sudo shutdown -r now to restart now.

Also you can disable it temporary ( until next restarting ) with

sudo setenforce 0

How to Disable SELinux


How to find the values that have changed in a form submission?

What I have done is to see if the value in $form_state['values'] is different from the #default_value in $form, like so:

if ( $form_state['values']['variable'] <> $form['variable']['#default_value'] ) { ... }


How to add javascript after form was validated with ajax callback?

If you only want to add a JS file in validate or Ajax handler function you just need to add JS to form with drupal_add_js or attach it to form.

This is an example of how can you add JavaScript in Ajax callback function:

function my_form_callback(&$form,$form_state){
if(some validation ){
$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);
}
return $form;
}


How to get the $form_state in hook form submit?

If you only need nid of node comment is being inserted inside and uid of comment author then use these codes :

nid exist in : $form_state ['values']['nid']

you can even load node if you need more info about it using :

$node = node_load($form_state ['values']['nid']);

to get info about author use : $form_state ['values']['uid']

if user is anonymous this returns 0


How to delete a vocabulary terms programmatically?

$tids = \Drupal::entityQuery('taxonomy_term')
    ->condition('vid', 'mycustomvocab')
    ->execute();

  $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
  $entities = $controller->loadMultiple($tids);
  $controller->delete($entities);


Controlling the display order of custom field sets that are shown both in a webform and in CiviCRM, via the webform_civicrm integration module

This bug was resolved in CiviCRM 4.5.2, the relevant issue was CRM-15435: Case ActivityView popups do not respect custom group weights.


How to write a Drush script to retrieve data?

You can start checking the code of the Drush Entity module.

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

And as Greg says you can use the Drushify module to start.

In this links you can find good references:

How to Create Your Own Drush Command
How to write drush commands and hooks
Drush Integration for your modules


I would have caught this question if you posted a support request ticket it in the module's issue queue.

The information in the post you are referring to is outdated. When using the newest version of the 3.x branch, you can define variants easily in the UI accessible under admin/config/search/simplesitemap/variants.

A variant is a sitemap instance of a particular sitemap type. When creating a variant, you can reference existing sitemap types or write your own by adding a sitemap type plugin which references URL and sitemap generator plugins.

Simple XML sitemap is heavily relying on the plugin architecture as opposed to hook architecture. Hence most of the time you would use the module's API service methods or write plugins inside of a custom module. There is still a couple of alter hooks remaining for convenience.

The 3.x branch has a release candidate which is very stable. You can read all about it in this blog post.


Given a form, how do I find the fields present in them?

go to your template "template.php for example" or your module, and use

hook_form_alter(&$form, &$form_state, $form_id){
  var_dump($form);exit();
}

and you will get very detailed look at your form


Where does views's template files get saved?

Where should I place any view template so that it can effect all views
  of specific content type like "Article".

While you can do this with nodes, I don't believe it's possible on views to affect all views of x content type. As you can see in FILTERS, there is a Type filter (=Article). It's just a filter.

The best option you have is to make it affect a specific view name and a view display.

EX: views-view-grid--[view-name].html.twig

if you want to specify a display then views-view-grid--[view-name]--[machine-name].html.twig

Then you copy the code from core's views-view-grid.html and paste it on your template file and modify as you wish.

If you want to alter fields, then use views-view-fields--[view-name]--[machine-name].html.twig

You place your custom template files in /themes/[Your Theme]/templates folder.


Define an auxiliary content type (say MyPoll).

I added a Node reference CCK field to standard Poll and a CCK Node Referrers (backreference) field to MyPoll. You can then easily create one (or even more!) polls as "children" of your MyPoll node, and attach their teaser content (the voting widget) to the MyPoll node.

As MyPoll is a "standard" content type, you can do whatever you want with it in views... including the display of the referred poll widgets. It's not straightforward...

I was inspired by http://www.lullabot.com/articles/photo-galleries-views-attach. Look at it this way: "galleries" are "mypolls", and "images" are "polls".


Clearing cache failed to add the new CSS properties

Your Drupal is not able to write inside DRUPAL_ROOT/sites/*/files/css directory. That's why aggregated CSS files are not renewed. Consult your sysadmin to correct permissions and allow Drupal full write access inside DRUPAL_ROOT/sites/*/files and all subdirectories, that should solve it.


How to programmatically modify fields of taxonomy terms?

The column name for a field isn't always value; in the case of taxonomy term references it's tid, and in the case of node/entity references it depends on what module you're using.

For a field created using the References module the name is nid, and for one created using the Entity Reference module, it's target_id.

The following code should work a bit better:

//hook_node_insert fires after new node has been inserted into db
function MYMODULE_node_insert($node)
{
    $taxonomy_term_id = $node->field_FRUIT[LANGUAGE_NONE][0]['tid'];

    // $value['tid'] isn't defined anywhere in this function scope so I
    // assume you meant to use $taxonomy_term_id here
    $taxonomy_term = taxonomy_term_load($taxonomy_term_id);
    if($taxonomy_term != FALSE)
    {
        $column_name = 'nid'; // Or 'target_id' if you're using entity reference

        $taxonomy_term->field_main_article_id[LANGUAGE_NONE][0][$column_name] = $node->nid;
        taxonomy_term_save($taxonomy_term);
    }
}


Cannot Find CSS Class For A Custom Block

You don't have a class, but you do have an ID so you can use:

#primary p {color:red;}

Note: there is also a nice module call block class (http://drupal.org/project/block_class) that you can use


You can look at the Quiz module. It also has an active Drupal Group :)

  The Quiz module provides tools for authoring and administering quizzes through Drupal. A quiz is given as a series of questions, with only one question appearing per page. Scores are then stored in the database.

  This module provides tools for

  Online courses (Audio and Video enabled)
  Self-learning programs
  Training programs
  Supplementary classroom activites


The Statistics module shows you how often a given page is viewed, who
  viewed it, the previous page the user visited (referrer URL), and when
  it was viewed.

  In Drupal 7 configure statistics via configuration > statistics.

  To enable collection of statistics, the Enable access log checkbox on
  the Statistics settings page must be checked.

  Enable Count content views to turn on and off the node-counting
  functionality. If turned on, an extra database
  query is added for each node displayed, which increments a counter.

Make sure you set permissions for the module at admin/user/permissions and configure it.

Based on drupal.org and http://groups.drupal.org/node/147619


How do I query a MySQL view in Drupal 7?

I don't think it's possible to query views using the DBTNG query builder: if you try to use db_select() with a view, it raises a PDOException complaining that the table doesn't exist.

Instead, you'll want to use db_query(). Let's assume you created a view named test:

CREATE VIEW test AS SELECT * FROM variable;

To get the value of cron_key, you'd do:

$name = 'cron_key';
$result = db_query('SELECT * FROM test t WHERE t.name = :name', array(':name' => $name));
$value = $result->fetchColumn(1);

The comment by drclaw on the db_query() API entry gives a number of examples which should help you out with figuring out how to manipulate a SELECT query using db_query().


After reading your question I would do the following:

Create a custom module with a custom block that holds the booking form. This way you can add the booking form on whatever page you like with the Context module for example.

The Drupal 7 example module can show and teach you how to create a block in a custom module.


Give user empty form on form validation error

I was able to unset the value from within the form validation function. In my case the element is named foo and it only validates if it's set to bar:

function mymodule_myform_validate($form, &$form_state) {
  if ($form_state['input']['foo'] != 'bar') {
    unset($form_state['complete form']['foo']['#value']);
    form_error($form['foo'], 'foo is not equal to bar');
  }
}

If the user enters anything but bar in foo, we set a form error and they presented with the form again without anything in the foo field.

I'm not sure how/if the form state array is affected by, for example, the i18n or locale modules, but this should get you started.


How can I add a field to a view description

I don't know that it will provide all the functionality you are looking for, but you could look into Views Field View:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Hard to tell which plugin is missing. A guess would be it is a missing field widget plugin which causes the error when you try to add a new field to the default form mode. Then change the plugin name to something like this:

  ->setDisplayOptions('form', [
    'type' => 'datetime_default',

If this is not the error, then provide a full error message with a backtrace.


How do I change the currency display from USD to $?

You could try

hook_commerce_currency_info_alter

For example,

function EXAMPLE_commerce_currency_info_alter(&$currencies, $langcode) {
    $currencies['USD']['symbol'] = '$';
    $currencies['USD']['symbol_placement'] = 'before';
    $currencies['USD']['code_placement'] = '';
}

See commerce_commerce_currency_info for the default currency info implementation.


Clearing the cache the menu and routing tables will be reconstructed.

In the admin UI, go to:

/admin/config/development/performance

Using drush:

drush cache-clear all

Other methods are described here: How do I call the menu_rebuild function in Drupal 7?


I suppose you have tried to use drupal_get_messages() within hook_mail_alter() as well?

The reason it probably did not return a value is because the default behavior or drupal_get_messages() is to clear the message queue (so it empty the second time). You can however make it persistent by passing FALSE as a second parameter (see the documentation).

So in your hook_form_alter() use drupal_get_messages(NULL, FALSE) and then you should be able to use it again in hook_mail_alter().


Why would single-use (harcoded) tokens not validate in the Message module, when the dynamic version does?

Provided you're using Rules to send the message, i'll suggest you to manually save the message entity after having set all required fields but right before sending the message.

Single Use token are evaluated at save time.


How can I place $content in search results instead of $snippet?

Define yourtheme_preprocess_search_result in your theme's template.php file. Do something like this:

function yourtheme_preprocess_search_result(&$variables) {
  //$variables['result']['node'] should contain the entire node object
  $variables['content'] = $variables['result']['node']->body[LANGUAGE_NONE][0]['value'];
}

You should be able to use the variable $content inside search-result.tpl.php now.


How to calculate number of submitted webforms?

Another option would be to use Views to create a view of webform submissions, and display the count from that.


Programmatically set class on extended field type

This is untested, but I'm pretty sure you just need to change the list class for the field types using hook_field_info_alter():

function ablecore_field_info_alter(&$info) {
  foreach ($info as &$field) {
    if ($field['list_class'] == '\Drupal\file\Plugin\Field\FieldType\FileFieldItemList') {
      $field['list_class'] = '\Drupal\ablecore\Plugin\Field\FieldType\AbleFileFieldItemList';
    }
  }
}


OP asks for D6. For D6 make sure you have the latest version of the date and the views module. Older versions have a bug that tends to "forget" the sort part of the SQL statement.


How to load a library only once, or how to check if a library has been loaded?

EDIT: Sorry didn't see you were doing it via AJAX, my below example might not be the same. But the theory of the JS triggering multiple times rather than the actual files loading might still be valid

I don't think it's the piece of code you've showed is causing your issue. Is the  library files definitely getting loaded multiple times into the source code? Or is it that the effects of the library are happening multiple times? (e.g. a JS being trgiggered multiple times) as thats a different issue

Drupal handles this situation and when it aggregates all the required libraries so any duplicates are removed. For example I'm just working on a news listing page that has 10 nodes coming out and just replicated your code to print "hi" add a library and the "hi" comes out 10 times but the library files only once


Views - Conditionally rewrite title link attribute based on field empty value

From what I understand, either the "Link" OR the "File Attachment" fields will be filled in, but never both. If that is correct the solution is pretty simple.

You need to "Exclude from view" the title field.

Then, you need to Rewrite both the File Attachment and Link fields via the "Rewrite the output of this field" and put the [title] (or wahtever the field name is) in the rewrite field.

Then also for each of those 2 fields, check the "Output as link" and put the link field into the link path for the link, and put the file attachment field into the link path for the file attachment.

Now you only need to open the "No Results Behavior" fieldset for each of those fields and check "Hide if Empty" and "Hide rewriting if empty".

Now either one or the other will be output with the title as a link to either the page or the file attachment depending on what you filled in on the node edit screen.


HTTPS and SecurePages Infinite Redirect - How do I reset which pages are always HTTPS?

I pulled this directly from the README.txt of the module.

  Configuration

  Generally on test/development servers you do not have access to SSL,
  so  generally you would like to disable secure pages on these systems.

  To do this add the following to your settings.php

  $conf['securepages_enable'] = 0;

  Removal of SecurePages

  In the case where your SSL mode has been disabled and you can no
  longer access the administration section of your site to disable
  securepages you can do one of the 2 following things.

  Use the above method to disable securepages.
  delete the secure pages module from your site.

  If you can use the first option but if you can't edit your
  settings.php then deleting it will not break your site, but will leave
  some variables that are set by secure pages.


How can i remove required field validation on click submit button?

In the form_alter function you can use the limit_validation_errors property.

'#limit_validation_errors' => array(),

The above code will not perform any field validations. You can then add the individual fields that you need to validate here using the below code.

$form['actions']['next']['#limit_validation_errors'][] = array($field_key);

Where next is the action that I am using.


I recommend the theming chapter by @jacine in Definitive Guide to Drupal 7 - http://definitivedrupal.org/. Not free but well worth it.


Code inside attached behavior not executed

Drupal disables the $ namespace for jQuery, to avoid potential conflicts with other libraries. Therefore the wrapping $() DOM-ready-function will neither be executed, nor can the $('#something') selector be used inside. Wrap your behavior with this instead:

(function ($, Drupal) {
  //inside the wrapper you can use the usual jQuery $ notation
  Drupal.behaviors.block_sidebar_register_buttons = {
    attach: function (context, settings) {
      var element = $('#block_register_buttons');
      //...
   }
  }
}(jQuery, Drupal));


Save values after add more ajax in form api - field name issue

I was having problems with the fieldset, since it was set to #tree. The submit handler should look like this:

function main_form_form_submit($form, &$form_state) {
  $film_id = db_insert('film_main')
  ->fields(array(
     'film_title' => $form_state['values']['film_title'],
     'film_title_1' => $form_state['values']['add_title'][1]['main_film_tab']['film_title_1'],
     'film_title_2' => $form_state['values']['add_title'][2]['main_film_tab']['film_title_2'],
     ))
 ->execute();


You must include at least one positive keyword with 3 characters or more

The search module is a little weird in Drupal, and can take some time to wrap your brain around.  If you start reading from node_search(), you will see a call to do_search() which is the function that links the search indexes to the things you are searching over.

If you read that function, you will see that there is a variable minimum_word_size, that defaults to 3.  If you need to be able to search on smaller words, you need to set this smaller.  I believe you can set this on 'admin/settings/search', but I don't have any Drupal 6 sites to check against.

Change this value, then wipe the search index and rebuild it.  These last two steps are most easily accomplished with Drush.


field_groups - adding an inner div wrapper programatically

It is strange that this has changed and I can't really find any posts relating to it.

I'm going to update my code to use hook_field_group_build_pre_render_alter() as an alternative.


Displaying one node for each unique field reference in View (e.g. one videogame for each developer)

UPDATE:

This unfortunately only works if your developers were users. After reading your question again, it appears you have created them as content, in which case my answer does not work.

Views has a built-in feature for this called 'Representative node'. This can be used to

  Obtains a single representative node for each user, according to a
  chosen sort criterion.

So how to use this:

Start off by creating a view that lists users and add the Representative node relationship (in the advanced section).
Configure the selection criteria; in your case this would be 'Content: Authored on'.

This adds a relationship to Views, allowing you to add fields to the view.
If you want to show the rendered node instead of individual fields, add the Rendered entity field instead:

No need for aggregation.

Do note that this will always fetch the last node the user has created of every content type. You should add additional filters to the view to limit this to game-nodes, etc.


Views: How to display the title and breadcrumb from taxonomy terms in URL?

By default, taxonomy terms default view is disabled so you can enable it and see how it is working with the contextual filter.

You need to Configure contextual filter: Content: Has taxonomy term ID (with depth)


Change individual file from public to private and vice-versa

I've written an update script to switch a file field from private to public:

function MYMODULE_update_7100(&$sandbox) {
  $field_name = 'MY_FIELD_NAME';

  $fids_data = db_select('field_data_' . $field_name, 'dat')
    ->fields('dat', array($field_name . '_fid'))
    ->execute()
    ->fetchCol();

  $fids_revision = db_select('field_revision_' . $field_name, 'rev')
    ->fields('rev', array($field_name . '_fid'))
    ->execute()
    ->fetchCol();

  $fids = array_unique(array_merge($fids_data, $fids_revision));

  // Move files using Drupal's File API
  $files = file_load_multiple($fids);
  foreach ($files as $file) {
    if ($file && file_exists($file->uri)) {
      $destination = str_replace('private:', 'public:', $file->uri);
      $directory = drupal_dirname($destination);
      if (file_prepare_directory($directory, FILE_CREATE_DIRECTORY|FILE_MODIFY_PERMISSIONS)) {
        file_move($file, $destination, FILE_EXISTS_RENAME);
      }
    }
  }

  // Update field configuration
  $field = field_info_field($field_name);
  $field['settings']['uri_scheme'] = 'public';
  field_update_field($field);
}

What this function simply does:

Gets the fid of all files from field_data and field_revision tables.
Moves files using File API
Updates field configuration


Using 'return' with an ajax callback renders an entire page before my content is loaded

You are missing the Drupal settings that include the Ajax settings, which is why the server doesn't know it should be ajaxified. You should (may) be able to fix it by changing this:

$content .= '
';
print $content;

To this:

$content .= '
';
$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
    $settings = '';
}

print $content . $settings;
drupal_exit();


The error has nothing to do with the Advanced Forum module, the error is coming from the IP address manager module. From it's error message, it looks like it's trying to insert a record that already exists. It could be a problem with how you upgraded that module (your dir suggests its version 1.4, but the line number matches the latest 2.0-beta) or it could be a bug.

Either way, if you're not concerned with preserving historical data in the module, uninstalling, removing, and reinstalling the IP address manager module would be one way to get rid of the error.


how to create all dynamic ubercart product images for CDN module to sync

This worked with the following setting in default/settings.php file

$conf['image_allow_insecure_derivatives'] = TRUE;


First off, you should not call drush.php directly; use the drush script instead.

Regarding site selection, Drupal looks up the site to use based on the domain name in the http request, which is passed in via the HTTP headers.  When you are using Drush, there is no web browser involved, so Drush needs to generate equivalent HTTP headers and select the appropriate site based on information that is provided either explicitly (via commandline options) or implicitly (via the current working directory).

If your cwd is inside your Drupal root, then Drush will, by default, look for the settings.php file inside the 'default' folder.  You can change this default by setting your cwd to the folder that contains the settings.php file that you want, or by passing in --uri=mydrupalsite.com as a commandline option (or -l mydrupalsite.com).  You might also want to read up on Drupal site aliases, which are an even more convenient way to tell Drush which Drupal site you'd like to use with your command.


Get field value directly from inside views-view-list.tpl.php

took me a while to work this out so sharing the solution i used.

<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_field_name', $id);?>
<?php endforeach; ?>

<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_second_field_name', $id);?>
<?php endforeach; ?>


Or you can create a new text field for embed flash. Be sure that your WYSIWYG filter will allow the embed and object tags.


How to get Taxonomy Term Field Value in twig

To get the url of your term reference image inside the node twig try:

node.field_color_term.0.entity.field_color_image.entity.uri.0.value

Change field_color_term by your field name.

There is another way by configuring the display of your content type and your term like the following:

Content type display should be like

Taxonomy term display should be like

After this configuration you can render your field type of Taxonomy term, it will show the image:

{{ content.field_YOURFIELDNAME }}


The list of nodes listed in the homepage by default is from the Frontpage(/admin/structure/views/view/frontpage) view. If you'll go to that view, you'll notice on the FORMAT section, under Show, the value is "Content | Teaser". This means that the each node displayed is using a specific View Mode called "Teaser".
Next is to enable twig debugging.  Once that's done and you check the homepage's markup, specifically on one of the article listings, you'll see this:

Notice that I'm highlighting one "article teaser" and on the markup you'll see a list of file names i.e. node.html.twig, node--teaser.html.twig and etc. and the one with the "x" is the default template that is being used.If none of the other files are found then Drupal always goes to the base template which in this case is node.html.twig. So if Drupal matches a theme suggestion in the list to a physical file on your theme, that's what it will use.
With those information, you can go to the current template file using the file path(core/themes/bartik/template/node.html.twig), copy it into your custom theme, rename it as node--teaser.html.twig, do some random edits for initial testing, clear the cache and then visit the homepage again.
You should see that the "x" under "FILE NAME SUGGESTIONS" will now be beside node--teaser.html.twig and your changes to the file as well.


There's a contrib module, contentaccess which is fairly easy to use and permissions can be managed on a node by node basis.

There's a good article about Drupal content access control here


Sounds to me like you just have to add an URL alias for ´portfolio/4´.

Go to Configuration > Search and metadata > URL aliases.
Click "Add alias".
Enter portfolio/4 as "Existing system path" and branch-locator as "Path alias".
Hit Save and it should be ok.

If you want nodes to have a similar path alias, e.g. branch-locator/node-title, you should look into the Pathauto module.

Cheers,


Presuming CCK=>Drupal 6, and without writing a custom module or custom compound CCK type, you could do something like this:

Create a cck content type, let's call it album_image, and in it have the following fields:

a.  Image field
b.  text field for title
c.  text area for description
Allow your users to create/edit these content types and fields via permissions
Create a view that returns all album_images created by the logged in user
Add a node reference field to the user's profile (The Content Profile module is an easy way to do this) and restrict it to one result, and call it for discussion here default_image.
Within CCK screens for the field above, use the view you created above to populate the "returned values" for the node reference instead of just selecting a content type.
Now, when your user edits his or her profile, they can select one album_image as the one they want displayed.

Now within your user profiles you have a field called field_default_image that contains the nid of the album_image your user wants to have displayed on his or her profile, so you can then load that up to get the image and use that wherever you need, eg, within whatever preprocess functions you use within your theme to paint the profile.


How to change the user profile edit page?

You can add new fields to the users profile page at admin/config/people/accounts/fields

You can also manipulate the form by implementing hook_form_user_profile_form_alter(&$form, &$form_state, $form_id) and hook_form_user_register_form_alter(&$form, &$form_state, $form_id)

To add new profile pages you can use the Profile 2 module.

You can also edit the user edit template by implementing hook_theme().


The field_data_field_name_first field had some data stored in it for that user ID, apparently because it was migrated in at a later time than the user table or because I didn't drop the database before I imported new data. As a result, the system couldn't write to the database user table and field_data_field_name_first table. The solution was to do a fresh import of the user table and the first and last name custom fields.

This was on a test site.


What are the modules / pages / panels / or other features in Drupal which can be used to display an object which is made up of several content types?

what's the best way to...

That is subjective. Here is a way to do it, not necessarily the best:

Views Megarow

  This module allows you to display content coming from a menu callback
  between two items of a views result set as a modal-like. You can use
  it to display a preview of your node or to build an administrative
  form.

  Said otherwise, you can dynamically display content below a row of a
  table of results coming from a view. This content is shown when you
  click on a link, it means that you can display anything from a preview
  of your node for instance to a moderation form of an entity.


Scheduler module not working even after cron run

Step: 1. First of all u have to uncheck the published node content types..

Then u have to set the schedular time for particular node

Then U can use Rules module to publish.


Why is this code using the global $user variable?

The code is not really using the global $user variable. Probably, the code was first using it, and that line has been left; it could also be the code using it was moved in mycaptcha_ask_form_validate().

As that line is just a variable declaration, there is no problem in leaving it, even if I generally remove it.


Filter values of a cck field with a view

If you want to show the latest 3:

Set the Fields you want to display, most likely Node: Title
Under Basic Settings set the limit to "3"
Add a Sort Criteria Node: Post date - ascending
Other Filters you'll want to add are: Node: Published - Yes & Node: Type

Hope this helps!


Drupal Commerce product sale price using Rules

I found the right way to do this: In the rule action I used Set the unit price to a specific amount instead of Set a data value.


Unfortunately I wasn't able to solve this issue, so I did a little bit of a work around.

What I did was built a content type where the user could specify what data he/she needed by use of a form and fields.

I then took the user input and built a dynamic sql query to output the required data.

Its a pretty dirty way of doing it... but until I find another solution, I'll have to use it.


Commerce Product with diffrent prices for different shops

To resolve the product display <-> product issue, I'd be using Inline Entity Form to embed the product form right into the product display node form. However, that doesn't address your need to have hundreds of unique prices corresponding to different physical locations. That's another issue entirely that we would typically refer to as pricelist functionality.

We do have a Commerce Pricelist module, but since "Store" wasn't a core entity type in Drupal 7, there is no pricelist variant correlating to a store. You'll likely need to enhance that module yourself to make it "simple" for end users. Other options would be dependent on your greater site IA ... and it's worth noting that store based product availability and pricing would be better suited to Drupal 8 if there's any chance at all at upgrading.


How can I upload multiple images all at once?

See the Plupload integration module. From the project page:

  Provides integration between for the Plupload widget to upload
  multiple files and Drupal. Plupload is a GPL licensed multiple file
  uploading tool that can present widgets in Flash, Gears, HTML 5,
  Silverlight, BrowserPlus, and HTML4 depending on the capabilities of
  the client computer.


Close a webform when total seats reach a maximum

I built a custom handler to process seat reservations. I just wanted to share my code for anyone else looking to do the same thing. @jrockowitz let me know if you want to add this into webform core.

<?php
namespace Drupal\webform_reservations\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
* Form submission handler.
*
* @WebformHandler(
* id = "webform_reservations_handler",
* label = @Translation("Reservations Handler"),
* category = @Translation("Form Handler"),
* description = @Translation("Manage maximum seat reservations"),
* cardinality =
 \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
* results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
* )
*/

class ReservationHandler extends WebformHandlerBase {

 /**
 * {@inheritdoc}
 */

  public function submitForm(array &$form, FormStateInterface $form_state,
  WebformSubmissionInterface $webform_submission) {
  $webform = $webform_submission->getWebform();
  $formid = $webform->id();

//query the db for all submissions of current webform submission
$query = \Drupal::entityQuery('webform_submission');
$query->condition('webform_id', $formid);
$result = $query->execute();

//load all the submissions from the results
$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $storage->loadMultiple($result);
$submission_data = array();

foreach ($submissions as $submission) {
$submission_data[] = $submission->getData();
}

$current_reserved = 0;

//add up all the values in the 'seats needed' field of each submission and save it to a variable.
for ($i = 0; $i < count($submission_data); $i++){
    $current_reserved += $submission_data[$i]['seats_needed'];
}

//when a registration form is submitted, check if the current reserved seats exceeds the value specifed in the maximum allowed seats field of the form.
if ($current_reserved >= $webform->getElement('max_seats')['#value']) {
    $webform->setStatus('closed');
    $webform->save();

 $message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ' the form will now be closed';
  } else {$message = 'The form has ' . $current_reserved . ' reserved seats, the max seats is currently set to ' . $webform->getElement('max_seats')['#value'] .  ', the form will stay open';}

//log the output to the drupal logger, to indicate if the webform is still open or closed after each submission.
\Drupal::logger('webform_reservations')->info($message);

}
}
?>


How to  redirect the user to a  page and show a message on the admin overlay (using drupal_set_message and drupal_goto)

I don't think this is possible with the current message system, it would require some crazy workaround do make it work anyways.

The problem is that when you use drupal_set_message(), the message is stored in the session variable and displayed whenever possible. When you redirect to a page with an overlay two things happens.

The main page is rendered and displayed.
The overlay page is rendered and displayed (with an iframe).

This means that whatever message you set, would always be displayed on the main page.

What you could do, is when the messages has been extracted to set them again and remove them. This could happen in your theme somewhere. The problem is that it is probably very hard to determine when you should do this, as you effectively would hide all messages if you always did this. Another side effect would be that you would constantly get more and more messages, possibly leading to a fatal memory error at worse.


You need to get the current request object first:

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

Or

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


How to add Wishlist button field in views in drupal 7?

Most straightforward way is to use views to render your product display nodes. Instead of "fields" choose "node" and then choose your display mode. Perhaps use display_suite or panels to get more advanced control over what your products look like when rendered.

Sidenote, there's a great video I created that shows you how to use hook_form_alter to move the wishlist button around.


How do I programmatically add text to a page?

You're looking for the page callback, which is:

  The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

For example:

function sky_view_menu() {
  $items['admin/skyview'] = array(
    'title' => 'Skyview Settings',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'page callback' => 'MYMODULE_skyview_admin_page',
  );

  $items['admin/skyview/tab1'] = array(
    'title' => 'Skyview',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'access callback' => TRUE,
    'weight' => 0,
    'page callback' => 'MYMODULE_skyview_admin_tab_1',
  );
  ...
  return $items;
}

function MYMODULE_skyview_admin_page() {
  return [
    '#markup' => t('Hello world'),
  ];
}

function MYMODULE_skyview_admin_tab_1() {
  return [
    '#markup' => t('Hello tab 1'),
  ];
}

The function name itself is arbitrary, but for the sake of sanity it's best to name it as something that represents the route behind it.


Whenever I'm stuck in a module, or a context that path_to_theme() doesn't return what I'd like - I use the following to access the current globally selected theme.

global $theme;
$path_to_theme = drupal_get_path('theme',$theme);

For instance if I am in a subtheme, or a slighly different flavour (mobile vs. desktop) of my theme, I use $theme that to get my active theme.


How to control the display of a user account connected via entity reference

how can I get this reference to show as a user link?

Go to your paragraph bundle and click on manage display. Find your entity reference field and click on the gear icon.

Note:

The label on the left it's the actual field label.
The label on the right, refers to the fields contents

Check-mark Link label to referenced entity.


Remember users Taxonomy choice, such as which city to filter the site by?

I would create a custom module and.

Save the choice in the users session (sessions is mapped to a cookie)
Use hook_boot to do the redirect, a simple drupal_goto should be enough.

Using sessions is more simple, but depending on your settings the data will persist for a shorter period of time than cookies. But that might be a good thing.


Behavior not attaching to a form element

You shouldn't need a single line of JS to have autocomplete textfield working in D6/D7. Please see the Form API refrence.


How to override confirmation messages when saving or updating content in Drupal 8?

Don't know if that's the best way, but it worked for me.

In your my_module.module:

/**
 * Implements hook_entity_type_alter().
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
 *
 */
function my_module_entity_type_alter(array &$entity_types)
{
    $entity_types['taxonomy_term']->setFormClass('default', '\Drupal\my_module\Form\MyTermForm');
}

Create my_module/src/Form/MyTermForm.php and override the save() method of Drupal\taxonomy\TermForm.

/**
 * @file
 * Contains \Drupal\my_module\Form\MyTermForm.
 */

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\TermForm;

class MyTermForm extends TermForm
{

    /**
     * {@inheritdoc}
     */
    public function save(array $form, FormStateInterface $form_state) {
        $term = $this->entity;

        $result = $term->save();

        $link = $term->link($this->t('Edit'), 'edit-form');
        switch ($result) {
            case SAVED_NEW:
                drupal_set_message($this->t('Created new :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName())));
                $this->logger('taxonomy')->notice('Created new :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName(), 'link' => $link));
                break;
            case SAVED_UPDATED:
                drupal_set_message($this->t('Updated :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName())));
                $this->logger('taxonomy')->notice('Updated :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName(), 'link' => $link));
                break;
        }

        $current_parent_count = count($form_state->getValue('parent'));
        $previous_parent_count = count($form_state->get(['taxonomy', 'parent']));
        // Root doesn't count if it's the only parent.
        if ($current_parent_count == 1 && $form_state->hasValue(array('parent', 0))) {
            $current_parent_count = 0;
            $form_state->setValue('parent', array());
        }

        // If the number of parents has been reduced to one or none, do a check on the
        // parents of every term in the vocabulary value.
        $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
        if ($current_parent_count < $previous_parent_count && $current_parent_count < 2) {
            taxonomy_check_vocabulary_hierarchy($vocabulary, $form_state->getValues());
        }
        // If we've increased the number of parents and this is a single or flat
        // hierarchy, update the vocabulary immediately.
        elseif ($current_parent_count > $previous_parent_count && $vocabulary->getHierarchy() != TAXONOMY_HIERARCHY_MULTIPLE) {
            $vocabulary->setHierarchy($current_parent_count == 1 ? TAXONOMY_HIERARCHY_SINGLE : TAXONOMY_HIERARCHY_MULTIPLE);
            $vocabulary->save();
        }

        $form_state->setValue('tid', $term->id());
        $form_state->set('tid', $term->id());
    }

    /**
     * @param \Drupal\taxonomy\TermInterface $term
     */
    private function getType($term)
    {
        $vocabularyId = $term->getVocabularyId();
        switch ($vocabularyId) {
            case 'pages':
                return 'page';
            default:
                return 'term';
        }
    }

}


Is CiviCRM data vulnerable to the Drupageddon bug?

Since a potential attacker got access to the database, and through the evil php module, could execute code, everything on the same server must be considered compromised.


Calculate percentage based on two fields, one of which is an embedded view

i tried in output code:

<?php
echo count($row->field_a) + count($row->field_a) ;
?>

and the result is:

I modified the view, and used aggregation.

I modified the field a:

I modified the field b:

I modified the field php:

And the code:

And result:


Is there a module that creates a jquery-like bar that displays system messages at the top of the page?

You could have a look at the "Purr Messages" module - I haven't used this myself, so I don't know if it allows for the messages being displayed at the top - it says it creates a "jquery popup," which I suppose means an absolutely positioned div which either fades out or you can click away with your mouse.

I did something similar to this this on one site by simply editing page.tpl.php - but it sounds like you want a module, & not coding advice.


Light box that is compatible with Views?

The Lightbox 2 module integrates with Views.  I use it on my site.  This module is extremely popular (more than 100,000 installs).

Unfortunately, this issue describes why Views and Colorbox are currently not compatible.


How do I create a base content type and subtypes ("bundles")?

Creating entity is quite complicated, but it will be easier if you generate a base code with Drupal console command first.

drupal generate:entity:content [options]

  Options

  --module  The Module name.
  --entity-class    The content entity class
  --entity-name The content entity name
  --base-path   The base-path for the content entity routes
  --label   The label
  --has-bundles Entity has bundles
  --is-translatable Content entity translatable

I post some useful tutorial / documentation here:

https://www.acquia.com/resources/webinars/creating-custom-entities-drupal-8
https://www.drupal.org/developing/api/entity


Detect if the value of a cck field has changed when a node is edited

I haven't done this, but my first idea would be to do this in nodeapi() and do something along the lines of (this horrid pseudo code):

if ( $op == 'presave' and $node->type == 'event' ) :
   $existing = node_load($node->nid);
   if ( $existing ) :
       check your fields in $node against the $existing node
       if they are different do something

and take into account you may no longer need IT or catering, so that needs to be conveyed as well as if you need it afterall.


How do I properly print the $node array in a views row template?

Install and enable the Devel module.

Next, wrap the variables you wish to debug in dpm() or dd()

dpm() will output to the browser if possible.

dd() will output to a file on your server.  For example on my Ubuntu dev box it outputs by default to /tmp/drupal-debug.txt


Firstly you add a cck field named flag for levels to your vocabulary when created, then after that when you import or add terms in this then fill flag value like "My First Level"/"My Second Level". then you can fetch very easily like that..`

/* Get All States From Taxonomies */
  function get_taxonomy_by_flag($flag) {
       $VocabName = "Master Data";
          $myStateArray = array(0=>'-- Select --');
        $Vocabluary = get_vocabulary_by_name($VocabName);
         $query = new EntityFieldQuery();
          $entities = $query->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('vid', $Vocabluary->vid)
->fieldCondition('field_flag', 'value', $flag, '=')
->execute();
if(sizeof($entities)>0)
{
  foreach($entities['taxonomy_term'] as $tid) {

    $term = taxonomy_term_load($tid->tid);
    $name=$term->name;
    $myStateArray[$term->field_code['und']['0']['value']] = $name;
  }
  return $myStateArray;
}
else
{
    return 0;
 }
}

    function get_vocabulary_by_name($vocabulary_name) {
        $vocabs = taxonomy_get_vocabularies(NULL);
         foreach ($vocabs as $vocab_object) {
          if ($vocab_object->name == $vocabulary_name) {
            return $vocab_object;
         }
      }
            return NULL;
      }
     call this function by flag name and you can easily get all parents. because i have used this for **State/District/Block/Village** purpose.
      get_taxonomy_by_flag('STATE');

hope this helps you lot...


Is there any way to change home page on small screen?

To actually answer your question (Is there any way to set the front page according to the screen size). No. Especially as you mentioned that you don't want to use JavaScript in a comment to Inizio.

The server by itself has NO idea of the screen size of the client, so the only way to get that info back would be using JavaScript (either implementing drupal.settings or some kind of custom AJAX callback). Any module that you use would alos have to utilise JavaScript.

If you want to change the frontpage based on DEVICE, then that's more realistic, with something like Mobile Detect, Browscap, WURFL (or something similar) but again - not foolproof.


Exposed filter shs (simple hierarchical select) in a custom template

The problem was I did't add filter- in front of the filter name. Now it works with:

print $widgets['filter-{filter_name}']->widget;


Export a specific non-default database using drush sql-dump

According to the Drush 8 docs, there is a --database=key option that does what you want.

I've verified it against a D8 site with multiple databases using the command:

drush @dev sql-dump --database="blog_import" > ~/tmp/blog_import.sql

The drush sql-cli command also has the same option so you should be able to import the dump using a command like:

drush @dev sql-cli --database="blog_import" < ~/tmp/blog_import.sql


Billing and shipping mismatch on some orders

Afghanistan is the default country in country select lists since it's first alphabetically. It appears to me that perhaps some part of your checkout form is causing a previously saved address to be overwritten. This is an infrequent but common issue when combining a variety of Ajax related features on a single checkout form. I'd begin debugging there to see if you can isolate the point at which stale address data is saved to the active billing profile accidentally.


select list sending old value in ajax request

Use Form state input rather than using values in ajax call back like below:

if (isset($form_state['input']['students'])) {
    $student = $form_state['input']['students'];
  }


How to change the functionality of FILE_EXISTS_RENAME?

There's no way to do it without changing the core function file_create_filename. That could obviously have unwanted side-effects for other parts of the system, and make updating difficult.

If you have to do it differently for whatever reason, you should write your own function and use that instead. Once you see how much code you need to copy and maintain from file_save_upload and file_create_filename, though, you might think twice about whether it's worth it.


How to use a custom block template when the block is embedded in a panel pane?

If you need to use the block template in panels, make sure you choose the style from the panels option to be "Systems block".

This lets you use block--sweet-name.tpl.php.


Poll is not a fieldable entity, so this is not possible in ui.

You can do this in code:

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'poll') {
    $fields['description'] = BaseFieldDefinition::create('text')
      ->setLabel(t('New discription field'))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

Apply the schema update on the database:

drush entity-updates


How include oun TPL in /admin/structure/types/manage/

First of all change this line in your alter function -
$form['#theme'] = 'admt_form_theme_function';
change it to
$form['#theme'] = 'mymodule_userinfo_form_theme_function';

Add below line of code in your admt_theme function for mymodule_userinfo_form_theme_function.
'template' => 'your-tpl-name'

function admt_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_userinfo_form_theme_function' => array(
      'render element' => 'form',
      'template' => 'your-tpl-name',
    ),
  );
}

Then create your-tpl-name.tpl.php file inside your module folder.

Now you can use this new template for your form.


WHERE can I change the notification email message for role assigments?

Per TR on the Ubercart forums:

"You may change this text under the Conditional Actions settings:
/admin/store/ca/uc_role_notify_revoke/edit/actions"

http://www.ubercart.org/forum/support/32739/where_can_i_change_notification_email_message_role_assigments#comment-70607


The path() & url() Drupal Twig functions expect a route name and will not work with a Drupal path. For a relative/absolute path to /contact, you can use path()/url() respectively with the contact.site_page route:

{{ 'Contact'|t }}
{{ 'Contact'|t }}

If you don't know your route name, what you're looking for is link()

{{ link('Contact'|t, 'base:contact', { 'class':[] }) }}

See this d.o. page for more explanation about these 3 functions and their differences.


Allow users to select among various default images while creating their profile if none is uploaded

Use this module - Avatar Selection.

Does exactly what you're looking for.


How can I “Link to the Content” for teaser view mode of custom content type module?

This is the setting link_to_entity: true:

field_version:
  type: string
  weight: 2
  label: inline
  settings:
    link_to_entity: true
  third_party_settings: {  }


I suggest you to give to the Computed Field module a try. It seems that it does exactly what you need.

  Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!


Custom DatabaseConnection driver does not get found by drupal!

It looks like Drupal's autoload failed. For it to work you should put your classes in .inc file in your module, and then mention it in files line of module's .info file.

If that does not help and your classes are needed even earlier, include them in your settings.php:

require_once('path/to/module/sqlsrvseed.inc');


how to force  image file and music file  to download with zip format in drupal 6?

I'll answer with a question, do you want to make a zip file because it's an easy way to force browser to download the image or the mp3 instead of showing it ?

If so I'll recommend you the File Force Download module to achieve this. Also you have DownloadFile module and a .htaccess way to do this: Force Files to Download Instead of Showing Up in the Browser but I don't find this one to be very flexible.


Views Fields and Relationship with Aggregation

Perhaps you want to remove the post date sort criteria, and add an ascending sort criteria for content: price. If you only want one result value, change that in the Pager area.


How to add the Interest field in profile page which links the user with similar interest?

This is done using taxonomy and the term reference field. Each term assigned to an entity has the option in the display mode to be a link to the term page, which in turn shows all entities tagged with that term.

Edit-

Since default term pages only look for content entities you will have to create a view to override those term pages to show user entities instead. You  can use the taxonomy views integrator module to selectively choose which terms use which view. https://drupal.org/project/tvi


Webform: prepopulate fields through URL, "page not found"

Here is the answer.

It seems clean URLs are not enabled in your site. So here I'm giving the solution in both ways

Assuming that your Field Key  for First Name field is first_name

If clean URLS not enabled.

  http://localhost/test_site/?q=content/prepopulate&first_name=miranda

If clean URLS enabled

  http://localhost/test_site/content/prepopulate?first_name=miranda

I've tested this on my environment and works perfect. Hope this helps


In replacement to your "Learn more" add "Custom text" field after "Field_program_id" in your views. In "Text" add "a" tag like

Learn more

Take a look in "Replacement patterns" for available fields. Read description there too for a guidance.

(this is in Drupal 8)

It is the almost the same in Drupal 7, just with [] instead {{}}. Class for "button" depends of the theme.


You need to extend the query to a PagerDefault, and then use theme_pager() to output the pager links at the end of your content. The rest will be taken care of for you:

$limit = 10;
$query = db_select('nid_tid', 'nt')
  ->fields('nt')
  ->condition('terms', $name,'=');

$query = $query->extend('PagerDefault')->limit($limit);

$result = $query->execute();

$row = $result->fetchAssoc();
$nid = $row['nid'];
$ex = explode(',', $nid);
foreach ($ex as $tag_nid) {
  $out .= $tag_nid;
}

$out .= theme('pager');


Module to display a website's favicon when displaying a link to it

i believe this will work for you https://www.drupal.org/project/link_favicon_formatter

hope this helps:)


Creating multiple URL aliases for the same node with their own context

This should be working using the Rules and Pathauto modules. There's already a similar question that is answered: How to automatically generate multiple aliases for one node?


In Drupal 7, where is the code for the "powered by Drupal" block?

The contents is provided by theme_system_powered_by(), which is turned into a block by system_block_info() and system_block_view().


Huge amounts of locale queries clogging up drupal to 40 MB per request

Does your site use a caching system like Boost? Try installing the Drupal boost module and see if it helps. It is a static page caching system and needs to access the database only once.


I found a solution by myself. May be useful for others I think:

/**
 * Implements hook_node_view_alter()
 */
function MYMODULE_node_view_alter(&$build) {
    if (isset($build['links']['translation'])){
        $build['links'] = array(
            'translation' => array(
                '#theme' => 'links__node__translation',
                '#links' => $build['links']['translation']['#links'],
                '#attributes' => array('id' => 'translation_links')
            )
        );
    }
}

* Now my links have their own ID, so I can customize them as I need with css
* If you need to custom only these links, I suggest to use MYTHEME_node_view_alter()


Altering existing route for translation overview page ie: entity.node.content_translation_overview

It was not working because in content_transaltion module priority was set to -210 so make need to change priority of custom module to -220 and it started working.
public static function getSubscribedEvents() {
    $events = parent::getSubscribedEvents();
    $events[RoutingEvents::ALTER] = ['onAlterRoutes', -220];
    return $events;
  }


How to switch 'standard' installation profile to 'minimal' in existing site?

Installation profiles contain code to set up a site during installation, that's all they do. They aren't useful to an installed site.

Trying to change the profile after installation could never conceptually do anything. The installation code has already run, and the purpose of the profile has been served at that point.


$scripts variable in drupal 6 adding unwanted script codes

You should start at template_preprocess_node() where the $scripts variable is initialised:

$variables['scripts'] = drupal_get_js();

Then have a look at drupal_get_js() and follow the functions from there to find out how that mechanism works.

Then have a look at any implementations of hook_page_alter() throughout your site, where the $vars['scripts'] variable might be being manipulated.

Even though that technically answers your question, I'd be surprised if you find what you're looking for there. I've never heard of any malware that specifically targets Drupal (which is what this would be if it's manipulating the $scripts variable).

I'd check the rest of your page source to see if there's some JS being injected somewhere which is adding that <script> tag to the <head> dynamically, just in case.


Create a field collection field programmatically

Have you tried using entity metadata wrappers? They come with the Entity API module and allow you to do this (copied from linked documentation):

<?php
    // Populate the fields.
    $ewrapper = entity_metadata_wrapper('node', $node);
    $ewrapper->field_lead_contact_name->set($contact_name);
    $ewrapper->field_lead_contact_phone->set($contact_phone);
    $ewrapper->field_lead_contact_email->set($contact_email);

    // Create the collection entity and set it's "host".
    $collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
    $collection->setHostEntity('node', $node);

    // Now define the collection parameters.
    $cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
    $cwrapper->field_facility->set(intval($offset));
    $cwrapper->save();

    // Save.
    $ewrapper->save();
?>

In this example a node and the attached fieldset are created at the same time, so it might just work with only below code. Perhaps it is required to save the node afterwards, I have not tested it.

<?php
    // Create the collection entity and set it's "host".
    $collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
    $collection->setHostEntity('node', $node);

    // Now define the collection parameters.
    $cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
    $cwrapper->field_facility->set(intval($offset));
    $cwrapper->save();
?>

Update:

At the bottom of the Entity Metadata Wrapper documentation (before the comments) there are some lines about debugging and finding available parameters. That also might be of help while attempting to find the right property.


Module Installation: Unable to create directory 'temporary://update-extraction-f781a69c/

For me, things like these were caused by selinux. Either disable it, or add appropriate policy:

grep httpd /var/log/audit/audit.log | tail -n 50 | audit2allow -M drupaltmp
cat drupaltmp.te

Look inside, may be tune a little. I've got this:

module drupaltmp 1.0;

require {
        type httpd_t;
        type var_lib_t;
        type etc_t;
        type etc_mail_t;
        class file { write setattr };
        class dir { search create getattr setattr };
}

#============= httpd_t ==============
allow httpd_t etc_mail_t:dir { search getattr };
allow httpd_t etc_t:dir setattr;
#!!!! This avc is allowed in the current policy

allow httpd_t etc_t:file { write setattr };
allow httpd_t var_lib_t:dir create;

Then install it inside selinux

semodule -i drupaltmp.pp


what are the implications of installing APC on a VPS running multiple Drupal sites?

One thing to keep in mind is that APC will require quite a bit of memory if you have multiple sites because each file will be kept in memory, even if it is in fact exactly the same file, just with a different path.

So you need to watch and tune the amount of memory that apc uses/can use. By default, it's 32MB, that's often too less for even a single Drupal site if you have many contrib modules. The problem is that if APC has not enough memory, it will always have to delete files from the cache. If it has much to less (e.g. not even enough for all files in a single page request), it will make your site slower than if you hadn't used APC at all.

VPS often don't have a lot of memory, make sure that you have enough for your sites. You could consider merging them into multi-sites to save memory.


Boost makes the editing of content/settings impossible

Did you add the Boost section in your .htaccess, which is necessary to make it work? If you already have, you might check that the part about GZIP is present.

I had this same problem, and what I did was to disable and uninstall and remove the Boost module. Then I installed and enabled the previous Boost version where this GZIP section is present. I saved that part in .htaccess and went back to installing the latest Boost version again, but with the added GZIP part in the .htaccess file.

You can also check this thread out: Impossible to edit nodes, log to in etcetera after enabling Boost and editing .htaccess

The most important gzip rules are these (if you want to try this without disabling, uninstalling and the re-installing the module:

  # GZIP
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=1]

  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz -s
  RewriteRule .* cache/%{ENV:boostpath}/%{SERVER_NAME}%{REQUEST_URI}_%{QUERY_STRING}\.html\.gz [L,T=text/html,E=no-gzip:1]

Hope this helps.


If i understand you in the right way you want to edit path alias when creating new content.
At first you have to give permission to create and edit URL aliases to some user role.

Then just add <?php print drupal_render($form['path']); ?> to your form template (EG. to the top of the form).


Is it possible to give a language prefix to all the nodes without third-party modules?

These are the rewrite rules to add in the .htaccess file located in the Drupal root directory.
RewriteEngine on
RewriteCond %{REQUEST_URI} !/he
RewriteRule ^(.*) http://www.domain.com/he%{REQUEST_URI} [L,R=301]