Different front page template for different domains

You can use a combination of the Context and the Delta modules to achieve this.

You can create a new instance of a theme using delta module and use context to use that instance for a specific module.

Alternatively, you can use Domain theme module (sub module of Domain module).

Let me know if you get stuck.


Why doesn't variable_set() work in an installation profile?

variable_set() works fine in installation profiles (standard_install() uses it), it's more likely that the submit handler for your form isn't being run. I seem to remember having to explicitly set the submit handler for one of these extra installation forms:

$form['#submit'][] = 'myprofile_install_mode_form_submit';

Try adding a call to drupal_set_message() in the form submit handler to make sure your code is definitely being run.


How do I add custom primary menu using CSS and HTML

You could alter the menu attributes using template.php file and its functions exclusively for menu.


It has been solved before. Have a look at https://drupal.stackexchange.com/a/36025/6286


Get rid of classes from views root container

You can use template_preprocess_views_view function and remove needles classes from  $vars['classes_array'] array.

function mymodule_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'my_view') {
    $vars['classes_array'] = array('view', $vars['css_class']);
  }
}


You should read the official security thread, if you want to go further I advice you to take a look at the cracking Drupal book. In chapter 1, which is available for free download, you will get an idea of the places to look at.

According to this book, most common vulnerabilities found in Drupal sites are :

    Vulnerability   | occurences as a percentage of the total

     XSS            |      44
     Access bypass  |      14
     CSRF           |      10
     SQL injection  |      10
     Code execution |      8
     ...

So you shouldn't be concerned by Drupal architecture but with the way you implement your website, like any other.
For instance, requiring administrator approval for users registration, making sure forms are safe and applying Drupal's updates should be a good start.

Also, if you choose to use the LDAP module for Drupal 7, keep an eye on its security related issues.


How do I prevent delimiters in a URL from being URL encoded?

I am sure I am missing a or the point here, but, could you do something like this:

while ($cbo_short_name = db_fetch_array($result)) {
  if ($count > 0) $delim = '+';
  $cbo_short_names_arg .= $delim . drupal_urlencode($cbo_short_name['cbo_short_name']);
}
$redirecturl = 'cbos/' . $cbo_short_names_arg;
$node->webform['confirmation'] = $redirecturl;

eg, sanitize your arguments but then glue them together with the + (that isn't encoded) ?


You can always create an array of name/value pairs and then a simple foreach loop to set them all. Or you can pass it to Node::create() if it is a new node.

There is no setMultiple() or similar API.


Pass argument to view block within a minipanel

I just solved the exact same thing on my site, so writing it up here for future reference.

Your views:

Create these as content panes
Contextual filter = Content: thas taxonomy term id (in this case)
Argument input (under "Pane settings" in the view) = "Input on pane config"

Your mini panels

Context -> Required context: taxonomy terms
Content -> (Your views) -> Settings -> "Term id" (probably named differently) = %taxonomy_term:tid

Your main panel

Context: Add taxo term id. You will have to add each term id you will want to use as a context here.
Content -> (Your mini panels) -> Settings, select the term you would like to use on that instance of the mini panel:


Can you disable drush pm-update for a site?

You can disable the core Update module on the live site,  and then should prevent being able run pm-update on live:

  $ drush pm-disable update The following extensions will be
  disabled: update Do you really want to continue? (y/n): y
  update was disabled successfully. [ok] $ drush pm-update
  Command pm-update needs the following modules installed/enabled to
  run: update. [error] The drush command 'pm-update' could not be
  executed. [error]


Where and when in the User login workflow is the last Access time timestamp set?

Simply scan the codebase for setLastLoginTime and you'll see that there's actually only one single place where this function gets called. And that is user_login_finalize.

/**
 * Finalizes the login process and logs in a user.
 *
 * The function logs in the user, records a watchdog message about the new
 * session, saves the login timestamp, calls hook_user_login(), and generates a
 * new session.
 *
 * The current user is replaced with the passed in account.
 *
 * @param \Drupal\user\UserInterface $account
 *   The account to log in.
 *
 * @see hook_user_login()
 */
function user_login_finalize(UserInterface $account) {

And when does user_login_finalize get called? Scan the codebase again. And you'll see that there are some few places only. For example in the submit handler of the user login form, in the submit handler of the user register form, or for example also in the install_finished handler when you after a successful interactive site installation (in the browser) get logged in as user 1.

Following the input from @4k4 there must be differentiated between the last login time and the last access time. Both are base fields of the user entity. The login time gets stored on every login finalize (see above) and the access time (the one you can see in the users View in the LAST ACCESS column at /admin/people) gets renewed every 180 seconds. This happens in an event subscriber which gets triggered on every request/response cycle – the UserRequestSubscriber.

The last access time then can be retrieved from User::getLastAccessedTime. I maintain a small module to calculate online, absent and offline states of a user with exactly that method: https://git.drupalcode.org/project/user_online_status/-/blob/8.x-1.0/src/StatusService.php#L83.


I don't think Drupal 7 or Drupal 8 support chunked AJAX response. Because AJAX in Drupal is implemented with jQuery.ajax which does not support that.


how to change h2 tag for div in block_view

try with the following:

Implement hook_theme_registry_alter to take the templates from your module.

/**
 *  Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  // Defined path to the current module.
  $module_path = drupal_get_path('module', 'mymodule') . "/templates";
  // Find all .tpl.php files in this module's folder recursively.
  $template_file_objects = drupal_find_theme_templates($theme_registry, '.tpl.php', $module_path);
  // Iterate through all found template file objects.
  //test if this page isn't in BO page
  if (!path_is_admin(current_path())) {
    foreach ($template_file_objects as $key => $template_file_object) {
      // If the template has not already been overridden by a theme.
      if (!isset($theme_registry[$key]['theme path']) || !preg_match('#/themes/#', $theme_registry[$key]['theme path'])) {
        // Alter the theme path and template elements.
        $theme_registry[$key]['theme path'] = $module_path;
        $theme_registry[$key] = array_merge($theme_registry[$key], $template_file_object);
        $theme_registry[$key]['type'] = 'module';
      }
    }
  }
}

Copy modules/block/block.tpl.php and past it in templates folder of your module.
Rename it from block.tpl.php to block--mymodule--myblock.tpl.php to change only for your block.
Change the line from <h2<?php print $title_attributes; ?>><?php print $block->subject ?>
 to <div<?php print $title_attributes; ?>><?php print $block->subject ?>

Clear cache.


How to add active class to link which is loaded via views and links comes from content type

Example:

In my content type I added a link field called "link", so the machine name is field_link

In this link field for url I put http://example.com/node/3

I created a View called "Test".

In fields I added link.

In fields I added link again, but this time I change the formatter to URL, as plain text

We are going to use template_preprocess_views_view_fields

In your theme's template.php file you add

function mytheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "test"){

    $field_link = strip_tags($vars['fields']['field_link_1']->content); // use strip_tags function to remove HTML markup.
    $field_link = str_replace('http://', '', $field_link); // remove http://
    $field_link = str_replace('www.', '', $field_link); // remove www.

    $node_url = $_SERVER['SERVER_NAME'] . '/' . request_path(); // see https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/request_path/7.x

    if ($field_link == $node_url){

      $vars['fields']['field_link']->content = '
' . $vars['fields']['field_link']->content . '
';

    }

    $vars['fields']['field_link_1']->content = null; // hides the field_link_1 field

  }

}

replace mytheme with the actual name of your theme.
replace test with the actual name of your view.
replace field_link with the actual name of your field.

Then you add the CSS to your theme's style.css file, Example:

.active-link a { color: green; }


How to render a template in a module controller?

You need to let Drupal know about the theme, and then you can leverage it in the controller code. The template needs to be in the folder my_module/templates.

my_module.module

function my_module_theme() {
  $theme['template_name'] = [
    'render element' => 'build',
    'template' => 'template_file_name',//This is only needed if you need a different template file name than the array key above, 'template_name'.
  ];

  //override existing template for this module
  $theme['html__my_module__template_file_name'] = [
    'template' => 'html--my_module--template_file_name',
  ];
  return $theme;
}

src/Controller/MyModuleController.php

public function index() {
  $build['#theme'] = 'template_name';
  //populate your build renderable array..
  return $build;
}


You can create two content types

Race Details
Race Standings

Node reference to Race Details as a field
Year
A Field Collection with details (Fields) like

Race Winner Name
Timings
Car
Position etc


Did you attach your WebformHandler to your webform via /admin/structure/webform/manage/WEBFORM_ID/handlers?

Your QuizWebformHandler::submitForm method does not match the WebformHandlerInterface::submitForm definition and should be throwing a fatal exception.


How do I get the content type of a node entity from the $entity object?

If you know that you have a node, then you can use getType(). If you don't know that, you can use he generic method ->bundle(). Note that the second will return the entity type in case of an entity type that doesn't have bundles, like users.

Again, my standard reference to http://wizzlern.nl/sites/wizzlern.nl/files/artikel/drupal-content-entity-8.0.pdf, it contains both methods.


Replace a content type name with a different string, in a view

Override the template file of you 'Content type' field for your particular view, and code in it.

switch($output) {
  case 'content type 1':
    print 'my content1';
    break;

  case 'content type 2':
    print 'contents for all';
    break;

  // ...
}


This is working :

setlocale(LC_TIME, 'French_France.utf-8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
//setlocale(LC_ALL, '') ;// if you try on local windows server

$annee = date("Y", strtotime($date));
$semaine= date("W", strtotime($date));

// Get the monday date of that week
$lundi = new DateTime();
$lundi->setISODate($annee , $semaine);

print "Semaine du " . strftime("%A %d %B %Y",strtotime($lundi->format('j F Y')));


It sounds like you could accomplish this with a combination of rules and user roles. I assume to don't want the node to be editable by anonymous users so set the rule to grant editing permissions to all users who have a particular role when the value of the field changes from locked to unlocked (or whatever your corresponding value is). If you want more granular control, (i.e. when a node is unlocked some fields are editable but others remain editable only by admin users), you'll need to install the field permissions module (https://drupal.org/project/field_permissions.


Implement user editable personal pages with subpages

You might not be aware of it, but this is a rather broad question.

Drupal is quite different to other CMS's. You don't create pages according to a certain URL structure. In a way, it's the opposite.

Your users just create content with relations/references to other content. How and where that is shown is up to you, not them.

One way to do this is to have two node types, "Project" and "Sub project" for example. Users create projects and they can create sub projects and select the parent project using an entity reference field.

Then, all you need is to set up alias patterns using custom code or the pathauto module (An inofficial D8 port can be found here, use on your own risk) so that it results in those URL's.

You can add plenty of things on top of it with views, custom code and so on: links to create sub-projects from a project, listing projects and subprojects but defining the content structure (and only after that the URL structure) is where you have to start.


How to set maximum height in image style in Drupal 7?

Your approach will differ depending on whether you want your images to be cropped or scaled to fit the appropriate size, but generally speaking, in most of the image style effects where you can specify a width and height, if you just enter one value, the value for the other will be automatically calculated ("Resize" is an exception, but since that can result in distorted images, you almost always want to use "Scale" or "Scale and crop" instead.) For example, if you add a "Scale" effect, leave the width field blank and set the height to 150px, when processing a 400x600px image, the system will notice that it needs to divide the height by 4 in order to reduce its height to 150px, and apply the same division to the width, resulting in a 100x150px image.

Again, depending on how you want images to be scaled or cropped, applying more than one action in sequence may also get you where you want to be. For example, scale to a certain width, then crop to a certain height. The "Scale and crop" action can do both of these together in one action, but might not do it in exactly the manner you want.


Custom block automatically adds code when edited in admin

The data-entity-type & data-entity-uuid properties are added with  WYSIWYG fields when you have the Track images uploaded via a Text Editor filter . This filter is designed to track usage of images as they are dropped into HTML body fields and update the fields accordingly when the image is updated.

To disable it, navigate to the Text formats and editors admin section and configure the format that's being used for your custom block. Untick the Track images uploaded via a Text Editor filter option and click the Save configuration button to disable the filter.


If you are not the super admin (user id = 1) on your drupal site.

You need to give the permission for "Use CTools importer" to be able to import a variant.


This was being caused by Cron run failing to complete for some reason.  We were able to solve the issue by installing the Cron Debug module and Cron would run successfully from there and clear up the extra text.


Conflict between with a function in two different modules

Rather than module weighting, I would suggest using hook_module_implements_alter to ensure your hook gets run last. So, something like this:

function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'theme_registry_alter') {
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}


Conditional patterns with automatic nodetitles

That module also provides the ability to use PHP to construct the pattern.  Look for the check box at the bottom.

Please refer to the module's help file for more info on combining PHP and tokens for the pattern.


That sounds like the core behaviour to: "Require email verification when a visitor creates an account"

However, the password will be selected after clicking the email verification link, to activate the account.


How do I set administrator menu to be the same as this Drupal 7 menu?

To disable the menu shown in your first image, go to Structure > Blocks and disable any menu blocks you don't want to display (e.g., Management, Navigation, User). (Thanks, @leymannx!)

To have the menu shown in your second image, enable the core Toolbar module.


depending on how your module is setting up the block, you could look into Block Refresh:

  Block Refresh allows an administrator to configure a block to refresh
  it's content via 3 different methods: automatically via a timer (eg
  every 30 seconds) , manually via a 'refresh' link, and once on page
  load.

  Block Refresh uses jQuery/AJAX so the refresh happens
  "behind-the-scenes".

  Block refresh can be handy to serve fresh content in certain blocks on
  otherwise cached pages. You can opt to bypass drupal's cache for the
  refresh callbacks for each block.

Edit

I just ran into this exact problem and developed a simple little approach that works nicely:

using Block Refresh

set up each of the blocks you want to refresh as manual - this would normally cause a link to appear in each block allowing a click refresh

create some css to hide the ugly links:

.block-refresh-button
{
    display:none;
}

then add a simple jQuery click to force block refresh to do all the work for you - this can be modified appropriately as necessary:

jQuery(".flag-wrapper").click(function()
{
    jQuery(".block-refresh-button").each(function()
    {
        jQuery(this).click();
    });
});

I found this will refresh ALL blocks on the page set up with block refresh, including Views.


How to set advanced views setting in code? Specifically disabling SQL rewriting with webform_select_options

So this approach let's you edit the view through the Views UI. I thought the view was created on-the-fly by the module, but the module loaded the view into the db and exposed it to the views UI. Though this doesn't address the question directly.


Drupal 7 - views blocks not displaying page field content

A block created by view shows up as any other view, unless you have permission control for the block at views level or at block level.

Permission at views

Permission at block

Visibility settings - By various ways block visibility can be controlled, ensure you have appropriate configurations for this.

Region Settings - Ensure you are putting the block in the region of right theme you are expecting the block to see.

Few things to debug.

Login with super admin(user id 1) see if you can see the block, if yes it will ensure you have permission issues.


Order of facets block change after the research

It may not be the block weights, but just in case, can you see what I mean by making sure they're distinct.

Verify the below and see if you still have the same issue:


When the admin changes(Add/Remove) roles of the user, how to get assigned and removed roles of that user?

Implement hook_user_presave:

/**
 * Implements hook_user_presave()
 */
function yourModuleName_user_presave(&$edit, $account, $category){
  foreach ($account->roles as $role_id => $val) {
    $user_roles_existing[] = $role_id;
  }
  foreach ($edit['roles'] as $role_id => $val) {
    // $edit['roles'] contains all roles ids as key and selected role id as val. If not selected then value is 0
    // ex. $edit['roles'] = array(5=>5, 6=>0) here role id 5 selected
    if ((int) $val > 0) {
      $user_roles_form[] = $role_id;
    }
  }
  $user_roles_new = array_diff($user_roles_form, $user_roles_existing);
  $user_roles_removed = array_diff($user_roles_existing, $user_roles_form);
  //roles added
  if (count($user_roles_new) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing new roles count' . count($user_roles_new));
  }
  //roles removed
  if (count($user_roles_removed) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing Removed roles count' . count($user_roles_removed));
  }
}


Newly Inserted Record was not Queried, Immediately after Insertion

You can simply check against inserted id. If insert successful means you get inserted id only then you render the data otherwise do nothing

$inserted_id = db_insert('studidtemplates',array('target' => 'import'))
        ->fields(array(
            'template_name' => 'WEW',
            'date_created' => date("Y-m-d H:i:s", time()),
            'user_name' => $user->name
        ))
        ->execute();
if($inserted_id) {
   return array(
    '#type' => 'ajax',
    '#commands' => array(
        ajax_command_replace('#myid_templates_editor_table_wrapper',     render($form['myid_templates_editor_table_wrapper'])),

    )
);
}


Look at the function that's used to save form "cache", form_set_cache:

function form_set_cache($form_build_id, $form, $form_state) {
  // 6 hours cache life time for forms should be plenty.
  $expire = 21600;

As you can see, it's hardcoded and you can't really change it without hacking core. Now the question is - should you?

{form_cache} as cache

Form data is kept as a cache bin, but it is not a "real" cache. Let's look at the definition from Wikipedia:

  In computer science, a cache (/ˈkæʃ/ KASH) is a component that transparently stores data so that future requests for that data can be served faster.

Now, that's pretty much what {form_cache} is not - it is kept to save temporary data that needs to be consistent, and that are never stored anywhere else during form processing. It means that when someone is using APC or Memcache, he needs to take extra care to prevent their "it can be deleted without any reason, for performance purposes" approach from corrupting forms. Most Drupal admins I know simply exclude form cache bin from them.

If you will shrink the time data is kept, you risk all kinds of errors. So keep in mind that your form cache bin should preserve data significantly longer than you expect anyone to need between first form display and the end of it's processing.


Taxonomy autocomplete returns "connection reset"

So after much frustration, I've finally got to the bottom of this. The answer is not within Drupal, but rather in my cPanel setup. I'll post the answer here because it may save someone else the headaches I've had.

The problem was that my cPanel hosting had xVarnish enabled. I'm not sure if it was suddenly added by a package upgrade, or if the behaviour changed, or if its effect only kicked in after a certain time span, but I certainly didn't switch it on! In any case, disabling xVarnish not only fixed this problem but also an "access denied" on image styles that had cropped up too.


How do I change the current language in a Kernel test?

Looks like I needed to call:
    \Drupal::languageManager()->reset();

No, wait, that doesn't seem to be the whole story.... ARGH.
EDIT:
For the entity to be treated as translatable and so return the right URL, I also needed to set the bundle as translatable:
    $this->entityTypeManager->getStorage('language_content_settings')->create([
      'target_entity_type_id' => 'node',
      'target_bundle' => 'page',
    ])->save();
    $this->container->get('content_translation.manager')->setEnabled('node', 'page', TRUE);


Pathauto not updating path portion of new path

I'm running into the same problem, I tried to trace the code and it looks like that token replacement is never called. Not sure if its a bug in token or pathauto module.


You don't need any template files. All you need to do is to create a pdf document with d design u want, then include it in the template section in your views setup


Drupal Commerce assign role on account create on checkout

$account = new stdClass;
$account->is_new = TRUE; //indicate the account is new
$account->name = 'account_name';
$account->pass = user_hash_password('password'); // make a function to create random passwords
$account->mail = 'email';
$account->init = 'email';
$account->status = TRUE; //set the user to activated at creation
$account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE); //set user as authenticated user
$account->timezone = variable_get('date_default_timezone', '');
$new_user = user_save($account); //create user (user_save() returns a fully loaded $user object)

$role_name = 'ROLE_NAME'; // The name of the role to add.
if ($role = user_role_load_by_name($role_name)) {
  user_multiple_role_edit(array($new_user->uid), 'add_role', $role->rid);
}

You can use the hook: hook_user_insert.
And apply the last piece of code from above to update the role.


Removing all 'stable' theme's CSS from a Drupal 8 custom theme

There's no wildcarding for the stylesheets-remove (FYI: there's a FR out there for it). However, you can use libraries-override to remove the library associated with the all CSS components you've highlighted:

libraries-override:
  system/base: false

It won't remove all CSS files in the stable theme, but it will condense removal of libraries that contain many CSS files.


Split commerce cart to multiple orders per product

As you now,by default drupal add to cart form add all products to the same order.

Looking at the code of commerce_cart.module, the base and unique behaviour of commerce_cart module, it doesn't works in other way. When a product is add to cart, the order associated will be the same order or a new order.

If you want to decouple the line items in two different orders in cart page you will have to code a module based in commerce cart with that feature.

You can take a look to this module, it maybe helps you https://www.drupal.org/project/commerce_cart_multiple


how to set custom permission to custom menu access?

If you do this using a custom module, you can use hook_permission to defile your permissions, and use in the views. You can also restrict access by role and set the visibility if you use blocks fir the 'list of registered students'.


Is there a trick to deploying Commerce Kickstart 2

Missing display/designs/CSS rules are typically a symptom of missing stylesheets or other CSS style rules. If you browse to your login page, Drupal reports many errors about not being able to create files.

It looks like your intuitions are likely correct; the server is probably having trouble writing aggregated CSS files to the files dir. Try turning off CSS/JS aggregation to confirm this. If that fixes it, check ownership of the files dir/subdir to make sure it's the same owner as the web server process.


Drupal 7 easy breadcrumb module hides breadcrumbs

Have a look at the Easy Breadcrumb project page. The answer to your question is in the Configuration section of it. Here is a quote from module's project page:

To start using it, just go to the admin modules page (URL admin/modules/list), locate and activate it under the category "others", then go to the blocks list page (URL admin/structure/block) and locate the block named "Easy Breadcrumb", and configure it like any other block (region, URLs, etc.).
The configuration page of this module is under Admin > Configuration > User Interface > Easy Breadcrumb (URL admin/config/user-interface/easy-breadcrumb).
Configurable parameters:

Disable the default Drupal's breadcrumb.
Include / Exclude invalid path alias as plain-text segments.
Exclude some paths from the segments to be generated.
Include / Exclude the front page as a segment in the breadcrumb.
Customize the title of the front page segment in the breadcrumb.
Include / Exclude the current page's title as a segment in the breadcrumb.
Use the real page's title when it is available instead of always deducing it from the URL.
Print the page's title as a link or as plain-text segment.
Use a custom separator between the breadcrumb's segments.
Choose a transformation mode for the segments' title.
Make the 'capitalizator' ignore some words (words not to be capitalized).


Is there a way to upload file in database instead of in filesystem via webform?

You could read the field and write the contents in the database. This could be done in a custom submit handler to the webform form.


How to setup hook_install to have a geometry field on a POSTGIS database?

I have no idea if this will work (don't have a postgis install handy to test), but try

$schema['table'] = array(
  'fields' => array(
    'some_geom_field' => array(
      'pgsql_type' => 'geom',
      ...
    ),
  ),
);

If that doesn't do it I think you're out of luck using hook_schema(), you'll probably need to execute a custom SQL script instead.


Customizing a drupal webform for Drupal 6

You can customize form's HTML markup using Drupal's form alter hooks:

hook_form_alter or hook_form_FORM_ID_alter
Form API Reference

after changing form's markup you should only styling form using CSS.


Results of GET Request inside block are being cached and not updating when GET request values are changed

You don't need cache tags, you need a cache context for the query key state:

$build['#cache']['contexts'][] = 'url.query_args:state';


Is there a way to use $front_page in node.tpl?

Absolutely:

function MYTHEME_preprocess_node(&$vars) {
  $vars['front_page'] = url();
}


Creating a view with a dynamic link from taxonomy term

In the contextual filters you may have to add the Context: Has taxonomy term ID filter.  You can set the Specify validation criteria settings.  The validator option is usually Taxonomy Term, but other validator options are available. Make sure to choose Term Name converted to Term ID, as this is what is needed to be passed for to the url.  Also check the Transform dashes in URL to spaces in term name filter values checkbox underneath.
Choose your action to take if the filter value does not validate dropdown.


Why cant I configure or remove this module?

I checked the error log and when I try to uninstall I get the following error PHP Fatal error: Call to undefined function google_analytics_clear_js_cache()

This means that there is a bug in this module (and off-topic here).

But this is a general problem, and this anser provides is a general solution to this problem, that can also be used with other modules.

Whenever you get a WSOD upon uninstall and the log tell you it is because a "Call to an undefined function" - locate that call in the module's source code, and just delete the statement with the call.  Then try to uninstall again.

After doing this, make sure you report the problem to the module's issue queue on Drupal.org to make the maintainer fix it (and alert others about it).


Limit amount of emails sent per time frame?

There is an option, Queue mail module that queues all output emails in the queue ( you can define what email Ids queue). then set Cron to run each hour with ultimate_cron module)
the only problem is that you can not define how many hours can be sent in a Cron run. you can just set how many seconds the Cron can be run ( Queue processing time) . I think with a couple of tries you find your desire time.


You should rather use the following code, but there is a problem I will describe.

if (empty($user->uid))  {
  $entityform->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
}

The problem with that code is that it will use the user ID of the next user account that is being created, which could not be the user who created the entity. This is true when:

The anonymous user creates an entity instance
After the code I shown is executed, a new user creates an account
The anonymous user who created the entity instance creates an account

I would rather do the following:

When an anonymous user creates an entity instance, asks for an email address
Save the email address as part of the entity

When a user account is created, and the user logs in the very first time:

Search for any entity instance where the email address is equal to the email address used for the user account
Change the user ID with the user ID associated to that email address

Instead of the email address, you could ask anything else, as long as it is clear to the user that the entered value is requested when s/he creates an account to assign to her/his account any entity s/he creates. As the email address is required to create a user account, I would ask the email address to the anonymous users who creates entities.


How to change "New content" text in entity connect autocomplete edit/add buttons?

In a form alter you can access those two buttons with something like:

$field_name = "field_test";
$form[$field_name][LANGUAGE_NONE][0]["add_entityconnect__".$field_name."_0_"]["#value"] = t("New");
$form[$field_name][LANGUAGE_NONE][0]["edit_entityconnect__".$field_name."_0_"]["#value"] = t("Edit");

Adapt the name, language and cardinality of the field accordingly.

You can use a basic hook_form_alter to affect all forms. The widget creation code is in entityconnect.form.inc and it can't be altered (no hooks, no variables).


Remove uploaded files before the 6 hours cron?

file_cron() contains the code that delete managed files. To adapt it to delete those files with their status set to 0, this is what I would use.

$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$fids = Drupal::entityQuery('file')->condition('status', 0)->execute();
$files = $file_storage->loadMultiple($fids);

foreach ($files as $file) {
  $references = \Drupal::service('file.usage')->listUsage($file);
  if (empty($references) && file_exists($file->getFileUri())) {
    $file->delete();
  }
}

This code returns you all the files matching those conditions. You can also use the following code to get them in batches of 100 per time.

$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$fids = Drupal::entityQuery('file')->condition('status', 0)->range(0, 100)->execute();
$files = $file_storage->loadMultiple($fids);

foreach ($files as $file) {
  $references = \Drupal::service('file.usage')->listUsage($file);
  if (empty($references) && file_exists($file->getFileUri())) {
    $file->delete();
  }
}

I didn't check, but it is probable you can also filter the returned file entities by the bundle using them.


Using Gulp JS in multiple theme development

I have finally found the best solution for this so I'm posting it incase anyone has a similar issue:

Add gulp (package.json, gulpfile.js & node_modules) to a centralized location (eg: sites/all/libraries/gulp)
In the root of each theme, create 3 symbolic links that point to gulpfile.js, package.json and node_modules


On Feed API, what does the setting "Delete news items older than:" mean?

This setting does two things:

1) When reading from a feed, ignore items older than this setting.

2) On cron, delete all node feed items older than this setting.


I have 10396080 seconds, and I want it to look like this: xxx hours, xxx minutes. Is there some function for that?

Not really.  What you want is 10396080 seconds converted to 2887 hours 48 minutes, and I know of now existing function that does that.

There  is format_interval().

 $seconds = 10396080;
 $string = format_interval($seconds, 2);
 echo $string;

But that will output "4 months 7 hours".

However, the following custom function:

 function _hoursminutes($interval, $granularity = 2, $langcode = NULL) {
   $units = array(
    '1 hour|@count hours' => 3600,
    '1 minute|@count minutes' => 60,
    '1 seconds|@count seconds' => 1,
  );  $output = '';
  foreach ($units as $key => $value) {
    $key = explode('|', $key);
    if ($interval >= $value) {
      $output .= ($output ? ' ' : '') .
        format_plural(floor($interval / $value), $key[0], $key[1], array(),
        array('langcode' => $langcode));
      $interval %= $value;
      $granularity--;
    }
    if ($granularity == 0) {
      break;
    }
  }
  return $output ? $output : t('0 second', array(), array('langcode' => $langcode));
}

 $seconds = 10396080;
 $string = _hoursminutes($seconds, 2);
 echo $string;

This will output: "2887 hours 48 minutes", which presumably what you want.


Views search for term reference in field collection

I've solved it by adding a relation with the field which holds the taxonomy term data for persons. A second relation needed to be added, this time related to the field collection name. This way I'm now able to expose the field which holds the job data as a search option.


This turned out to be a conflict with the songkick module. I'm a maintainer  so I'll make sure the issue is handled and post further updates in the issue cue on Drupal.org here.


Sending form to mail from custom module fails without error

Did you implement hook_mail in your module? – Alfred Armstrong
where to place the hook_mail function? – Lance

Goes in the .module file. Ex: my_module.module
/*
* Implements hook_mail().
*/
function my_module_mail($key, &$message, $params) {
  switch($key) {
    case 'my_module':
      $options = [
        'langcode' => $message['langcode'],
      ];
      $message['subject'] = t('@title', ['@title' => $params['context']['subject']], $options);
      $message['body'][] = t('@body', ['@body' => $params['context']['message']], $options);
      break;
  }
}

Flush all caches so hook gets picked up.


How to set a default theme programmatically

Looking at ThemeController::setDefaultTheme (the request handler for the /admin/appearance/default route), this should do the trick:

\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', 'machine_name')
  ->save();


Why cannot I print $form in my template file?

There's no $form variable available in page.tpl.php (see the docs for a full list of available vars).

If you're trying to output the page content it's done like so:

<?php echo render($page['content']); ?>


I don't know what get_menu_weight() returns (it is not in the standard Drupal API, is it?), so the following is the answer for a general case in Drupal 7.

In short, as long as the menu item is linked to a node, and if the node has at least one translation, the following code should work to get a path-alias of the node for all the translatable languages:

$hstpath = translation_path_get_translations('node/123');
array_walk($hstpath, function(&$v, $k){$v = drupal_get_path_alias($v,$k);});

gives an associated aray like:

Array(
  [en] => info/basic.html
  [fr] => info/basic.html
)

where both English (en) and French (fr) versions have the same path-alias of info/basic.html.

How to convert this path-string to a link to the node to view in the desired language depends on both your language-detection configuration and with which language environment you would like to display the node.

For example, if the URL with the path-alias is given the highest priority, then add the prefix of /fr/ to the French node (as long as French is not configured to be the default language with no path-prefix defined).  In addition, you may need to add base_path() at the head, if Drupal is not installed in the top directory of the website.

For a reference, a candidate answer to "Menu links not being translated" explains some basic for the Drupal menu with i18n.


Why are overrides not included in download file?

The solution was to use drush.

drush fu feature_name

After that all files were inclduded.


Views 3 remove exposed filter programmatically

I would use hook_form_alter using unset on the form object as you are in your example for the element that you want to remove.


I solved like that

$file_name = $file['name'];
$file_get = file_get_contents($file['tmp_name']);
$new_file = file_save_data($file_get, 'public://images/'.$file_name);


String translations not working after setting language in page preprocess function

I have got this working now by moving the code into the preprocess_node() function instead.

function phptemplate_preprocess_node(&$vars, $hook) {
  global $language;
  $languages = language_list();
  $new_lang_code = $vars['node']->language;

 if (isset($languages[$new_lang_code])) {
  $language = $languages[$new_lang_code];
 }
}


Two columns on frontpage with a CCK form and a node list

Administering panels has a huge overhead, however, since panels are highly cached there is actually a performance boost to use them over plain blocks. It's discussed in this article, Assembling Pages with Drupal.

If this is some type of survey or questionaire you can make the node edit form the front page by using using the site configuration feature assigning the font page path. With Views you then can create two blocks that you use to show on the right column in either the block administration page or the panels administration page. However, for surveys the standard is to use the Webform module.


How do I programmatically enable a view mode?

Use following code to enable view mode programmatically in Drupal 7:

module_load_include('inc', 'field_ui', 'field_ui.admin');
$bundle_settings = field_bundle_settings('ENTITY TYPE', 'BUNDLE');
$bundle_settings['view_modes']['VIEW MODE']['custom_settings'] = TRUE;
field_bundle_settings('ENTITY TYPE', 'BUNDLE', $bundle_settings);

Replace ENTITY TYPE, BUNDLE, VIEW MODE with your values.


Set a data value for a content field with rules

Solved by myself.

under the same rule (after a user has been flagged, )and after "create a new entity", I added 'set a data value' and chose 'entity-created:'. This then followed by the value "flagged-user:...".

If you understand my question, then you should understand my answer.lols


You need to let Views know about your custom field in database with hook_views_data. Here is an article that explains all about it: http://blog.menhir.be/2008/10/22/expose-database-fields-to-views-in-a-custom-drupal-module/


Yes.
Combined with 'entity_type' = 'comment', yes. An entity (comment, node, term, user, ..) is always identified by their entity_type and entity_id.
Not directly, in this case. There is also field_revision_comment_body table, which is in this case not used because comments don't support revisions (but field always needs to create one because nothing stops you from adding that field to a node and create revisions of it). There are also the field_config and field_instance_config tables which contain information about which field is attached to which entity type/bundle.


Webform options are config entities. You can export and import then via /admin/config/development/configuration.

You can also just bulk edit the options YAML. (/admin/structure/webform/config/options/manage/time_zones/source)

Or you can use hook_webform_options_alter() or hook_webform_options_WEBFORM_OPTIONS_ID_alter() to dynamic populate options from database or web service.


Drupal 7 set default value from database in hook_form

Basically, you have to add an indicator with edit question link i.e query string to load the selected question from database and pass the default value to the form.

  A query string is the part of a uniform resource locator (URL) that contains data to be passed to web applications.

"Click here to edit" link may look like (clean URL enabled):

http://www.your-domain.com/item_view/question/44

or

http://www.your-domain.com/question/44/edit

44 in both cases represent question id.

Then, take question id from the url and pass it to a mysql query to retrieve question title and assign it to #default_value

Example as follow:

function question_form() {

  $question_id = 0;

  // assuming url: www.your-domain.com/item_view/question/44
  if (arg(1) == 'question') {
    $question_id = arg(2);
  }

  // retrieve question title by question id
  $query = db_select('questions', 'q')
    ->fields('q', array('question_title'))
    ->condition('q.question_id', $question_id);
  $result = $query->execute()->fetchAssoc();

  $form['question'] = array(
    '#title' => t('Question'),
    '#type' => 'textfield',
    '#default_value' => ($result && isset($result['question_title']))? $result['question_title'] : '';
  );
}


Why the ETAG always change of my D7 site

In my setup, if I am logged into the CMS, then the Etag seems to be written as a unix timestamp, which is clearly being done to force caching off.  So this may be the reason you see the Etag constantly changing.

However, even when not logged in, in my case the Etag seems to change when the associated page cache expires, even if the content in the resource doesn't change at all.  I don't know why this is happening.


Is there a way to get (and use) an environment variable in a template file?

So I guess my problem was that I was on a Local environment, where Acquia does not provide any environment variables. I had to push my test code to Dev in order to see any effect.


Programmatically display user names according to the user profile type

I've put the following code on a module:

<?
// Find the type of the current user
function mymodule_get_usertype(&$user) {
  $usertype = 'other';
  if (is_array($user->roles) &&
      in_array('authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('non authenticated user', array_values($user->roles))) {
    $usertype = 'individual';
  }
  elseif (is_array($user->roles) &&
          in_array('business', array_values($user->roles))) {
    $usertype = 'business';
  }
  return $usertype;
}

// Implements hook_username_alter,
// to display the user name according to the profile type
function mymodule_username_alter(&$name, $account) {

  $profile_type = mymodule_get_usertype($account);
  if (!empty($profile_type)) :
    $profiledata = profile2_by_uid_load($account->uid, $profile_type);
  endif;

  if ($profiledata) :

    switch ($profile_type) {
      case 'individual':
        $firstname = field_get_items('profile2', $profiledata, 'field_first_name');
        $firstname = $firstname[0]['safe_value'];
        $lastname = field_get_items('profile2', $profiledata, 'field_last_name');
        $lastname = $lastname[0]['safe_value'];
        $name = "$firstname $lastname" ;
        break;

      case 'business':
        $bizname = field_get_items('profile2', $profiledata, 'field_biz_name');
        $bizname = $bizname[0]['safe_value'];
        $name = $bizname;
        break;

      default:
        // For admin users, no change
    }
  endif;
}
?>

The result is that the new name is displayed whenever a user name is displayed (e.g. on the menus, on the user page, or on the user listing pages)


Moving the file path from `c:\windows\temp' to another location, and after setting the IUSR permissions on that new folder, it worked as expected!


Have you tried http://views-help.doc.logrus.com/ or the advanced help module?

Edit::
Unfortunately there is no deeper documentation that I know of. I wrote a custom field handler and got most info from other handlers that came with views. I would recommend looking at the views/handlers directory, especially all files beginning with 'views_handlers_filter_'. At least that is what I did.


Hope this will help  you,

In Drupal 7 if you are using Captcha module, you can achieve it by the following steps

Let say you want to add Captcha to Article node form

Get the node form for which you want to add the Captcha, you an achieve it by using

    //Implements hook_form_alter() for node_form().
    function hook_form_alter(&$form, &$form_state, $form_id) {
        //use drupal_set_message to print the form ID
        drupal_set_message("<pre>" . print_r($form_id,1) . "</pre>");
    }

After printing the node article form

Get form id alternative (For developers) : Go on the page where your form is displayed.
Next, use developer tools of your browser to show DOM structure.
The form_id is displayed like the orange box on screenshot (Chrome example):

After enabling the Captcha module go to admin/config/people/captcha and add the node article form id and save the configuration.

Go to node article form and you can see the captcha(for non admin)

Note:

Configure the captcha setting as per your requirement.


Textfield default value to user email NOT WEBFORM

In your form function, you can add global $user; at the top. Then in your #default_value you can use $user->mail.


how do I make JavaScript run after the page is loaded

Did you use $(document).ready or better Drupal.behaviors?

This is from drupal docs:

  When using jQuery it is standard for a large majority of situations to
  wrap almost all code inside the $(document).ready() function, like
  this:

$(document).ready(function () {
  // Do some fancy stuff.
});

  This ensures that our code will only run after the DOM has loaded and
  all elements are available. However with Drupal there is an alternate
  better method; using the functionality of Drupal.behaviors and once().
  If used properly this will ensure that your code runs both on normal
  page loads and when data is loaded by AJAX. The Drupal.behaviors
  object is itself a property of the Drupal object, and when we want our
  module/theme to add new jQuery behaviors, the best method is to simply
  extend this object.

  A really basic example:

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    // Using once() to apply the myCustomBehaviour effect when you want to do just run one function.
    $(context).find('input.myCustomBehavior').once('myCustomBehavior').addClass('processed');
    // ... left out the more complex examples
  }
};

Quote from JavaScript API in Drupal 8


Why is my property being rendered when I don't call render?

content.video_url contains a build array of the field which Twig renders automatically, including the HTML markup of the field template.

To print the raw string value use the entity object which stores the field, node in node.html.twig

{{ node.video_url.value }}

or paragraph in paragraph.html.twig:

{{ paragraph.video_url.value }}


How to setup Recaptcha on pages cached by Varnish?

CAPTCHA and reCAPTCHA modules are incompatible with page caching.


Delete node references for some content types only

Your code can be made more concise using Drupal APIs. It's rare that DB queries are required in Drupal 8, as the system generally has APIs that handle it for you. Here's how I'd do what you're trying to do. I think the key you were looking for is the line with in_array().

// Load all 'some_content_type' nodes.
$properties = [
  'type' => 'some_content_type',
];
$nodes = \Drupal::entityTypeManager()->loadStorage('node')->loadByProperties($properties);

foreach ($nodes as $node) {
  // Loop through the entities referenced by the field.
  foreach ($node->get('my_reference_field')->referencedEntities() as $entity) {
    // Only act if the entity is not one of the given types.
    if (!in_array($entity->bundle(), ['type_1', 'type_2'])) {
      // Delete the entity.
      $entity->delete();
    }
  }
}


fatal error when i want to disable apachesolr module

Updated:

Point from @kiamlaluno is correct, the apachesolr_stats has apachesolr listed as a dependency. Therefore, in order to disable the apachesolr, you should first disable the apachesolr_stats (and possibly other dependent modules).

I suspect that this issue comes from cached blocks, when I look at the trace you posted. Try to clear the cache and/or disable the apachesolr_stats block before trying to disable the apachesolr module.

Original:

You should try to disable the apachesolr_stats module first.
If you are using drush, this would be the command:

drush dis -y apachesolr_stats

If you don't have drush, you can also use MySQL/PHPMyAdmin commands, here are some links with examples:

Disabling modules:
https://www.drupal.org/node/157632

Clearing cache:
How do I clear cache using an SQL query?  [if that answer works for you, you can upvote ;) ]
https://www.drupal.org/documentation/clearing-rebuilding-cache

Good luck!


To get a table in drupal 7 same as content_type_[your_field_name] in drupal 6?

That depends what fields you have defined in your content type.

An easier way is to load the node object and fetch your data from it.

$node = node_load($nid);

If you install the Devel module you can do dpm($node); and find how to access all data attached to your node.


How to create a Content Type that reuses data from existing Content Type?

You can use Entity reference:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field)

And the Inline Entity Form module:

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.

Others similar modules to Inline Entity Form:

Entityreference Autocreate

  A deliberately simple way to invent nodes on the fly in order to refer to them via entityreference.

References dialog (beta2 release only)

  This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog.

Autocreate Node Reference

  Autocreate Node Reference adds a node reference field and automatically creates the referred node by cloning a template node.

Node Reference Create

  Node Reference Create is an enhancement to the nodereference
  autocomplete widget that allows users to reference non-existent nodes.

Entity connect (rc5 release only)

  It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.

  The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.

EDIT: The module most used is Inline Entity Form, but it doesn't works with the Automatic Nodetitles module, but I know that Entity connect works fine with it. In addition with Entity connect you can edit existing entities. In my case I prefer Entity connect.


How can I programmatically load and display all available blocks?

Using the service plugin.manager.block we will get all blocks available definition.

$blockManager = \Drupal::service('plugin.manager.block');

$contextRepository = \Drupal::service('context.repository');

// Get blocks definition

$definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());

To get details about one specific block you can use below code.

print_r($definitions['help_block']);


How to View of commerce products with image from product_variation

Here's how I did mine :

View of products
Add relationsip: variation image
Add that relation in the fields displayed (You'll now get all the images for the product
Add a field Product variation delta
Add a filter with the delta which equals to 0 (which will show the image of the first variation).

It's not perfect as if the first variation as no images, it think it won't show up... But it should fits quite some cases.


Classes to differentiate between different status messages?

I've been looking around in core a bit and found a solution from the classy theme. Copying its status-messages.html.twig file to my theme solves the problem since the type classes for each message are being set there.

{{ attach_library('classy/messages') }}
{% block messages %}
{% for type, messages in message_list %}
    {%
    set classes = [
    'messages',
    'messages--' ~ type,
    ]
    %}

I think this logic in views is a bit weird.


Swiftmailer just sends emails ... it doesn't let you create HTML / plaintext content for emails.
For ease of setting this all up you likely want to use a module that supports the Mime Mail module and then at least use something like Previewable Email Templates (PET) module. Quote from the PET module page:

The Previewable Email Template (PET) module lets you create email templates, with token substitution, which can be previewed by the user before sending. The emails can be sent to one or many email addresses in a flexible way, and the recipients may or may not be Drupal account holders (users).
PET stores templates in a db table, not the variables table, so there is none of the memory usage which goes with the latter.
PET templates are in one place for easy management by site administrators. Emails can be sent one of three ways:

interactively, from a link.
programmatically, in response to any situation.
via a Rules action (D7 only).


You're not using theme_get_setting() quite right at the moment; the first argument should be the name of the setting, not a default value.

For example, your element defined as $form['z_email'] should look like this:

$form['z_email'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Email'),
  '#default_value' => theme_get_setting('z_email'),
  '#description'   => t("Global Email Id for ZealInd site."),
);


array_keys() expects parameter 1 to be array, null given in drupal_schema_fields_sql()?

You've forgotten to return anything from your implementation of hook_schema().

Just add return $schema; to the end of the function, and re-install your module.


Change the value of a taxonomy field on cron run

You store the value returned from \Drupal::entityTypeManager()
    ->getStorage('node') in $storage, but you don't use it. On the next line you use \Drupal::entityQuery(). (I don't recommend it, as it will be deprecated in Drupal 9; you should use the entity type manager.)

The code I would use is the following one.

  use Drupal\Core\Datetime\DrupalDateTime;

  // Build Drupal DateTime & set correct format for your query
  $curent_time = new DrupalDateTime('now');
  $curent_time = $curent_time->format('Y-m-d\TH:i:s');

  // Get Entity Manager to build your query
  $storage = \Drupal::entityTypeManager()
      ->getStorage('node');

  // Get all Nodes satisfing your conditions
  $nids = $storage->getQuery()
      ->condition('type', 'article')
      ->condition('field_verification_status', 272)
      ->condition('field_article_expiry_date', $curent_time, '<=')
      ->execute();

  // Load all Node entities according to their IDs
  $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  // Do whatever you want with Nodes
  foreach ($nodes as $node) {
    // Do something
    $node->save();
  }

See also

DrupalDateTime
DateTime in queries


How do I export Entityform submissions to CSV?

My problem was that I installed Views Data Export after installing Entityforms.

I had to go to the Entityforms view (which is the automatically generated admin view showing the form's submissions), click the arrow next to "Edit View Name/Description" and click "Revert View".

Now a CSV/XML export button shows up on the Submissions view, and I can export happily.


using drush php-eval db_query() are there differences with db_query() from code?

I don't know this for definite but conceptually speaking, if Drush didn't use a standard Drupal bootstrap to perform these tasks it would have to re-implement all of that functionality itself.

Drush uses your site's settings.php file for the database connection, which leads me to believe it will also have access to things like $db_prefix.

I think it's safe to say exactly the same thing is happening when you run db_query() from Drush as if you run it from any other bootstrapped instance of Drupal.


This was most likely caused by a rather long script that was timing out. The IPCCommTimeout on your virtual server is set to 40 seconds. If you encounter this problem again, you could edit the Apache directives that apply to this virtual server in /etc/apache2/sites-available/test.com.conf and set IPCCommTimeout, for example, to 300.

If you are using Virtualmin

Chose the virtual server that you want to edit from the drop-down
menu
Go to Services -> Configure Website -> Edit Directives
Modify IPCCommTimeout from 40 to, for ex. 300 (seconds)


Exposed filter in view should display all available values in select box

A little bit more research would have helped, I found out myself how to do this. (Though I don't know if it would work without custom code.)
I hooked into hook_form_FORM_ID_alter() inside my theme (would also work in a custom module) and altered the form like this:
function MYTHEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-MYVIEWID-MYFORMID') {
    $nids = \Drupal::entityQuery('node')->condition('type', 'article')->execute();
    $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
    $options = ['' => 'All'];

    foreach($nodes as $nid => $node) {
      $value = $node->get('field_article_year')->getString();

      if (isset($value)) {
        $options[$value] = $value;
      }
    }

    asort($options, SORT_NUMERIC);

    if (isset($form['article_year'])) {
      $form['article_year']['#type'] = 'select';
      $form['article_year']['#options'] = $options;
      $form['article_year']['#size'] = 1;
    }
  }
}


I am sure that there is developer mistake here, we have something like  you guested,a global $user information  overwrite by developer code,I suggest you found when this happened,when a comment submit?when a specified form submit and .... ?
I think in custom module your developer first  write global $user; and in continue define $user variable,I suggest you search for global $user then look at afterwards codes.


Your first option is to simply inspect the html of the form, it should have identifying markup in the HTML which you can then use to grep all your modules for.

Your second option is to implement hook_form_alter and output $form to see which form is generating it and whether there are any identifying markers there. You can use kpr() to output the results of $form using the Devel module to get nicer looking output. You can also use hook_form_alter to remove the fieldset if you want.


How to theme views fields template to display a gallery?

I would recommend going via Views Templates, take a look at views-view-fields.tpl.php template. From there you should be able to duplicate and modify the views content for the thumbnail part.


Preventing user creation, but allowing edit

You might want to use the Administer Users By Role module. The 7.0-2.x version depends on the Chain Menu Access API.

After both modules have been installed and enabled, you will be able to grant user edit but not user add permissions to certain roles within the /admin/people/permissions form.

Nice side-effect: The user editors won't be able to alter the site admin's profile, if you don't allow it, as it could cause serious problems.


Access Individual Fields - Contact Form - Swiftmailer

This definitely isn't a very nice solution, but it does "work".

I created a module, and added this into the .module file.

function modulename_mail_alter(&$message)
{
  if(empty($message['params']['contact_message'])) {
    return false;
  }

  //$message['body'][1] = str_replace("\n\n\n\n",'',$message['body'][1]);
  //$message['body'][1] = str_replace('   ','',$message['body'][1]);
  $contactMessage = $message['params']['contact_message'];

  // Build message body
  //$message['body'][0] = [];
  $message['body'][1] = [];
  $message['body'][1] = "

";

  if($contactMessage->hasfield('field_your_name')) {
    $message['body'][1] .= "

Full Name:
";
    $message['body'][1] .= $contactMessage->get('field_your_name')->getString() . "

";
  }

  if($contactMessage->hasField('field_email_address')) {
    $message['body'][1] .= "Email Address:
";
    $message['body'][1] .= $contactMessage->get('field_email_address')->getString() . "

";
  }

  if($contactMessage->hasField('field_telephone')) {
    $message['body'][1] .= "Telephone:
";
    $message['body'][1] .= $contactMessage->get('field_telephone')->getString() . "

";
  }

  if($contactMessage->hasField('field_mobile')) {
    $message['body'][1] .= "Mobile:
";
    $message['body'][1] .= $contactMessage->get('field_mobile')->getString() . "

";
  }

  if($contactMessage->hasField('field_company')) {
    $message['body'][1] .= "Company:
";
    $message['body'][1] .= $contactMessage->get('field_company')->getString() . "

";
  }

  if($contactMessage->hasField('field_enquiry_type')) {
    $message['body'][1] .= "Enquiry Type:
";
    $message['body'][1] .= $contactMessage->get('field_enquiry_type')->getString() . "

";
  }

  if($contactMessage->hasField('field_version')) {
    $message['body'][1] .= "Version:
";
    $message['body'][1] .= $contactMessage->get('field_version')->getString() . "

";
  }

  if($contactMessage->hasField('message')) {
    $message['body'][1] .= "Message:
";
    $message['body'][1] .= $contactMessage->get('message')->getString() . "

";
  }
}

So basically I clear the message, and then build it up again...


Create link to views page that preselects the filters of an entire vocabulary?

Based on the URL provided:

function MODULE_NAME_build_taxonomy_views_link($taxonomy_tid) {
  $vocabulary = taxonomy_vocabulary_load($taxonomy_tid);
  if (!$vocabulary) {
    return;
  }
  $term_ids = array();
  foreach (taxonomy_get_tree($taxonomy_tid) as $term) {
    $term_ids['tid'][] = $term->tid;
  }

  return l($vocabulary->name, 'resources', array('query' => $term_ids));
}


What you're actually looking to do is to implement a custom Views Display Extender plugin (https://api.drupal.org/api/views/views.api.php/group/views_plugins/7.x-3.x).

It's not particularly trivial and I got most of my information from this wonderful tutorial here: How to write a Views Plugin Display Extender (D7) by Bryan Ollendyke

Here's a basic outline:

-create a custom module (let's call it mymodule) and implement hook_views_api().

/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule'),
  );
}

-Create a mymodule.views.inc file (remembering to add the file to your mymodule.info file) and implement hook_views_plugins(). It should look something like this:

/**
* Implements hook_views_plugins().
 */
function mymodule_views_plugins() {
  $path = drupal_get_path('module', 'my_module');
  $plugins = array();

  $plugins['display_extender'] = array(
    'mymodule' => array(
      'title' => t('Some Setting'),
      'help' => t('A description of the setting.'),
      'path' => $path,
      'handler' => 'mymodule_views_plugin_display_extender',
    ),
  );

  return $plugins;
}

-Note the "handler" index in the above array. You'll need to implement that in a file called mymodule_views_plugin_display_extender.inc (again, remembering to add that in your mymodule.info file). The implementation should look something like this:

class mymodule_views_plugin_display_extender extends views_plugin_display_extender {
  /**
   * Provide a form to edit options for this plugin.
   */
  function options_definition_alter(&$options) {
    $options['my_setting'] = array(
      'default' => 0,
    );
  }

  /**
   * Provide a form to edit options for this plugin.
   */
  function options_form(&$form, &$form_state) {
      parent::options_form($form, $form_state);

      if ($form_state['section'] === 'mymodule') {
        $form['my_setting'] = array(
          '#type' => 'checkbox',
          '#title' => t('Some Setting'),
          '#description' => t('A sample checkbox.'),
          '#default_value' => $this->display->get_option('my_setting'),
        );
      }
  }

  /**
   * Handle any special handling on the validate form.
   */
  function options_submit(&$form, &$form_state) {
    $this->display->set_option('my_setting', $form_state['values']['my_setting']);
  }

  /**
   * Provide the default summary for options in the views UI.
   *
   * This output is returned as an array.
   */
  function options_summary(&$categories, &$options) {
    $options['mymodule'] = array(
      'category' => 'other',
      'title' => t('Some Setting'),
      'value' => ($this->display->get_option('my_setting')) ? 'Yes' : 'No',
      'desc' => t('Set a setting.'),
    );
  }

}

After all that your mymodule.info file should look something like this:

name = My Module
description = Sample views display extender
core = 7.x
version = 7.x-1.0

dependencies[] = views

files[] = mymodule.views.inc
files[] = mymodule_views_plugin_display_extender.inc

If that all works out, you should see a setting show up under "Other" (you can change that using the 'category' in the options_summary implementation in mymodule_views_plugin_display_extender.inc.

After that, in your module, you can access the option from the view using something like:

$view->display_handler->get_option('my_setting');

For instance, if you were implementing `hook_views_post_execute().

/**
 * Implements hook_views_post_execute().
 */
function mymodule_views_post_execute(&$view) {
  $my_setting = $view->display_handler->get_option('my_setting');
}


Using rules to populate a field with the output of pdfprevew

From your question, I seem to understand that this is your goal (= quote from your question):

  ... use rules to automatically populate the cover image field with the generated cover whenever there is a generated cover image, and the cover image field is empty.

There seem to be at least 3 ways to achieve that goal, as further detailed below ...

Solution 1

This solution elaborates on one of your comments, which is like so:

  I was thinking at node view, might be a good time just to be sure that the preview had had a chance to be saved. I'd then need a condition to check whether the cover field already has a value and one to see if either there is a pdfpreview available or if the first file in the field is a pdf.

This could indeed work, but the crucial Rules challenge here is that there is no such event like "BEFORE" a node is being viewed. Because the "clue" about what Rules EVent "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

My advice: only use this if all other options (solutions) fail. Read on for what IMO is a better solution.

Solution 2

This solution elaborates on one of your comments, which is like so:

  ...  at node create and node update may be a much better time, if pdf preview has had a chance to do what it does by the time those events fire ...

Using this approach, you'll run into another Rules challenge ... I.e what's detailed in issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

My advice: using this solution is a kind of risky, because of that above mentioned Rules challenge. Read on for what IMO is a better solution.

Solution 3

A possible compromise to avoid the kind of issues described in Solution 2, is to implement what needs to be done into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected). Read on for how you can get this to work ...

Step 1 - Create a Rules Component

Have a look at this Rules Component, in Rules export format:

{ "rules_populate_an_output_field_with_an_input_field" : {
    "LABEL" : "Populate an output field with an input field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_to_update" : { "label" : "Node to be updated", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node-to-update" ], "field" : "field_image" } },
      { "NOT data_is_empty" : { "data" : [ "node-to-update:field-image" ] } },
      { "entity_has_field" : { "entity" : [ "node-to-update" ], "field" : "field_cover_image" } },
      { "data_is_empty" : { "data" : [ "node-to-update:field-cover-image" ] } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node-to-update:field-cover-image" ],
          "value" : [ "node-to-update:field-image" ]
        }
      },
      { "entity_save" : { "data" : [ "node-to-update" ], "immediate" : "1" } }
    ]
  }
}

This Rules Component used a "node" (the node to be updated) as a parameter.

This is what the Rules Conditions in the above Rules Component are about:

It uses a parameter "Node to be updated".
It processes the fields with machine names field_cover_image and  field_image (adapt the machine names to fit your own field names, prior to trying to import this Rules Component in your own site).
It has a rules condition "Entity has field" (twice) to make those fields available for subsequent processing.
It has a Rules Condition for each of both fields to check that their initial value (before the Rules Component's actions will be triggered), to match your requirement like "... populate the cover image field with the generated cover whenever there is a generated cover image, and the cover image field is empty...".

This is what the Rules Actions in the above Rules Component do:

Set the value of field field_cover_image equal to the value of field  field_image.
Save the node (to ensure the updated value actually gets saved ...).

Step 2 - Create a Rule to schedule the Rules Component

This one is pretty easy, here is a rule (in Rules export format) that will "schedule" the execution of the Rules Component from the previous step:

{ "rules_schedule_image_population" : {
    "LABEL" : "Schedule image population",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_cover_image" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_populate_an_output_field_with_an_input_field",
          "date" : "+1 min",
          "identifier" : "Schedule-image-population-[node:nid]",
          "param_node_to_update" : [ "node" ]
        }
      }
    ]
  }
}

The rule uses as Rules Event "After creating a new node", or "After updating an existing node".

To avoid wasting resources, we only want to trigger the Rules Action for nodes that do have that field_cover_image field we want to populate (hence the Rules Condition).

And all this rule has to do (as Rules Action), is to schedule the execution of the Rules Component from the previous step. Adapt the delay to fit your needs (I've set it to just 1 min).

My advice: go for solution 3 (tested in my own setup, works like a charm ...)

Easy, no?


Adding gmap markers programmatically with a module

I wouldn't even get that fancy. Just use drupal_add_js to send an array of markers to a page, then call drupal_add_js to call your basic javascript that instantiates your map. Gmap hasn't been updated for V3 of the Google Maps API (so you need to go get a key, and you need to update the key when you move sites) and I've found that it's easiest, especially if you only need it on one page, to just call your own stuff.

EDIT: Maybe an example will help.

I had to do something similar where I wanted custom markers based on a set of results. In my preprocess I did:

  foreach($variables['results'] as $key => $result) {
    $store = node_load($result);
    $markers[$key] = array(
        'latitude' => $store->field_lat[0]['value'],
        'longtitude' => $store->field_lon[0]['value'],
        'title' => $store->title,
    );
  }
  $settings['markers'] = $markers;

  /* Add in the settings first */
  drupal_add_js($settings, 'setting');
  /* Then add in the javascript to instantiate map */
  drupal_add_js($module_path . '/map.js');

Then in my map.js:

Drupal.behaviors.map = function(context) {

  var initialZoom = true;
  mapInit();
};

function mapInit() {
  /* Get the markers variable set in PHP */
  var markers = Drupal.settings.markers;

  var myOptions = {
    mapTypeId : google.maps.MapTypeId.ROADMAP,
    scrollwheel : false,
    draggable : false,
    disableDefaultUI : true
  };
  var mapElement = document.getElementById("map");
  var map = new google.maps.Map(mapElement, myOptions);
  /* Loop through my markers and add them to the map */
  $.each(markers, function(index, value) {
    var latlng = new google.maps.LatLng(value.latitude, value.longtitude);
    bounds.extend(latlng);
    var marker = new google.maps.Marker({
      position : latlng,
      map : map,
      title : value.title
    });
  });
}


You need to change #type value to date_select

So your code should look like this

$form['dob'] = array(
    '#type' => 'date_select',
    '#date_format' => 'm-d-Y',
    '#title' => 'Date of Birth',
    '#required' => TRUE,
);

If you want text field instead of select dropdown menu you can change date_select to date_text


It turned out that there was nothing wrong with my theme.  I installed the theme in a new installation of drupal and the search block was available.


array_flip(): Can only flip STRING and INTEGER values with nested Field collection

The problem is with your code.

You need to pass entity_load an array of entity IDs but the structure of a field on an entity is not just an array of IDs.

$item->field_paragraph is an array of field items and field items can come in many different structures based on the type of field.
Then there is also the ability to have different languages so the language is part of the structure.

The basic structure is like this:

$entity->field_name['language code'][delta]['column_name']

I think for field collections the entity id is stored in the "value" column so you would access it like this (this assumes you aren't using multiple languages):

$item->field_paragraph[LANGUAGE_NONE][0]['value']

That would get you the entity ID of the first item for that field.

It is generally considered better though to use field_get_items() like this:

// Pass a lang code into field_get_items() if you have a multilingual site.
if ($chapter_items = field_get_items('field_collection_item', $node, 'field_chapter')) {
  $chapter_ids = array();
  foreach ($chapter_items as $chapter_item) {
    $chapter_ids[] = $chapter_item['value'];
  }
  $chapters = entity_load('field_collection_item', $chapter_ids);
  foreach ($chapters as $chapter) {
    // Some echos from fields in $chapter.

    // Pass a lang code into field_get_items() if you have a multilingual site.
    if ($paragraph_items = field_get_items('field_collection_item', $chapter, 'field_paragraph')) {
      $paragraph_ids = array();
      foreach ($paragraph_items as $paragraph_item) {
        $paragraph_ids[] = $paragraph_item['value'];
      }
      $paragraphs = entity_load('field_collection_item', $paragraph_ids);
      foreach ($paragraphs as $paragraph) {
        // Some echos from fields in $paragraph.
      }
    }
  }
}

When you are using entities and fields like this it is a good idea to do some debugging to check out the actual structure of the data you're trying to use.


View Field, Insert View, View Reference, Block Reference, Insert Block: which to choose to embed a view in a page

Option 1:

Just create a page for the view.

You can set which permission or role should have access to the page.

If you need to display content above or below the view use the header and footer.

Option 2

Use hook_node_view() and views_embed_view() to add the view as a field to the node you want to target:

function hook_node_view($node, $view_mode, $langcode) {

  // Add whatever logic you want here to only target the nodes you want
  if($some_check == TRUE) {
    // Add a new field to the content array
    $node->content['view_field'] = array(
      // Render you view
      "#markup"=> views_embed_view('view_name', 'view_display'),
    );
  }
}

You say it's better to not write PHP for maintenance reasons. I would argue the exact opposite - it's much easier to version control code than it is configuration stored in the DB.


How to programmatically remove a user from an organic group

Part of me thinks that og_membership_delete would be a good option, you can pass the entity ID in as a parameter (and by "can", I really mean "need to"). Also, og_ungroup seems useful as well.

You can find more functions that OG defines at: http://www.drupalcontrib.org/api/drupal/contributions!og!og.module/7

Here's an example of og_ungroup:

og_ungroup('node', $gid, 'user', $uid);


How do I conditionally change the print.css stylesheet to use media = all

I ended up using hook_css_alter(&$css)

<?php
  function MYMODULE_css_alter(&$css) {
    if (isset($_GET['print']) && $_GET['print'] == 'true') {
      $css[path_to_theme().'/css/print.css']['media'] = 'all';
    }
  }
?>


Views hardcodes RIDs in when you export or featurize a view. That means that if the role has a different RID on one site than on the other, you'll have issues with Views giving permissions to the wrong users.

One way I've gotten around this is to hack the exported view, and where it would say something like

$handler->display->display_options['access']['role'] = array(
  4 => 4,
);

I have

$rid = ($role = user_role_load_by_name('administrator'));
$handler->display->display_options['access']['role'] = array(
  $rid => $rid,
);


No, not really. JavaScript is the only way to have content (including forms) change on a page without relaod. Now you have two ways to go around it:

Make all choices available in all 3 downloads and only hide unneeded ones using JavaScript. That way if someone will not have JS enabled, he will see all choices and will be able to make his selection. Don't forget to test if his selection is sane on the server side!
Use multi-step form. See this question and accepted answer. That way you will be able to ask one thing at a time, serving new steps using good old HTTP.


Simply pass the “page” parameter with the request, like ‘api/foo/bar?page=1’. Views will return the next set of results as you increment the page number. You can do the load more interaction however you want on the front end so long as you specify the page and keep track of total results.


Pass custom query strings across website

That's probably a bit messy. Have you considered using cookies or even the session variable?

Edit:
Turns out it might actually be possible and without much fuss! Thanks OP for raising the question and making us question (and research) this a bit.

Drupal has a hook to rewrite all URLs (hook_url_outbound_alter), which coming to think about it makes total sense.

Basically you can use this hook to grab a session variable or a cookie - you still want to store it somewhere just so that in case you lose it at some point you can easily retrieve it and recover the navigation - and rewrite the URLs according to whatever rules you need.

Here's a sample for future reference, not mine just adding it here so we don't lose it if the link breaks:

<?php
/* Helper function for using strpos with an array of strings.
 */

function strposa ($haystack, $needles) {
    $bool = false;
    foreach ($needles as $needle) {
        if (strpos($haystack, $needle) !== false) {
            $bool = true;
        }
    }
    return $bool;
}

/* Implements hook_url_outbound_alter
 */

function rl_int_url_url_outbound_alter(&$path, &$options, $original_path) {
    //Break path into an array
    $arr = explode('/',$path);
    //Get country list and exclude paths
    $c_list = array('us','ca');
    $system_paths = array('admin', 'user', 'sites', 'system');
    $exclude_paths = array('node/add', 'sitemap');
    //If the path contains a system path in the first argument, or has an exclude path in the full path string, do not set a prefix.
    if (in_array($arr[0], $system_paths) || strposa($path, $exclude_paths)) {
        $options['prefix'] = '' ;
    //OK, it's not an excluded path. If the path doesn't have the prefix already, add a prefix.
    } else if (in_array($arr[0], $c_list) == false) {
        $c = $_COOKIE('Drupal_visitor_country');
        $l = $_COOKIE('Drupal_visitor_language');
        $options['prefix'] = $c . '/' . $l . '/';
        //Special case: remove "home" from the path if it's the home page, so that it's example.com/us/en instead of example.com/us/en/home.
        if (drupal_lookup_path('alias', $path) === 'home') {
            $path = '';
        }
    }
}
?>

Hope this helps!


How do you edit content of a Drupal\Core\Render\Markup instance via a preprocess function in Drupal 8?

You can't edit the content. There is no public method to change it.

Usually you simply override it with a new instance:

$variables['fields']['title'] = Drupal\Core\Render\Markup::create('New content');

The double underscore indicates a magic function, which would be called automatically if you use the object in a string context. This is readonly.

If you want to add a string to the old markup, that would be an example how the magic function __toString() works:

$variables['fields']['title'] = Drupal\Core\Render\Markup::create($variables['fields']['title'] . '!!!');


Finaly I found the problem.
The real problem was not because the user had this or this role.

But the view that i wanted to show had specifc class for some objects for user with Administrator Role.

Example :
an 'article' can have 'contextual' class when the user connected had Administrator Role.
the same 'article' does't have it  when the user connected didn't have Administrator Role.

I am new in drupal 8, so...


subfolder installation user block login and destination issue

Finally i found the issue of redirection. I have checked form.inc file from where i have found that drupal_goto function from common.inc file is called.

Now by debugging that form.inc i found that drupal_redirect_form calls drupal_goto with different options. In subfolder case (i.e. my case) drupal_goto function i have found that $path has value like '/drupal6/' default. So what i have hacked is

$folder_name = '/drupal6/';
$length = strlen($folder_name);
$path_check = substr($path,0,$length);
$path_len = strlen($path);
$remaining_path = '';

if($path_check == $folder_name) {
    $remaining_path = substr($path,$length,$path_len);
    echo $path = $remaining_path;
}

So now my problem of adding two folder name like 'http://localhost/drupal6//drupal6/admin/settings/site-information?destination=admin%2Fsettings%2Fsite-information/' have been solved but as you know that this is core hack and i dont like it. Any better solution???

I know that if i transfer this site from my localhost to internet than that would not create any problem without making this kind of small hacks.


How can I use a token to display the node body summary?

Correct tokens are [node:body] and [node:summary].
Yoy should probably check http://drupal.org/node/1295524 if you experience problems with summary tag


How do I access the first value of a multiple value text field using replacement patters inside a rule?

Have a look at the tutorial about "Using Entity Reference in Rules". Starting from about 2:50, and up to about 4:15, it shows how in a Rules Action you can access the 1st, or 2nd, or ... value of a multiple value field, provided you also included a Rules Condition like "Entity has field" (related to the multi value field). So if you have a content type with a multi value field with (say) myfield, then you'd use node:myfield:0 for the very first value of that field (or node:myfield:1 for the 2nd value, etc).

However, the same tutorial, starting from about 4:20 and up to about 6:40, also explains how to loop through multiple-value references, using a Rules loop, and which I think is more appropriate to answer your question.  If you're not familiar with such loops, then I strongly recommend to also have a look at the tutorial titled "Lists and loops".


How to pass multiple target_id/values field using entity reference prepopulate?

So if you want to create this link: node/add/page?field_bar=1,2,3

You need to put a comma between each nid, so implode() is what you want.

E.g.

$l = l( t('Create Package'), 'node/add/package',   array('query' => array('field_product_food' => implode(',', $nids))  ));


I think you should not think about language and let Drupal handle it.

If you install locale module and configure it correctly you will gain what you need:

Install the Locale, Internationalization and Taxonomy translation modules. (The latter is optional.)
When adding a taxonomy term, select "Multilingual options->Per language terms."
When adding a content type, select "Workflow settings->Enabled."
when adding content, select language.


How to properly set up Drupal Console on Windows 7

This will surely help you debug: https://evolvingweb.ca/drupal-console-windows-devdesktop-troubleshooting

And here is a guide explaining how to do it from scratch: https://evolvingweb.ca/blog/installing-drupal-console-windows


Invert shipping rate position with VAT field

I assume that you know how to create a module and what a hook is, you can use hook_commerce_price_component_type_info_alter like this:

<?php
function mymodule_checkout_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  if (isset($components['commerce_price_formatted_amount']['weight'])){

    // Get the row weight of total sum.
    $last_weight = $components['commerce_price_formatted_amount']['weight'];

    // Increase the row weight of the total row, so we can place the vat directly before.
    $last_weight = $last_weight + 100;
    $components['commerce_price_formatted_amount']['weight'] = $last_weight;
  }

  if (is_array($components) && count($components)>0){
    foreach ($components as $name => &$component){

      // Set the weight of the VAT row to the last position before the total sum.
      if (substr($name, 0, 3) == 'vat'){
        $component['weight'] = ($last_weight-1);
      }
    }
  }

  return;
}


Content types on "Add Content" randomly re-sort themselves

You can check in which order the content types are loaded from the configuration storage with drush:

drush ev "print_r(array_keys(\Drupal::entityTypeManager()->getStorage('node_type')->loadMultiple()))"


How to access Field-settings in the widget formatter

You can take number.module from the CCK package as an example; it allows prefix and suffix values in the field settings that are rendered in the formatter.

In theme_number_formatter_generic() the field settings are retrieved using $field = content_fields($element['#field_name'], $element['#type_name']);. The values are then taken from the $field array, sanitized and added to the output.


in product title on new product type drupal commerce kickstart

Go to admin/structure/types, and click "Manage display" for your content type, which is a product display for your new product variation.
Choose the "Product list" display, and make sure the title's format is set as Default.


Programmatically setting video_embed_field URL

Actually, the last try in my choices seems to work after all.
 $node->field_video = ["value" => $item["video"]];

I must have done something dumb with my editor like not saving the changes...
Well, maybe someone else finds the info here...


How can you reference taxonomy term by another field in Yaml file?

Here is a simple migration for looking up a taxonomy term by name based on the text in a CSV.

taxonomy_field_name:
  plugin: entity_lookup
  source: name_of_source_column
  value_key: name
  bundle_key: vid
  bundle: name_of_taxonomy
  entity_type: taxonomy_term

For example, if you have a taxonomy called fishes, and your CSV has a column called fish, and your node has a field called field_fish which is an entityreference to a taxonomy term of the fishes vocabulary, and there is a taxonomy term "Carp" with entity ID 14

field_fish:
  plugin: entity_lookup
  source: fish
  value_key: name
  bundle_key: vid
  bundle: fishes
  entity_type: taxonomy_term

Given a row in the CSV with "Carp" set as the fish, this will assign entity id 14 to that field.

Does that help?  I am not sure what you mean by "a given field can be referenced by any other field from my site".


How do I display Search API Facets and Openlayers Proximity search in one view?

The "facets block" type that drunken monkey mentions on the issue you link to, is simply a type of views "Display", you can see below where you add one:

I haven't used the proximity filter, nor much of Search API, so I can't really give you an answer with better details. It seems to be like drunken monkey has actually answered the question in the issue queue, and perhaps you need to specify more precisely where you have a problem, to get better help.


It seems like it is a pure markup error. I should have the statement placed in my main markup. Updated template looks like the snippet bellow.

<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>
  <div class="<?php print $classes; ?>">
<?php if ($options['alignment'] == 'vertical') : ?>
<?php foreach ($columns as $column_id => $column) : ?>
  <div class="<?php print trim($column_classes[$column_id]); ?>">
  <?php foreach ($column as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

<?php endforeach; ?>
<?php else : ?>
  <?php foreach ($rows as $row_id => $row) : ?>
    <div class="<?php print trim($row_classes[$row_id]); ?>">
  <?php foreach ($row as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

  <?php endforeach; ?>
<?php endif; ?>
<?php if ($row_id % 2 == 0 && $row_id !=0): ?>

        <?php print views_embed_view('display_random_snippet_home_1', 'block'); ?>

<?php endif; ?>


Making new variable for a theme function shows an error notice

You should use THEME_preprocess_comment_wrapper(&$variables) to alter comment wrapper variables.


Configuration management and site specific configuration

There are multiple ways to override the configuration on a per-environment base.

The config split module is a great tool for splitting complex configurations between the environments. E.g. having some development modules enabled/configured in development, but not installed/no database stored configuration for them in production.

Besides splitting entire module configurations, it also allows you to split single configuration items like parts of your solr settings. You can have them stored in separate configuration folders. These folders can be used as argument when running drush cim <folder> to get them re-imported to a site.

However, this kind of configuration management most often is overly complex, when your configuration differs slightly only between your environments (e.g. some URLs, IDs or flags, while other settings keep unchanged).

The better approach for minor differences might be overriding the configuration within your settings.php, or even better a settings.local.php file, which can be enabled by uncommenting the according inclusion lines at the end of your settings.php (given it's based on default.settings.php):

/**
 * Load local development override configuration, if available.
 *
 * Use settings.local.php to override variables on secondary (staging,
 * development, etc) installations of this site. Typically used to disable
 * caching, JavaScript/CSS compression, re-routing of outgoing emails, and
 * other things that should not happen on development and testing sites.
 *
 * Keep this code block at the end of this file to take full effect.
 */
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

You can then override your environment specific configuration using the $config array in your settings.local.php:

$config['search_api_solr.settings']['site_hash'] = '...';

This will not alter the database stored configuration or the managed configuration imported using drush cim. Instead, it will override the database stored configuration during page load. Therefore, it might be wise to having production values stored in your database/configuration management and config overrides for your local and/or staging environments. Once you remove your overrides from your settings file, the database stored configuration (re-)applies.


An AJAX autocomplete textfield in Drupal 7 doesn't work in Chrome

I found out what causes AJAX error! When I turn on any module with UTF-8 encoding, it causes the error; when I change the encoding to ANSI or to UTF-8 without BOM, everything works. This encoding problem happened only in Google Chrome; in Firefox all encodings work well.


If you have created a node, for instance a "Page" node, by going to "Content" => "Add Content", AND have the Path or Pathauto module enabled, you can give that node the path "news" when you are editing it.
Alternately, you can create a view that is a page, and has that path.

Specifically, the Drupal menu router has to have an entry for the path "news", and know what to serve up.  Blocks and templates don't create that path entry.

More information on creating content can be found at:
https://www.drupal.org/node/120635


Make a views of data entered in composed fields

Write a function in your module/theme that will accept two arguments,

1) the serialized value a:3:i:1;s:3:"First Subfield";i:2;s:4:"Second Subfield";i:3;s:7:"Third Subfield";

2) the name of the key you want to use.

Have it return the value.

Create three new columns that use PHP code in your view,  and pass the appropriate arguments to your module/theme.


How Do I Properly Add Custom CSS Classes And IDs To Drupal 7 Sub Menus

Have you tried the Menu Attributes module? It's easy to use and has great features:

  The module currently allows you to set the following attributes for
  each menu item:

  Id
  Name
  Target
  Rel
  Class
  Style
  Accesskey