FAPI redirect *and* store to local database

EDIT: added option (1) after thinking about this more, haha. It's a much simpler solution.

(1)

If the below is to complex you (and you actually want to POST something) you could form_alter the form and append your own additional FAPI #submit function which uses drupal_http_request() to POST/GET the url with all the submitted form params.

(2)

I think you want to set the destination value from within the #action of the form to be wherever the default webform submit path is and tag on a destination querystring parameter to the action which drupal will then goto after the form has been validated/submitted.

I know you said you tried using #action but I'm talking about the action being the drupal action and destination being a remote url (url-escaped).

Eg, I have customized a login form to use various login backend logic depending on the url of the login: /user/login, /student/login, /staff/login ... etc. I then make the destination of a succcessful login goto a specific drupal page. destination is used by drupal_goto() to redirect the user anywhere -- even an external url.

Here is a small example from code I have in D7:

/**
 * The following 2 functions allow our form overrides to occur.
 */
function MYMODULE_form_user_login_block_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_staff_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function MYMODULE_form_user_login_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_id_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function _MYMODULE_auth_user_login_form_alter(&$form, &$form_state) {
  global $conf;
  $saveForm = $form;
  $form = array();
  # overrides the default validator.
  foreach ($saveForm as $key => $value) {
    if ($key == '#validate') {
      $form[$key] = array();
      foreach ($value as $validator) {
        if ($validator == 'user_login_authenticate_validate') {
          // If we progressed down to this level of nested Alters, we have
          // #auth-destination.
          $type_of_login = $saveForm['#auth-destination'];
          switch($type_of_login) {
            case 'staff':
              // These functions are custom validate functions whose logic is
              // copied/altered from the default
              // 'user_login_authenticate_validate' implementation.
              $validator = 'MYMODULE_auth_staff_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=staff/login&destination=%3Cfront%3E';
              break;
            case 'student':
              $validator = 'MYMODULE_auth_student_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=student/login&destination=student/my-surveys';
              break;
            default:
              break;
          }
        }
        $form[$key][] = $validator;
      }
    }
    else {
      $form[$key] = $value;
    }
  }
  $form['name']['#title'] = ($type_of_login == 'Staff') ? 'Staff Username' : 'StudentCampusID';
  unset($form['links']);
}


ImageStyles does not create thumbnail image while uploading large images

You can restrict the image upload size using field settings in the admin to less than 1 MB and show a help text that max upload size is 1 MB.

Other option already given by Molot.

Hope it will  help you.


How can I search for a specific user on the People administration page?

That's all you can do with core Drupal - it is a little frustrating for sure.  :-)

However, there are lots of contrib modules that let you do more, such as

Advanced User, in which user fields to filter/search by can be configured in the module's settings or
the simpler User search to People Admin which simply puts the user search box on there for you.

Of course, you can also opt to make yourself a user-based view and create an admin page yourself by using relationships and filters.  :-)

Hope one of these helps!


How to create a taxonomy terms "skills" with level "low", "medium", "high"

Without knowing how you're planning to use this in a larger context, here's what I would do:

Create a vocabulary (or possibly just a plain text field with a select list) for "skill"
Create a second field with a dropdown list for skill level (I probably wouldn't use a taxonomy for this).
Make the second field dependent on the first, per this Stackoverflow question about fieldsets and conditions


To overrider the default Access Denied page of the Drupal, you have to change the path of this page.

To change the page path, follow these steps:

Go to admin/config/system/site-information.
At the bottom of the page, there is a Error Pages section.
There is a field Default 403 (access denied) page. Provide your custom panel page link.
And the save it.

I hope it will work.


Creating a file upload field with a translatable title attribute field

What I ended up doing was I used hook_i18n_string_info to define a new "Captions" text group, hook_field_widget_form_alter to attach a new process function to the desired upload widgets, and my callback for hook_field_widget_form_alter cloned the title field (into title_fr for me), then also checked to see if #default_value was a string and used i18n_string_translate to update title_fr's default_value.

What I did and wouldn't recommend doing was I put the translation handling in the submit function for my form. In there I constructed my translation "name" using caption:$field_key::$nid::$field_delta and then calling i18n_string_translation_update($name, $french_caption, 'fr', $english_caption).


Drupal custom page template based on the title of the page

I don't think this is an optimal solution at all, because node titles can easily be changed (and duplicated), but here you go:

function MY_THEME_preprocess_node(&$vars) {
  // This assumes that you are using Pathauto for generating clean URLs.
  // Get the "clean" title.
  $title = pathauto_cleanstring($vars['node']->title);
  // Replace all dashes with underscores. This is necessary for recognizing the
  // template filenames.
  $title = str_replace('-', '_', $title);
  // Add new template variation.
  $vars['theme_hook_suggestions'][] = 'node__' . $title;
}

Note: to make this bulletproof for different languages, alphabets and special characters, make sure you have the Transliteration module installed and set to transliterate strings prior to creating URL aliases. This way if a node title has non-standard character (e.g. Č) it will be transliterated to Latin alphabet (in this case C).


How to choose appropriate token for URL path alias pattern display in URL?

This is the answer:

 [node:field-category:parents:join-path]/[node:field-category]/[node:title]


What's the coding standard for class constants?

The correct one would be:

class Foo {
  const CONSTANT_VALUE = 'bar';
}

For example, quoting after Zend Framework naming conventions (however there are many others for different frameworks, just Google around):

  Constants may contain both alphanumeric characters and underscores.
  Numbers are permitted in constant names.

  All letters used in a constant name must be capitalized, while all
  words in a constant name must be separated by underscore characters.

  For example, EMBED_SUPPRESS_EMBED_EXCEPTION is permitted but
  EMBED_SUPPRESSEMBEDEXCEPTION is not.

  Constants must be defined as class members with the "const" modifier.
  Defining constants in the global scope with the "define" function is
  permitted but strongly discouraged.

It does not explicitely say anything about FOO_CONSTANT_VALUE vs CONSTANT_VALUE, but not using class name in constant name is general practice. Which perfectly makes sense, considering that you are in class scope.


How to make a specific region use a specific template?

I thought Drupal already added the theme hook suggestion for region--name.tpl.php, but if not you can add it yourself with a preprocess function in your theme's template.php file:

function MYTHEME_preprocess_region(&$vars) {
  $vars['theme_hook_suggestions'][] = 'region__' . $vars['region'];
}

Once you clear Drupal's caches your new template file should start being used for that region. It might be worth noting that you'll probably need a copy of the core region.tpl.php file somewhere in your theme folder as well, or the theme registry might not pick up your custom file.


Creating an email newsletter using simplenews

I found this links useful

Designing a HTML newsletter for Drupal

http://drupalsteve.com/node/30

Drupal & Simplenews

http://www.slideshare.net/desk02/dug-simplenews-6192093

Email Newsletters and the Simplenews Module
http://www.group42.ca/email_newsletters_and_the_simplenews_module

and probably

Newsletter subscription management in Drupal with E-mail Marketing Framework

http://www.drupalcoder.com/blog/newsletter-subscription-management-in-drupal-with-e-mail-marketing-framework


How can I have a view reset when an exposed title filter is emptied?

You would need to add jQuery to listen on the textfield change event, or similar. If value is empty then set location to current path without querystring. YMMV


Filter the Node Locations view in the navigation menu

Set up a taxonomy vocabulary (eg Status) with the terms 'active' 'closed' etc, and attach a term reference to the node.

Then filter your view on the term. Have a look at Filter map to show single taxonomy or single content type.


How do I create a rule to display a system message to users that an event is now over?

Rules can be used for this.  Your message will be displayed using drupal_set_message()

Starting at the Admin screen;

Click through Configuration > Rules > Add New Rule
Give it a name and select Content is viewed in React on event. Click Save.
Under Conditions click Add condition

Select Data > Data comparison
Select node:type and click Save
Fill in for your content type and save

Under Conditions click Add condition (again)

Select Entities > Entity has field
Data Selector should have node
Field should have the field you're wanting to check. This should be a date field

Under Conditions click Add condition (again)

Select Data > Data comparison
In Data Selector chose your field. Mine was node:field-end-date
Click Continue.
Under Operator select is lower than
Under Data value select site:current-date
Click Save

Under Actions click Add action

Select the System > Show a message on the site entry.
Enter your Message, select the Message type (this is the drupal_set_message() status), untick Repeat message and click Save

Browse to your expired content to see your message.


Programmaticaly remove a member from a group

The entity type interface (GroupInterface) has a removeMember method; all you need are the relevant entity objects:

if ($account = \Drupal\user\Entity\User::load($user_id)) {
  if ($group = \Drupal\group\Entity\Group::load($group_id)) {
    $group->removeMember($account);
  }
}


Try with items[0]['content'] or if its field of type text you will find the value of the text with items[0]['content']['#text'] or items[0]['content']['#value']


The hint that solved this was in the error message:

for column 'sourceid1'

This column is in the Migration class's map table, where it tries to make a record of what it has processed.  The "fix" for this is to prevent the errant data from getting that far in the system.  I am coding a custom getItem to do the filtering for this issue there.


Last Comment Name field is not removed after account cancellation

The forum module doesn't respond to any user deletion activity so you'll have to build your own solution here. You can create a custom module with a  hook_user_cancel implementation that will:

Check that the canceled user account is being anonymized.
Look up the username's entries in the node_comment_statistics (and other relevant tables).
Execute a UPDATE DB query that replace the name with "anonymous" (or whatever anonymized name you like).


What is the default behavior of the Drupal 7 cache?

To find out all events when page and block cache is cleared - you can search through all modules for using of cache_clear_all() function.

Here is brief list of such events in Drupal core.

Any content is created or updated (nodes, taxonomy terms, comments, etc)
Content permissions are updated.
Block is created or updated.
Vocabulary created, edited or deleted.
Any settings form in admin back-end is submitted (those forms that use system_settings_form()).
User account is created, updated or canceled.

As you see page and block cache is not cleared automatically when any content is deleted.


'access callback' needs to be a function name. The function should return TRUE or FALSE;
From the API:

"access callback": A function returning TRUE if the user has access
rights to this menu item, and FALSE if not. It can also be a boolean
constant instead of a function, and you can also use numeric values
(will be cast to boolean). Defaults to user_access() unless a value is
inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK
items can inherit access callbacks. To use the user_access() default
callback, you must specify the permission to check as 'access
arguments' (see below).
"access arguments": An array of arguments to
pass to the access callback function, with path component substitution
as described above. If the access callback is inherited (see above),
the access arguments will be inherited with it, unless overridden in
the child menu item.

This means you could ommit 'access callback' and use 'access arguments' instead:
// This will be true for users with the access content permission
'access arguments' = array('access content');


How to migrate drupal6 ubercart to D7 commerce

You probably want to look at Commerce Migrate together with Commerce Migrate Übercart that respectively understand how to create Commerce content and read Übercart content.

Commerce Guys already wrote two blogposts, Part 1, and Part 2, on the difference between the two.


List of favorite articles based on number of visitors

In the module list, you've a module named Statistic enable it and you'll have a block that show the articles most visited in the past 7 days or 24 hours.

Also, with Views you'll able to create blocks/pages as you want.


Is it possible to query against the ldap server stored in drupal without reconnecting?

So I assume that you are using the LDAP module?

I've not looked into the code they use however I would expect that they will close the connection before your module runs, and even if they don't the connection won't be a global variable so your module will not have access to it.

If you are writing a custom module then you do have access to the DB - just use db_query and fetch the results, or look in your settings file for your connection details. Then you can connect directly to your DB using software like Navicat.

The table ldap_servers has a field called address. This is where you will find the address to your ldap server.


Views and Panels Newbie... Maybe simple...Hope its simple

I think you would not need panels for two column.

There are two ways I know:

Quick way: You can choose a styling format as grid and define columns as 2
Long way: A View listing can be shown in two columns by styling and template overriding.


Change CCK Nodereference View at runtime

Thanks for the sugs.  I prefer to do everything in code so this was my solution.  I just manually loaded the view given some argument, and parsed the results.

function module_form_nodetype_node_form_alter(&$form, &$form_state)
{
    // Manipulate form after build so we have access to CCK
    $form['#after_build'][] = '_form_afterbuild';
}

function _form_afterbuild($form, &$form_state)
{
    // Custom options list for this nodereference
    $arg = user_access('administer nodes') ? false : true;
    $form['field_fieldname']['nid']['nid']['#options'] = _GetOptions($arg);
}

function _GetOptions($arg=false)
{
    $viewResults = views_get_view_result('view_name', '', $arg);

    $options = array();
    foreach ($viewResults as $row) {
        $optionTitle = $row->title;
        $options[$row->nid] = $optionTitle;
    }

    // Sort options by alpha
    asort($options);

    return $options;
}


How to merge results from two different views?

Output one view as you normally would.

Implement views_pre_render.
Call view::preview on the second view.
Manually merge the results from 2 into 1.


Programatically untick generate automatic URL alias for new node

Save your node twice, once to generate the alias and the second time to turn off that option for the node.

 // Save node to generate alias
 $node->save();
 // Turn off pathauto
 $node->path->pathauto = 0;
 // Save again.
 $node->save();

Then open edit form and " Generate automatic URL alias" will be unchecked.


What should the dynamic query for the following SQL string be?

$query = db_select('sites', 's')
  ->fields('p', array('id', 'name'))
  ->groupBy('p.id');

$query->addExpression('GROUP_CONCAT(s.name)', 'site_list');
$query->join('publications', 'p', 's.id = p.site_id');


Media Gallery module field settings stored in database?

You can make the 'dirty solution' from the link posted by @NikhilMohan into a more 'clean' one pretty easily:

function MYMODULE_form_media_gallery_node_form_alter(&$form, &$form_state) {
  if (arg(1) == 'add') {
    // Get the language code from the node object. Should be reliable.
    $langcode = $form['#node']->language;

    $form['settings_wrapper']['presentation']['media_gallery_allow_download'][$langcode]['#default_value'] = 0;
  }
}

If you're not comfortable writing a custom module you can easily drop this function into your theme's template.php file instead, but change the name of the function to MYTHEME_form_media_gallery_node_form_alter. Once you clear Drupal's caches the hook will start to be called.

Don't forget that Media Gallery is still in beta so you have to expect a few bugs/missing configuration options. Using hooks to alter the fields you need to is pretty much the only option you have here, without going directly into the database.


watchdog is trying to save an error log and database fails (probably too many error logs ?).
you might try to select showing errors on screen or sending them to syslog - you would probably get rid of the rying database and could diagnose the original problem :).

the original error seems to be undefined index on line 380 of commerce_firstd
ta.module


Drupal bootstrap takes care of session_start for you, so you should be able to define sessions like...

$_SESSION['my_data'] = 'my value';

You can also add the following in settings.php to determine the life span of the session

ini_set('session.cache_expire',     200000);


How to implement custom Checkboxes in Checkout

Check out one of the following modules:

Commerce Checkout Field Group:

  Commerce Checkout Field Group turns Commerce order field groups into checkout panes.
  This allows to add custom fields to the checkout pages.

Commerce Fieldgroup Panes:

  This module creates for each field group of the order entity a new checkout pane. These panes can be activated or deactivated as usual.
  This enables an easy way to collect information in the checkout process. For example customer comments, feedback about where the customer founds the shop or any other fieldable information.


Print the location or filename of an uploaded file from a custom content type

The file field is an entity reference field, you can get the first file entity with .entity:

{{ node.field_downloads.entity.filename.value }}
{{ node.field_downloads.entity.uri.value }}

And access the fields of the file entity as usually.

If you have more than one file in the field:

second file:
{{ node.field_downloads.1.entity.filename.value }}
third file:
{{ node.field_downloads.2.entity.filename.value }}


How can I display a form button on top of the form?

If you use $form['actions']['my_submit'] like this, then you will get the button inside $form['actions']. $form['actions'] weight would be considered with the weight of other fields. Try the following code.

 $form['my_submit'] = array(
  '#type' => 'submit',
  '#value' => t('My custom action'),
  '#weight' => -1000,
  '#submit' => array('node_form_submit', 'my_custom_node_form_submit')
 );


My Ajax call for my submit button does not work?

Try following code.

$form['suggested_actions']['list']['mentorship']['button']['#ajax'] = array(
  'callback' => 'erc360_completeness_report_suggested_actions_mentorship_ajax',
  'wrapper' => 'mentorshipunconfirmed',
  '#callback' => 'ajax_test',
  '#wrapper' => 'wrapper',
  'method' => 'replace',
  'effect' => 'fade',
);

function erc360_completeness_report_suggested_actions_mentorship_ajax($form, $form_state){
  dpm("The AJAX FUNCTION has ran...");
  $form['suggested_actions']['list']['mentorship']['text']['#markup'] = 'confirm';
  return $form['suggested_actions']['list']['mentorship']['text'];
}


Redirect to a custom page in hook_init()

If you define the redirect in hook_init, then it would work for non cached pages. But in case of Cached pages it would not work.

So it is recommended to use hook_boot instead of hook_init.

hook_boot would help you in redirecting for cached pages as well.


Why is my functional test not matching my manual testing?

The assertion failure looks as though the testing framework isn't following the double redirect (from /user/logout to <front> and thence to /node/2). Maybe explicitly request the front page after logging out?

Ie.

$this->drupalGet('user/logout');
$this->drupalGet('<front>');
$this->assertUrl('node/2');


30+ small modules versus 5 large modules versus 1 HUGE module: Which is better?

It sounds like you don't really know what your bottleneck is. This restructuring will likely have very little impact on performance (unless you happen to find and trim some major bloat in the process), but it may make things easier for you to maintain. If you do decide to restructure I would recommend splitting up along "site features" (blog, image galleries, etc.).

But if performance is your concern you first have to diagnose the problem before you attempt surgery.


Create a filterable, sortable admin view that produces front end block

Another way to do this would be to install
https://www.drupal.org/project/term_queue

This contrib module gives you all you need.

Here is a screenshot, admin interface to the right, front-end block to the left.

The module provides a block automatically, for each term queue, you simply need to place it.

Good luck!


I fixed this problem going to sites/default/files/.htaccess file and commenting

# Options None
# Options +FollowSymLinks

After that I had some other broken images but there are some wrong address in the nodes  tags linked to
/subdirectory-of-staging-server/sites/default/files
instead
/sites/default/files

Thank you for all the comment who help me to debug the error ^^


You can create and use https://www.drupal.org/project/field_collection to have a new field containing an image field and a file field for your pdf.
You set the field in unlimited.
Problem is that you might have to reupload every picture manually or write an update script that does the conversion for you.

Then for the colorbox popup with your button, have a look at https://www.drupal.org/project/entity_popup


Fetch a view into hook_preprcess_node and then put it in a block

If you want to draw a view of content based on a node, then you should build a module that declared hook_block(), and that hook_block gets the current node with menu_get_object(), and form the desired view.

At the theming layer, when your node is preprocessed for theming, it's not a good place to construct any blocks. Hope this helps.


Show attribute widgets even if the Add to Cart form only represents one product

There are a few things you have to ensure you do right for this to work, as even in my little test environment to reproduce the error I screwed it up a couple different ways.

You must ensure the field you've added to your product type has checked the box to state that it should function as an attribute field on Add to Cart forms.
You must edit the field display settings using the form you've posted a screenshot of, but make sure you save the full form as the "Update" button on the expanded form doesn't actually save any changes to the database.
You must reproduce that for all relevant view modes.

With all of those things in mind, I was actually able to confirm the feature itself is working as advertised when properly configured:


HIde taxonomy menu based on count? Possibly using rules?

There is an option in the taxonomy_menu "Hide empty items" to disable menu options if there are no nodes tagged with the specific term. The option can be found in the admin/structure/taxonomy then the vacab you are using.

Below is an image for reference.

Settings Image


Overriding migration source URL with hook_migration_plugins_alter

If you don't want the overridden config to be saved to the database you can override it on the fly with ConfigFactoryOverrideInterface. I'm storing the file path in State API storage via a custom file upload form.

my_module.services.yml

services:
  my_module.overrider:
    class: \Drupal\my_module\MyModuleOverrides
    tags:
      - {name: config.factory.override, priority: 5}

src/MyModuleOverrides.php

<?php

namespace Drupal\my_module;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryOverrideInterface;
use Drupal\Core\Config\StorageInterface;

/**
 * Overrides migration configuration.
 */
class MyModuleOverrides implements ConfigFactoryOverrideInterface {

  /**
   * {@inheritdoc}
   */
  public function loadOverrides($names) {
    $overrides = array();
    $state = \Drupal::state();
    $overrides['migrate_plus.migration.my_migration']['source']['path'] = $state->get('my_module.my_migration_source_uri');
    return $overrides;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheSuffix() {
    return 'MyModuleOverrider';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($name) {
    return new CacheableMetadata();
  }

  /**
   * {@inheritdoc}
   */
  public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
    return NULL;
  }

}


I am not sure if you still need this information, but for the benefit of others...

You might want to look into the webform_mysql_views module.
If you are using drupal 7+, you can create a simple view of the "Webform Submissions" type. Then, under Fields you should be able to find Webform Submissions: Data Value field. Select that and then add the field you want to show up in your table. Do this for the rest of the fields you want. Finally, add the filters and/or sorts the very same way. NOTE: You might have to add a relationship (the very right drop-down) or two to show you relevant results.

Hope this helps!


I've not used this particular distro, or module... there's not a block that already contains the user badges? There are several places you could add the code, there might be more:

Add a user_profile.tpl.php template to your theme, add the code in there.
Create a simple custom block with the code. You might have to get a reference to the User. I think your module would have to provide that (I don't think it is in the variables available to blocks)
Using a preprocess function for the profile in your theme. Might best work in combination with the tpl.
(not recommended) uses php filter, and put the php directly in a block.


How to assign a confirmed user role upon email confirmation without logintoboggan?

If you're only allowing the user to login once they validate their email (which would make sense if you're using email confirmations) then you could just create a rule that assigns the role to the user when the user logs in:

{ "rules_add_user_role_at_login" : {
    "LABEL" : "Add user role at login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } },
      { "entity_save" : { "data" : [ "account" ], "immediate" : "1" } }
    ]
  }
}

Now, if you're allowing a user to login without having to validate their email (which makes less sense) then you'll need to write a bit of code that hooks into the user reset form and adds the role to the user when that form submits.


Multiple aliased pages for same taxonomy term (e.g. blog/term1 and images/term1)

The problem with dynamically creating every page is with the "content type", Drupal does not support dynamic arguments (wildcards) as the first part of a path, so there really isn't much you can do about that.

But let's approach it a little different, actually you should be able to use the taxonomy view that comes disabled with views by default to achieve what you are looking for, I would create a new page and:

enable it
create a contextual filter "Content: Type"
add relationship "Content: Taxonomy terms on node" and require it
add contextual filter "Taxonomy vocabulary: Machine name" using the relationship
rearrange the contextual filters: "content type", "vocabulary", "term id(with depth)", term id("depth modifier")
edit "Content: Has taxonomy term ID (with depth)", in the section for "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" change "Filter Value Type" to "term name"
edit the path for the page (browse/%/%/%)

save your view and that should do it.

Again, remember that we can't use a dynamic path argument as the first part of a path in drupal which is why I added "browse".


One option may be to simply bring the Google Analytics data into your website, where you can then leverage the power of views to display the view statistics for the exact pages you want.

If you use the Google Analytics Statistics module, you should be able to set it up to download view stats either for the past 24 hours, 48 hours, week, month, etc and it'll do that as you run cron.  The config page is at /admin/config/system/ga_stats.  After connecting it to your Google Account by typing in your Google Login, the module setup looks something like this:

Then - you can view your Google Analytics statistics on your site (rather than through the Google Analytics interface) and can create any number of views for your different page groups as you want.  The module integrates with views...

Let us know if that works for you.

I've only recently found out about this module and started using it, so I'd be interested in any others chiming in here...


Modify how Drupal builds fields on a per form basis

I think your third option is the most direct solution since you are only looking to change one form and that file will only be called when you use that form.

The only alternative I can think of is to use hook_form_FORM_ID_alter and iterate through the form items, putting html into the #prefix and #suffix values; or creating #attribute['class'] or #attribute['style'] values depending on what you are trying to achieve.


You can try like this:

$block = module_invoke('views', 'block_view', 'profile3-block_4');
$url = render($block[content]);
Assume your Output will be
TITLE

then use **$url =  strip_tags($url);**
LINK TEXT
It will be better to use **l()**
l(t('Link text'), 'http://my-site.com/page/'.$url);

If you are still facing issue request you to provide block html output.


How many libraries is too much before there is a performance issue?

In Drupal, the best way to do your CSS is to keep it componentalized, and attach the CSS using #attached directly to the item to which it belongs. This way, the CSS is only ever attached when needed, and if a user overrides the render array further down the pipeline, removing the element to which the assets are attached, the assets will not be attached to the page, including unnecessary CSS.

Then you turn on CSS aggregation (or even better, use the ADVAGG module), and Drupal will handle the heavy lifting, aggregating the files as needed for the page.

So the answer to your question is that there aren't too many libraries. What is more important is effective management of the CSS/JS you are attaching.


How do I add multiple custom CSS classes to Views rows?

if you're using multivalue class token, this bug report may be of interest for you. There's also a patch as a workaround available.

  Currently if a views field token contains multiple space-separated class names, these classes will be combined into one class when the string is run through drupal_html_class(). Attached is a patch to split token classes before they are sanitized for HTML.


Ok, this looks like part of this is a case of PEBKAC. Or maybe could be considered an issue of documentation.

It looks like the default search box form does not interface with search API and that in order for the search API indeces to be used you must use the Search API Pages module.

However, re-indexing definitely does NOT re-index attachments on existing nodes. I'm not sure whether it's supposed to or not but that is what threw me to believe it was not working.


How do I add an OR expression between two ->addExpression() in Drupal 7

addExpression() is for adding expressions to the query, (i.e. fields that will be selected), you can't use it to add conditions.

You could either use a combination of db_and() and db_or() to build up your conditions, or (and probably easier) just use the where() method instead:

$condition = '(flag.fid is not null AND flag.fid = :fid1) OR (flag.fid is not null AND flag.fid = :fid2)';
$query->where($condition, array(':fid1' => 2, ':fid2' => 3);


Missing the message status when saving Node

This message comes from node.pages.inc (never edit Drupal core) in a form submit function and I believe messages are stored in the $_SESSION['messages'] variable. I would try to get at these with a hook_form_alter() and custom validation and submit handlers to see where it might be dropping.

If you're running any custom code look specifically for interactions with the $_SESSION variable. Clobbering or unsetting it could prematurely remove these messages.

If you use the devel module you can simply use the following.

dd($_SESSION['messages']); //Logs to drupal logs
dpm($_SESSION['messages']); //Outputs debug information to screen

You can also create your own messages using drupal_set_message()

For example:

drupal_set_message(t('It worked!'), 'status');

You may also want to check that you don't have something like the Disable Messages module installed or misconfigured.


Display a link to create new content when content missing (via Contextual Filters)?

Here I suppose you have added an argument in panel path. You can assign any context to your argument, eg Node: Id. It can be Term as well.

Assign any context to argument like :

Add a visibility rule if Context exists to your view and not exists to custom pane.


How to update drupal (with composer) and not update to the latest major drupal release

It depends on the version you specify in the composer.json file. You can specify broad versioning, or exact version, and composer will adhere to that.


Views: Display block based on taxonomy term

When you edit your view, there is a section called "Filter Criteria" in the left column (Drupal 7 / Views 3). Click on "Add" in the Filter section, then limit the criteria to Taxonomy only by choosing "Taxonomy Term" in the Filter drop-down. You should see the correct category, then just pick the term you want to check for ("alive").


Views: Display number of nodes published by author on profile

In my opinion, You do not need Display suite to achieve this. You can do this in very Simple Drupal way .

1. Your views configuration if perfectly fine. I am just posting my one for reference purpose, Where I did two changes, (1) In the pager setting, I have set the pager item to 1. (2) I removed the User: name as it is not needed.

Note: You do not need to anything with aggregation setting at filter level.

2. From your views it is visible that you have created block.

3. Now, What you need to do is put that block in your user profile, so it looks like as a one of the field of user profile.

4. How to do that:

4.1 Place that Block under  Main page content in Content region on as shown in following image.

4.2 Set the display rule for this block as shown in following image. So what happens, the block are visible only on the user profile page.

4.3 Set the Role permission for the User Role, so other user can see teh profile page of other's Or anonymous users also can see teh profile page of other's: I am sure you are aware of all this.

5. Output Image: As you can see, I have tried in my Bartik theme. I have just given block title,  So it can distinguished in the image. Note: I have removed User:name field from the views, as it is not necessary. The views will automatically detect from the url.

**Other example from other login **

Hence, this way without using any other display help, you can add the new field in the User profile. So you do not have to much play with the User profile page.


Taxonomy term listing of nodes with the term in a paragraph

As per you comments you need some thing like the following to change the Title to a taxonomy term.

/**
 * Implements hook_views_pre_render().
 */
function MODULE_views_pre_render(Drupal\views\ViewExecutable $view) {
  // Get the machine name of your view and replace below.
  if ($view->id() === 'myview_machine_name') {
    $tid = $view->args[0];
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
    // overide the title with the term name.
    if (is_object($term)) {
      $view->build_info['title'] = $term->getName();
    }
  }
}


These emails are assembled in the faq_ask_mail function (faq_ask,nodule, line 1013). The body is assembled beginning at line 1077.

If you wish to open up the body, you can go in and include some newline ('\n') characters into the text.

Since this hacks the module core, perhaps you should submit a patch as a feature request.

EDIT:

faq_ask_mail is an implementation of hook_mail. You can define your own hook_mail in a custom module to override the output. You must, however, adjust the weight of your custom module so it is processed after the faq_ask module. You would handle it as follows:

function MYMODULE_mail(&$key, &$message, &$params) {
  $body = $message['body'];
  switch ($key) {
    case 'notify_expert':
    case 'notify_asker' :
      /*** Change the formatting of $body ***/
      $body = str_replace("\.", "\.\n\n", $body);
      break;
  }
  $message['body'] = $body;
}

Remember that this will have no effect if it is executed before the faq_ask_mail function.


The authorize.net module supports recurring payments using ARB. You can also setup recurring payments using the paypal module. I wouldn't be surprised if the other credit card payment gateways support recurring payments too.


I'm not sure what the real answer is to this issue, but I found a workaround: I created my own token which provided me this alias

/**
 * Implements hook_token_info().
 */
function example_tokens_token_info() {
  $types['og_path_alias'] = array(
    'name' => t('The OG Path Alias'),
    'description' => t('Tokens for the OG path alias'),
  );
  $og_path_alias['path_alias'] = array(
    'name' => t('The OG Path Alias'),
     'description' => t('The OG path alias'),
  );
  return array(
    'types' => $types,
    'tokens' => array(
      'og_path_alias' => $og_path_alias,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function example_tokens_tokens($type, $tokens, array $data = array(), array $options =     array()) {
  $replacements = array();

  if($type === 'og_path_alias') {
    $node = $data['node'];
    foreach($tokens as $name=>$original) {
      switch($name) {
      case 'path_alias':
      $node_wrapper = entity_metadata_wrapper('node', $node);
      if($node_wrapper->__isset('og_group_ref')) {
        $chapters = $node_wrapper->og_group_ref->value();
        foreach($chapters as $chapter) {
          $new_alias = drupal_get_path_alias('node/' . $chapter->nid);
        }
      }
      $replacements[$original] = $new_alias;
      break;
  }
}
}

return $replacements;
}


How to expose paging data in REST export views

Enable pager Exposed option "Allow user to control the number of items displayed in this view" in rest display, then build custom module with views style plugin - to return results and pager data, and set in rest display

short code from custom style plugin:

$ret = $this->serializer->serialize(
 [
   'results' => $rows,
   'pager' => [
     'count' => $count,
     'pages' => $pages,
     'items_per_page' => $items_per_page,
     'current_page' => $current_page,
   ]
 ],
 $content_type
);

full code in gist: https://gist.github.com/svetlio/79f3c32667b21d89ed03cdb660308668

thanks to Dan's post here: https://www.mediacurrent.com/blog/8-insights-and-useful-snippets-d8-rest-module


Cannot use my drupal installation after enabling new custom theme

theme.inc on line 98 is trying to collect theme's ancestors.

My bet is that your custom theme is wrong and it's telling Drupl that is a subtheme of itself, making Drupal the enter in an infinte loop that exhausts memory.

Double check your custom theme configuration or just move it away from Drupal directories so Drupal can't process it.


How to add custom language specified text?

You can set the translations for each specified language in the strings settings part of the internationalization module: /admin/config/regional/i18n_translation

To show it in a template file you simply use the t() function to wrap your text - which translates text for you and automatically adds new text defined in the t() function to the strings page.

See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

If you are hardcoding links with your text you can use l(), so if you have say a text link and want the text to be translated you would use l() and in it define your text using t() - something like this:  http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

See http://api.drupal.org/api/drupal/includes--common.inc/function/l/7 for its usage.


One of my drop down menus, the "Create Content" option under the parent "Content" tab has dissapeared. How can I recover it? (I'm using Drupal 7)

It looks like you're using admin menu, right? A blog post about rebuilding the drupal admin menu says you can:

Delete you current links via SQL DELETE FROM menu_links WHERE menu_name='management'.
Clear all caches at Administration > Configuration > Development (or just: http://example.com/admin/config/development/performance if your menu is ruined at this point). Drush users can of curse use drush cc all or even drush cc menu

Disclaimer, I didn't try it myself. Hope this helps.


If you add a select field in your webform, for example ( language ) then you can filter emails using that select field. You can rather let the user select the language or do it with a language detection script.


use an inline javascript function (not jquery) on drupal 7

If you want to write a plain JavaScript instead of JQuery, You can proceed with normal function declaration like

function sample() {
}

and go ahead. It is normal way of the doing things in javascript, More over jQuery is a framework of javascript and as said you can add js files in the traditional way

drupal_add_js()


Use a custom module to add JS to every page in Drupal 8

Assume the custom module is called example.

First create a example.libraries.yml file in your module root folder like this:

example:
  version: 1
  js:
    example.js: {}
  dependencies:
      - core/jquery

Next in example.module use hook_page_attachments() too add your JS to every page:

/**
 * Implements hook_page_attachments().
 */
function example_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'example/example';
}

So now the custom module has 4 files:

example.module
example.info.yml
example.js
example.libraries.yml

hook_page_build() and hook_page_alter() are now deprecated so can no longer use them.

There is a page drupal.org on adding CSS and JS using a custom module with more information.


The "Mock LDAP" server that is being used for the LDAP Test module is, in fact, a mock server object. It allows the tests to run, and doesn't exist outside the scope of the simpletests.

If you're looking to provide a way to "mock" an LDAP instance on your development site, it can't provide that functionality.

If you're trying to write your own simpletests for LDAP integration, check out the Examples for Developers project. The included module, simpletest_example, has excellent documentation for writing simple tests.


Try removing the selection rule. If the page is active and has a variant, I would expect it to work without a path selection rule.


Drupal has an API for documentation and comment standards that allow you embed comments in the code using a special syntax that will automatically generate documentation for the module, including modules that create content types.

This is the system that is used to automatically generate the online API reference  found on http://api.drupal.org and other similar sites.

The API module used to generate these pages parses documentation and code in PHP files, and it expects documentation to be in a format similar to other code/documentation parsing systems such as PHPDoc, JavaDoc, etc. The system was originally based on doxygen, but it has evolved into something that has its own set of tags and Drupal-specific functionality.


In Drupal 7, how do I create a custom rules event for any and all file entities?

You can't just declare hook_rules_event_info(), it just tells rules about an event type, but you still need to invoke that event.

To invoke a declare event, use rules_invoke_event().

Example

/**
 * Implements hook_entity_insert().
 */
function rules_extended_entity_insert($entity, $type) {
  if ($type == 'file') {
    rules_invoke_event('rules_extended_rules_event_file_insert', $entity);
  }
}


You can use hook install to create your own tables, if you really want to, although Drupal has many other more out-of-the-box solutions.  But if you do want to roll your own, there's an example module, called dbtng_example, in the examples module: https://www.drupal.org/project/examples, complete with routing for adding and removing your custom database entries.

I'd recommend installing it and trying it out, then you can use that as a basis for creating your own database table in Drupal 8.

Another approach to consider is to create a config entity or a content entity.

If you use the drupal command line tool there's even a command for generating these "drupal generate:entity:config", and "drupal generate:entity:content".

Also in the examples module, there is config_entity_example and content_entity_example.

From https://www.previousnext.com.au/blog/understanding-drupal-8s-config-entities: "The main difference between content and config entities is how they are stored and (at the moment) config entities are not fieldable".

There are some other more out of the box solutions, such as the config_pages module that allow you to easily spin up places to store data on your site:
https://www.drupal.org/project/config_pages

We recently used these for one off landing pages, by creating a controller and route.  This has a huge advantage over a custom table as you can easily add new fields and you can use data types such as images and entity references easily, you can also set field formatters, and load the data formatted using the config_pages entity view builder.


Convert a regular autocomplete field into an autocomplete deluxe field?

As per the README.txt file, something like this should work

   $form['field_term_ref_tid'] = array(
     '#type' => 'autocomplete_deluxe',
     '#autocomplete_deluxe_path' => url(
       'autocomplete_deluxe/taxonomy/field_term_ref',
       array('absolute' => TRUE)
     ),
     '#multiple' => TRUE,
     '#autocomplete_min_length' => 0,
     '#autocomplete_multiple_delimiter' => ',',
     '#not_found_message' => "The term '@term' will be added.",
   );


I might be terribly wrong here, but there appears to be no such hook for Drupal 6. If so, it will never fire.

See https://api.drupal.org/api/drupal/6/search/hook_preprocess_html.

Perhaps you're backporting a theme from D7?


Can you resume sending mails to a list of which only part of the addresses are having had a newsletter?

To avoid automated spam testing, most hosting companies avoid reporting back on failed sending. If you somehow know who got and email and who didn't, you could suspend or remove subscription for those who did, send email again and after that re-enable users. That's pretty universal method, works for any mass sending mechanism.

If you don't know who got your email and who didn't, only raw number, you have a problem that's unsolvable.

For the future, Drupal integrates pretty well with some paid mail sending services. That's a solution for sending large amount of mail and keeping page on shared hosting. If you want to avoid mail sending services, virtual private server shouldn't have a limit on sent mail count. Sending mails is pretty expensive in terms of cpu and memory, and it's an outdated technology, so it's only to be expected shared hostings will limit and discourage it, except for small quantities like registration confirmation etc.


User List of user roles in List field af a content type

You can try using Role Field module..

Project page says

  Role Field provides a field for selecting roles that exist in your
  site.

  Please note that there is no out-of-the-box permissions shenanigans
  going on. It just lets you pick from a list of roles. Although,
  combined with Rules the possibilities are pretty interesting.


Adding a custom Token so i can use in Webforms

Create your own tokens!

You could create a small module that implements the token hooks (D6, but D7 should be similar), like so:

function YOURMODULE_token_list($type = 'all') {
  $list = array();

  $list['smart-ip']['smart-ip-country-code'] = t("The Country code");
  // ...etc

  return $list;
}

function YOURMODULE_token_values($type, $object = NULL, $options = array()) {
  $tokens = array();

  $tokens['smart-ip-country-code'] = $_SESSION['smart_ip']['location']['country_code'];
  // ...etc

  return $tokens;
}

Or, even better, add these hooks to the smart_ip.module file and submit a patch to the module maintainer :-). Tokens are really great, and it would certainly be a good addition to the smart_ip module.


Altering the views Sorting Criteria, to display first ISSET fields

Why not order by quantity of elements in photo field, or delta ?


I think you are inventing a problem that doesn't exist.

The active database will be per-request, not site wide.  So if one user is accessing your backend, another user can do whatever they need against your default Drupal database.

Within a request, you can use the db_set_active() function to switch databases as much as you want. eg

$query = db_query(...);   // runs against the default database
db_set_active('backend'); // change databases
$query = db_query(...);   // runs against $databases['backend'];
db_set_active();          // change back to default databases
$query = db_query(...);   // runs against the default database

As PHP is single threaded w/in a single request, you don't have to worry about a query running against the wrong database.

So, in summary, just use db_set_active() to change databases when you need to, and then remember to switch back when you are done.  If you isolate your code (which you really need to do in Drupal anyway), you shouldn't run into trouble.

I would also look into hook_views_data().  This works very well to being in external data into Drupal.


Using Commerce Feeds module, commerce file names are being changed when importing

Go to structure/feeds importer
Select yourproductimporter - go to mapping/.
Go to Files:URI (commerce_file:uri)
Click on the button below text "Rename if file exists."
Change to "Replace" and save the importer.  That worked for me.

That will eliminate the _0 or _1.mp3 and keep the same file name as your database.


Create content type with fields that are content types

A think you could be interested in Field Collection


I got an answer for this in the Drupal Community on Google+: Use drush @sites en your_module -y.


In D7 how can I append an element to the DOM via ajax on an arbitrary event (not forms and not links)?

First visit example.com/ajax/insert to verify your content is being printed out.

Your overall JS structure looks odd, plus you have a lot of typos. This .field-name-field- is probably not a real class since it ends in a trailing dash. /q= is not a HTTP query, you probably want /?q=.

Try this:

(function ($) {

  Drupal.behaviors.my_mod = {
    attach: function (context, settings) {

      $.ajax({
        type: 'GET',
        url: Drupal.settings.basePath + '?q=ajax/insert',
        dataType: 'html',
        success: function(response) {
          $('.field-my-field-class').html(response.data);
        }
      });

    }
  };

})(jQuery);


Is there any option to add file upload/attachment field in webform?

Will need to define the private file system to get the web form upload fields. By default the private file system was not defined that's why the upload fields were not showing up. After defining the private file system through the settings.php file and clearing the cache I found several upload fields option to add in the form.


How can I update existing config from a custom module's config/install yamls?

A module install should not update config. If you want to update existing config, your module should implement hook_update_N() (see docs) instead.

However, you could add a dependencies: enforced section to your YML config files. This will remove your existing config on module uninstall, and install the newest config on module reinstall. This way you can "emulate" a simple update mechanism for your own, private custom module. See doc for enforced config dependencies


How to retrieve data from set with drush_set_option() from within install profile

It appears the answer is simple: You can use drush_get_option().

  Get the value for an option.

  If the first argument is an array, then it checks whether one of the options exists and return the value of the first one found. Useful for allowing both -h, and --host-name.


Fairly sure you can't do this from within the Blocks interface, but would be delighted learn otherwise.

A strategy to try would be to create a Views block that will display or not as required. A View over Users with a Contextual Filter that takes the Raw Value from URL, picking out a given path component, would be a start. You can then filter the view by User: Active.

If that all works out then your View will show. You can then get the content you want for your block by using a Rewrite of User: name field and, perhaps also, using Global: Text area in the header. (Well, you might be able to get the content this way. Depends on what's needed in the block.)

When you add the View block, you'll do something such as user/*/downloads, but the block will show depending on current user matching the contextual filter.


Inserting the value from Datetime field form

Datetime fields in Drupal 8 are stored as strings, partially because date support between databases isn't consistent and partially to make them easy to manipulate to extract parts where there aren't proper date functions.

The date is stored with the format DATETIME_DATETIME_STORAGE_FORMAT, and the timezone is implicitly DATETIME_STORAGE_TIMEZONE.

You would need to do something like:

Before Drupal 8.5

/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));
$string = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);

In Drupal 8.5 and after, as per https://www.drupal.org/node/2912980

/** @var \Drupal\Core\Datetime\DrupalDateTime $date */
$date->setTimezone(new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));
$string = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);

There are better ways to handle this, though.  It is best to use the date formatter service to format the dates, rather than the ::format() method (I'm being lazy here).  It is also probably best to use proper entities and add this as a field, and not just stuff it into a database table.


This feature is already done in core in D8, however not in one menu but in multiple one (in the wrapper divs of the elements).

First of all I would make a list exactly what I want to include in the custom menu (menu items edit, content edit, etc..).

And then trying to look inside the core for the existing solution for that and unite them into one menu.


How to theme a paragraph bundle with a template file?

I had the same question. Here's what worked for me with: Drupal 7.41, Paragraphs 7.x-1.0-rc4.

Go to the end of your settings.php file and remove the hash sign to enable
"$conf['theme_debug'] = TRUE;" Or add the line if not present.
Flush your cache.
With your favorite browser, inspect the Paragraph output that you
want to override. You should now have HTML comments, just before the
actual markup, with template filename suggestions that you can use
in your theme.

With my setup, the template filename suggestions are:

paragraphs-items--{field name}--{view mode}.tpl.php
paragraphs-items--{field name}.tpl.php
paragraphs-items.tpl.php

Where field name is the name of the field you use when you assign the paragraph field to a content type (not the Paragraph bundle name).

So in your particular case, if the paragraph field happened to be named "text-buttons" (machine name "field_text_buttons"), the filename suggestions are:

paragraphs-items--field-text-buttons--full.tpl.php
paragraphs-items--field-text-buttons.tpl.php
paragraphs-items.tpl.php

Don't forget to turn off theme debugging on your production site.

Best of luck.


How do I create custom layouts for Panelizer?

Panelizer is based on Panels module, which uses Layout API module in Drupal Core for providing  layout plugins. Please refer to the relevant documentation:

https://www.drupal.org/docs/drupal-apis/layout-api/how-to-register-layouts is written with newer Layout Builder in mind, but basics should be the same
https://www.drupal.org/node/2578731 is an older version of the same docs - might be slightly out of date, but also contain something not present in the previous document


path_set_alias() generates the wrong alias, and creates a 301 redirect to the desired alias's path

The trick was to set $node->pathauto_perform_alias = FALSE; before calling node_save.  Then my manual aliasing was allowed to take effect.

I still haven't figured out how to prevent the 301 redirect.  It only produces a warning now, and the alias stays the way I want.


Create a Ubercart Drupal site to sell memberships?

I was also trying to do this fairly recently.  Found a nice tutorial on Site Membership and Ubercart from Torontowebsitedeveloper.

https://www.youtube.com/watch?v=vbeqlNjBvwQ


How to create a new seller (store) under administrator using drupal commerce marketplace

First you add role like seller then just add a user with role of seller and set permission for seller.


How to display messages "properly" when using ajax submit?

Finally, after hours digging Drupal Answers, I made it work this way.
My ajaxCallback:
$response = new AjaxResponse();
if ($form_state->hasAnyErrors()) {
  $messages = \Drupal::messenger()->deleteAll();
  $messages = [
    '#theme'        => 'status_messages',
    '#message_list' => $messages,
  ];
  $response->addCommand(new ReplaceCommand('#messages', ''));
  $response->addCommand(new AppendCommand('.region-highlighted', $messages));
}
else {
  $response->addCommand(new \Drupal\Core\Ajax\RedirectCommand(Url::fromRoute('<front>')->toString()));
  }
}
return $response;

and my submitForm is now empty!
Nota: $response->addCommand(new ReplaceCommand('#messages', '')); is here to have a new error message replacing a previous one (without this command, all the messages are displayed one after the other...).


views exposed form alter hook works with login but not work with out login?

Please check your code on search_redirect_permission.You have to use

access search_redirect module content in user_access function to display result.You have to use search api under anonymus login codition.

Something like:

if (user_access('access search_redirect module content')) {
  // search results!
 } else {
  // no search results!
 }

But I don't understand why you are using hook_permission(),if it should be viewed by anonymous users.

EDIT: For form redirect you should do something like:

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

    if($form_id == 'your_form_id')
    {
      //YOUR SOME LOGIC IF ANY
      $form['#submit'] = array('custom_form_submit_handler');
    }
}

function custom_form_submit_handler($form, $form_state)
{
//YOUR SOME LOGIC IF ANY
   $form_state['redirect'] = 'your_url';
}


Unable to send email local configuration problem

This was resolved by setting up a 'anything@mydomain.co.uk' with my host, and setting this to my email address under Configuration/Site Information, and also under the settings for the Trigger rule I set to send an email when a user is created.


There are a couple of things you can do. First, instead of grabbing the filename field from the {file_managed} table, you'll want to grab the uri.

Then you can use file_create_url() to generate a url to the original file:

$icon = file_create_url($row['uri']);
$output .= '';

Or if you want to run the image through an image style, you can use image_style_url() (you'll need to know the machine name of the image style)

$icon = image_style_url('image_style', $row['uri']);
$output .= '';


How do I add a custom field to the image field widget in Drupal 7?

Attaching metadata to images and other media, is precisely the reason that prompted the creation of the media module. We use the unfortunately "unstable" version ourselves, with good results. Using Media, your images becomes entities, allowing you to attach any field you want to them through the normal means.
While the solution to manipulate the existing widget is fully valid, it will require quite a bit of understanding of the Field API, and I believe any such solution would get rather messy.


As the Flowplayer API states the basic configuration is like this

$f("player1", "flowplayer.swf", {
    clip: {
        url: 'KimAronson-TwentySeconds59483.flv',
        autoPlay: true,
        autoBuffering: true
    },
    plugins: {
        controls: null
    },
    onLoad: function(){
        alert("player loaded");
    }
});

Note the  controls: null section this will allow you to render the player without controls.

Read Flash plugins section for more detailed information.


D7 Why I cannot just copy a template file from a module to my custom theme to override it?

Create tpl file for field field--field-name.tpl.php. place it to your theme.

  if Field name is: field_page_photos
  then File name will: field--field-page-photos.tpl.php

copy sites/all/modules/timefield/theme/timefield.tpl.php code to above tpl file.
make changes and clear cache.


How can I list the users who are associated with a given Profile2 profile using Views?

As I understand it,  several 'profile types' with different fields and questions relevant to various 'organizations' in your company.

Here's a suggestion to create a view which shows a list of the details in all profiles grouped by 'organization field' and sorted by the various 'hierarchy fields'.

The key to making this work is that the different profile types have a couple of fields in common eg. organization, first name, surname etc.  Assuming each profile type uses the same 'field_organization', 'field_first_name', 'field_surname' we can use table view and grouping.  If we need to display profiles with different fields, then add the fields and select another view type such as list view instead.

You may be able to do this even if only field_organization is in common in all the profiles (with list format instead of table format.  Even if the profiles have other fields which don't match, they can be combined into the same report using 'list view' instead of table view.

Create a new view.
Either: Show 'Profiles' of type  'profile type for particular organization'
Or:     Show 'Profiles' of type  'All'
Create as a block and/or page as required.
This will show a list of profile ids.
(optional) In view editor, add a relationship "Profile: User uid"
This will give you access to the person's username and email.
Add fields as required eg. mail from user, username from user,
Add fields fields "Organization"
Add each of the "Hierarchy" fields
(optional) add field "Profile: type"

If the fields are shared and appear in more than one profile type,  you should see "Appears in: profile2:org_1, profile2:org_2, profile:org_head_office etc. as you select the field to be added.

To group by organization as you outlined, avoid 'grouping and aggregation', and instead select 'Format: HTML list". In the  'format settings' use the 'Grouping field Nr.1 ' to 'Organization'.

Caveat
- if someone has more than one profile, they will appear more than once in this list.

If there is just one 'hierarchy' taxonomy  reused in all the profiles, then you might be able to add this as 'Grouping field Nr. 2' instead of relying on sorting.

With luck you should end up with a list such as:

Organisation Unit 1:

Firstname
Surname
Heirachy position1
Firstname
Surname
Heirachy position2
Firstname
Surname
Heirachy position3

Organisation Unit 2

Firstname
Surname
Heirachy position1
Firstname
Surname
Heirachy position2


That option will add some code to the generated module to make it a Feature module - a module that provides some exportable configuration.

More info: https://www.drupal.org/docs/8/modules/features/creating-and-configuring-bundles
Source: https://github.com/hechoendrupal/drupal-console/blob/master/src/Generator/ModuleGenerator.php#L94


Edit profile2 tab in view profile2 rendered with views

Profile2 provides a submodule Profile2 pages which does exactly that: allows the ability to render the profile separately and includes an Edit tab.


Try any one of the module as per your requirement.
Content Complete

Content Complete is a CCK extension module that allows to tag CCK fields needed for completion (CCK Complete). The module checks the tagged fields against the content provided for those content types, and computes a complete percentage that can be shown to the user.

Field Complete

In some situations you want to mark an entity field to indicate it should be completed but not enforce its completion at that time. This module extends the choice between Required and Not required to "desirable" completion.
This module overcomes the problems with the (otherwise excellent) Content Complete module which cannot cope with field collections or fields that link to other entities.

Hope the following links give you clear ideas on how to use Content Complete module.
Measure node completion in Drupal, part 1
Measure node completion in Drupal, part 2


You probably should run Drupal.attachBehaviors($('.newcontent')); instead of trying to add this logic manually for each module. But since you asked for flag 3.x it is Drupal.behaviors.flagLink.attach($('.newcontent'));


Line 623 of modules/cck/modules/content_copy/content_copy.module needs to be changed from:

function template_preprocess_content_copy_export_form($vars) {

to

function template_preprocess_content_copy_export_form(&$vars) {

https://drupal.org/node/2230081


Preprocessing is just an optional step between defining a render array that will then use a twig template and the actual twig template.

It's a place where you can execute PHP code to prepare variables that you can later use in your template.

You don't have to use preprocess for you own templates but some things can only be done there or are a lot easier, as you can't execute arbitrary code in a twig template.

See template_preprocess_image() for an example. Note the different names of preprocess functions. There's always the one prefixed with template. That's reserved for the module that defines template in hook_theme() and is called first. And then it's called for each module and active theme, just like a hook, e.g. as yourmodule_preprocess_image.

That brings me to another advantage of the preprocess phase. There can only be one template that's actually used and while there are ways, modules in general shouldn't provide template unless they define it. But, every module can implement the preprocess function and influence the output of a template to a certain degree. For example to add a certain class or data attribute to a node so that some JS can then use it.


Programmatically load webform edit page by SID

I managed to solve it by creating a custom module, with a custom page and inside the custom page I use the :

drupal_get_form

and it works perfect!


What are you doing in your module?, If you are building a new entity, you would to use hook_apachesolr_field_mappings() http://drupalcontrib.org/api/drupal/contributions!apachesolr!apachesolr.api.php/function/hook_apachesolr_field_mappings/7

An example is the implementation in http://drupal.org/project/apachesolr_commerce

Regards!


Seems like I had to assign a profile to my user role. Configuration>Media>IMCE. Create a profile with access to browse, upload, thumbnails, delete and resize for \users\user%uid. Atleast that worked for me.


Multiple (bulk) upload with the media browser widget

You will need to use https://drupal.org/sandbox/fangel/1652676 to be able to upload multiple images and still be able to access the media library.


How can I print messages in a Panel layout template?

What do you think about using Panels Everywhere?
You could then add a message pane to your Default site template and avoid 1.

Also you can disable Block from now on, because all parts of your site, are now panels.


How can I filter specific user on Views list?

Add a filter criteria of type User: Roles,
Select the operator Is none of:
Select Administrator from the listbox.
Save the settings

This will block the display of all the users with role as administrators. If you only want to limit a certain user you can select the filter criteria of User: Name, or User: The User ID, whatever suits you.


List content referenced to another content type

You can create a view that lists episodes that references the show. This is done using the module Views.

Go to admin/structure/views/add and add a view, call it episodes and create a block display.

Create a new view and a relationship, the label will be "Entity Reference: Referencing entity" and as description you will see "A bridge to the Content entity that is referencing Content via field_YOURFIELD".

Then add a contextual filter called "Content: Nid". In the settings for the filter look for "When the filter value is NOT available" and choose "Provide default value" and choose "Content ID from URL".

Your settings will look something like this (I removed the second column to make the image smaller).

Now go to admin/structure/block and place the block you created (if named the same as my example it will be called "View: episodes") and place it in the region you want it to show.


How to use hook_form_alter with commerce checkout

If you remove the code shown below, it would only affect the review pane.

case 'commerce_checkout_form_checkout':
    break;
case 'commerce_checkout_form_shipping':
    break;


Add to cart button enabled if subscriber seller

My answer would be for Drupal 7 with respect to current code to your final question of functionality:
 - After making sure both the rest of your structure is in place, Add the Rules watchdog that will "listen" for the role or lack thereof
   and then do not only 'it' but perhaps other things for example display a popup message. It would be possible to change the look or color of the button as well. Requirement: Rules module. Rules UI will have it write the code for you, that you can then save to code if you want.
 - With a rule stating normal code behavior not having fired or reverting to normal behavior after logging in, then the button will do as it was coded to do.

Subscriptions with an end date in Drupal by marrying a subscription to a role by https://www.drupal.org/project/commerce_license not released for 8 production yet whereby you do all the magic of billing: Commerce Billing is an option in Drupal 7, method, cycle, grace period, and expire or downgrade the role as you wish upon expiration. From a step point-of-view, this step precedes the rules, as this will be the basis for rules. "commerce_billing" is only available for Drupal 7 at this time with respect to billing anyway, and the projects don't show a Drupal 8 version being started yet. That's why my answer is for Drupal 7 only at this time, except when one module may be ready but calls itself "dev", and the other is not yet started.


D8: How to perform ajax call in javascript

Instead of specifying an incorrect datatype in the client call, you fix your route and specify that you return json. Use the _format route key as explained in the route documentation


Computed field module: value of field when creating new content

menu_get_object() provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling menu_get_object() will return that.

From: http://api.drupal.org/api/drupal/includes!menu.inc/function/menu_get_object/7

It returns empty upon creation because you add the node from "node/add/[content-type]" page but update it from "node/[nid]" and it can use the nid to load the node.

If you need just to duplicate the value from the start_time field of the same node, use this:

$entity_field[0]['value'] = $entity->field_start_time[0]['value'];


Downloaded Drupal 8 with composer, now what?

Composer installs all dependencies for you

Next steps

setup a database with user and pass
setup so that your apache/nginx see /web as the webroot (revisit/fix this step so you can get on next step)
visiting the URL should bring up the installation procedure which should ask for DB/user/pass, follow the instructions to complete the installation


What does xmlrpc.php do and how can I use it?

You should be able to use it for other RPCs. Example xml-rpc post for user.update shows an example of a user.update method call.

<?xml version="1.0"?>
<methodCall>
   <methodName>user.update</methodName>
   <params>
     <param>
       <struct>
         <member>
           <name>uid</name>
           <value><int>38</int></value>
         </member>
       </struct>
       <struct>
         <member>
           <name>name</name>
           <value><string>diana.ruiz12</string></value>
         </member>
         <member>
           <name>mail</name>
            <value><string>ndy.r@eeuwkern.org</string></value>
         </member>
         <member>
           <name>pass</name>
           <value><string>candy9223</string></value>
         </member>
       </struct>
     </param>
   </params>
</methodCall>

It doesn't look like a widely used feature, and it will be moved out of core in Drupal 8.

See also Services Tutorials and Examples.


User variables defined in hook_variable_info() in rules

As the Rules module uses tokens, and the Variable module implements hook_tokens(), you should not do anything.

If the value returned from that implementation of hook_tokens() is not the value you would expect, in a module of yours you could implement hook_tokens_alter() to alter the token values returned by the Variable module.

Reading Entity property information, I get fago means code similar to the following one should be used.

function mymodule_entity_property_info() {
  $info = array();

  // Add meta-data about the variables exposed from the Variable module.
  $properties = &$info['site']['properties'];

  // ...

  return $info;
}

I didn't find any information about the parameters passed, for example, to the setter callback, even though entity_property_verbatim_set() is defined as entity_property_verbatim_set(&$data, $name, $value, $langcode, $type, $info).

function entity_property_verbatim_set(&$data, $name, $value, $langcode, $type, $info) {
  $name = isset($info['schema field']) ? $info['schema field'] : $name;
  if (is_array($data) || (is_object($data) && $data instanceof ArrayAccess)) {
    $data[$name] = $value;
  }
  elseif (is_object($data)) {
    $data->$name = $value;
  }
}

Vice versa, entity_metadata_user_set_properties() is defined as entity_metadata_user_set_properties($account, $name, $value).

function entity_metadata_user_set_properties($account, $name, $value) {
  switch ($name) {
    case 'roles':
      $account->roles = array_intersect_key(user_roles(), array_flip($value));
      break;
  }
}

entity_metadata_user_entity_property_info() uses that setter callback in the following definition.

  $properties['roles'] = array(
    'label' => t("User roles"),
    'description' => t("The roles of the user."),
    'type' => 'list<integer>',
    'getter callback' => 'entity_metadata_user_get_properties',
    'setter callback' => 'entity_metadata_user_set_properties',
    'setter permission' => 'administer users',
    'options list' => 'entity_metadata_user_roles',
    'access callback' => 'entity_metadata_user_properties_access',
  );


Is there a trick to getting Mime Mail to recognize by-mailkey theme templates?

Use latest dev version of Mime Mall module. It doesn't work in 7.x-1.0-alpha1 and 7.x-1.0-alpha2.

But you can also make a quick hack. In file mimemail.module need to comment the row #531

$key = str_replace('_', '-', $key);

After that you can use mimemail-message--help-wanted.tpl.php template.


The live() method wasn't added to jQuery until v1.3. Your site is currently using the standard jQuery library included in Drupal 6, v1.2.6.

To fix this all you need to do is download and install the jQuery Update module. That will upgrade your site's jQuery library to v1.3.2 and you should stop getting the errors.


How to apply coupon in commerce order programmatically?

When you are creating a discount, you will enter the name and the system will automatically generate machine-name. You need to use the machine name as an argument for commerce_discount_fixed_amount() function.

Here's a screenshot:

Here's how you would use it:

commerce_discount_fixed_amount(EntityDrupalWrapper $wrapper, 'discount_test_discount');


How do I manage a mix of menu and custom breadcrumbs?

Do I have to create my own Breadcrumb builder class?

Yes, there are many places where you can modify breadcrumbs, but this is the only straightforward way. The custom breadcrumbs should have a priority higher than 1010 (the priority of the breadcrumb builder of Menu Breadcrumbs), so that nodes that follow rules you put in applies() of the BreadCrumbBuilder class can't be controlled by Menu Breadcrumbs.

  How do I set the priority (asked in the comments)?

The priority is set in the service definition, example from the Menu Breadcrumb module:

menu_breadcrumb.services.yml:

services:
  menu_breadcrumb.breadcrumb.default:
    class: Drupal\menu_breadcrumb\MenuBasedBreadcrumbBuilder
    arguments: ['@config.factory', '@menu.active_trail', '@plugin.manager.menu.link', '@router.admin_context', '@title_resolver', '@request_stack', '@language_manager', '@entity_type.manager']
    tags:
      # The priority must be higher than core taxonomy builder (priority: 1002)
      # see https://www.drupal.org/node/1495510
      - { name: breadcrumb_builder, priority: 1010 }

(which is also where you have to look when you want to override an existing breadcrumb builder, you can see here what was considered concerning the taxonomy breadcrumbs)


How can I add a link to users of an organic groups in views

Build a new view or block listing users and limit access to members of the users of group. Go to you current view and add a link to the new view or block.

Got to Structure>Views and add a view. Name and set to Users

Set groups fields and filter to specific group.

Change the page URL

Save

Copy url of view and go to existing view and create the link.


Set blank vale as default for a select box using Drupal form API?

In Drupal 7, you could use the #empty_option property, for which the default value is "- Select -" for a required field, and "- None -" for an optional field. The property adds the additional label as per the following cases:

If #required is TRUE and there is no #default_value, an empty option is added to the select control to force the user to make an active choice.
If #empty_value or #empty_option is set and #required is FALSE (default), an empty option is added to the select control, allowing the user to choose nothing.
If none of #required, #empty_value, #empty_option, and #default_value are set, then no empty option is added to the select control. This leaves the control in a slightly illogical state, since all user agents automatically preselect the first available option. There's no way for the user to select nothing, and the user is also not forced to make an active decision.

The property is used only for "select" form fields.


What does Drupal do when registering a user?

No file is being created (unless you count the user avatar), only a database row in the users table.

You should check out the user_save function in the Drupal docs.


Put your project in WAMP's www folder.
Start wamp and make sure both aparche and mySQL is up and running
Go to phpmyadmin http://localhost/phpmyadmin
Create a new database and import your database backup
Go to wamp/www/[your project folder]/sites/default and edit settings.php file.
Set database connection and $baseurl in settings.php file.
Go to http://localhost/[your project folder]


How can we find the id of the parent form in preprocess_HOOK() or HOOK_alter() theme functions?

Not directly, but you can do it in two steps. In a form alter, set whatever information you need on the element where you later need it.

I'd suggest do use some sort of prefix, like #project_form_id = ABC

That should then be available in the preprocess/suggestions hooks.


Show forbidden content to non-authorized users when viewed in a Panel(-s Node/-ized Node), not when otherwise?

I do two things.

I install Rabbit Hole, and configure those nodes/content types to be inaccessible.
I install Custom Search, and configure it to exclude those content types from search results.

IIRC, there is an issue open for Rabbit Hole about excluding nodes/types from search, but I don't think there has been any progress or real discussion on it.

Also take a look at Don't index certain content types for another approach for handling the search results.


"SELECT DISTINCT node.nid AS nid" killing MySQL performance?

from what I see, you may be running views, and complex views, that perform complex queries. execute() is a database abstraction layer function. I am deducing that you are using views from the image you sent, which lists queries that look like generated by the views module.

Luckily, if my supposition is correct, then your problem can be lifted. When editing the view, you can enable caching. Unless you have a constant flow of new view items, you can make caching time 10, 30, or even 60 minutes. Or more. Making these expensive queries cached will lift the overhead. Also, if you are using panels, you can cache panel panes as well, or whole pages for anonymous users, keeping in mind, that caching on the larger level (page vs a single view) is more preferable.


Drupal 7 Does “New Node Creation” initiate/prepare the Fields for different Content Types?

The node can have fields attached to it. If any are required and not provided then I believe your save() will fail with an error message. If your fields provide a default value that value will be used for those fields.

If there are no required fields. The basic node information (nid, type, title?) will be the only values set on your new node (and timestamps, owner uid).

I believe it's up to you the developer to assure the fields have the data you want when you save the node (and meet the Requirements of the node/fields configuration) from the Field UI.


What would be the correct way of adding a link to existing path into admin menu?

I think the easiest way to do this would be to create a fully fledged menu item and simply forward it on to the node/add page using drupal_goto() as the page callback:

function MYMODULE_menu() {
  $items['admin/content/add'] = array(
    'title' => 'Add Content',
    'access arguments' => array('administer nodes'),
    'page callback' => 'drupal_goto',
    'page arguments' => array('node/add'),
    'weight' => 10 // Use this property to control where in the menu the item will appear.
  );
  return $items;
}


Why is my field not showing up in the template?

Your code is right. If field_secondary_links is in $content, it should be rendering it out. You might want to double check that the field is named correctly. If you have devel installed, try using dpm($content) to make sure the field is in there, that it is named right, and the the correct data is getting pulled in.

EDIT =======================================================
If $content is unavalible for whatever reason, you can still render this from $node, but it's a bit diffrent. Your code should look like this:

<?php  print render(field_view_field('node', $node, 'field_secondary_links', array('label'=>'hidden'))); ?>

You can remove the array('label'=>'hidden') from field_view_field() if you want the label to show up.

That should prerender and then render the field for you. Not sure why your $content is missing though, but this should be a workable work-around.


remove the filter and only add the contextual filter with taxonomy term id.
also change path to /Dog/%.


No.

Blocks aren't entities in Drupal 7, so there's no real way to add fields to them.

If you want fields on blocks, then take a look at the awesome Bean module.

  Beans were driven by the API first. This means that you can create
  block types (bean types) all in a plugin class turning off the UI. The
  entire configuration in code. No worry about feature reverts.


How to remove the "Save" button from checkout cart summary form?

One way of doing this is implementing hook_form_alter and hiding save button. Check example below:

function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID') {
    // Set access to FALSE will prevent rendering form element on form.
    // Check the hierarchy of 'Save' button, before using #access.
    $form['actions']['save']['#access'] = FALSE;
  }
}


As mentioned by @clive in the comments, the issue is certainly specificity or style precedence, which basically means that some CSS rules will have more importance than others. I'll give you the 2 most basic things you need to know:

Order. The latest in the code a CSS rule is, the more power it has. So, your custom CSS stylesheet should be loaded after other stylesheets.

Selector specificity. By rule, the more specific a selector is, the more power it has. An ID selector takes precedence over a class selector, and a class selector over an element selector. For instance, let's say you want to style a div:

...

In your CSS, you could reference this div in, basically, three ways:

div { color: red; }

.col-md-1 { color: green; }

#login { color: orange; }

In this case #login rules will have precedence because of two reasons: Order (it is below the other two selectors) and Selector specificity (an ID selector is more specific because it's unique). Therefore, the text color will be orange.

The only exception to these rules is when you use the !important keyword, which adds superpowers to your rule, forcing it to take precedence over any other selector. That's why in your code, it only works when you do this, as you mention.

So, instead of adding !important, try to understand your selectors and you'll do just fine.

EDIT: As mentioned in the comments, a syntax error (in this case, a missing bracket) in your CSS file could cause all following code not being read (Tip: If you use SASS or Scss, they will alert you of these type of errors).


Blocks do not have URLs.  Pages that blocks are on have URLs.
Check the gear icon when you hover over the view area.

If it says configure block, you are on a page created somewhere else and depending on how it was created may need to edit the code where it is defined in hook_menu() or if it is a page node, you can just go to admin/content and search for that page, and at the bottom you will see URL settings.

If it says does not say configure block and only edit view, then that page was likely created by that view you are about to edit.  In this case you can click Edit View and in the middle of the window you will see Page Settings section with a Path field.  You can edit that Path field which is the URL of the view.


What happens if you leave out an `access callback` specification?

Yes it uses user_access() by default, but only when you specify 'access arguments'. See http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_menu/7.


How to prevent a PDO exception when using Rules to Set a data value after saving new content?

Have a look at 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" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what you're trying to do in your Rules Action (related to Set a data value) in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Save new content" for sure completed, and your new content will have been created as expected.

PS: I'm assuming this question is about D7.


How to construct database query with conditions that include 'and' and 'or' clauses?

Here's an example, taken from statistics.pages.inc

$query = db_select('accesslog', 'a', array('target' => 'slave'))->extend('PagerDefault')->extend('TableSort');
$query->join('users', 'u', 'a.uid = u.uid');

$query
  ->fields('a', array('aid', 'timestamp', 'url', 'uid'))
  ->fields('u', array('name'))
   ->condition(db_or()
    ->condition('a.path', 'node/' . $node->nid)
    ->condition('a.path', 'node/' . $node->nid . '/%', 'LIKE'))
  ->limit(30)
  ->orderByHeader($header);

What you want to notice, is the use of db_or(), which adds an OR to your query. There is also the similar db_and(). You can mix and match the two as much as you want. The db_and() documentation also has comments with examples of the two used together.


Is it possible to change the view type form "content" to "content revision"?

Technically speaking, the type of a view corresponds to the base table against which a database query is executed. This means that it sets the stage, so to speak, for the data that is going to be collected. All fields, filters, sort options etc. are configured in relation to that starting point.

Since changing the view type would mean changing the base table, you would be replacing the foundation your view is built on. This a tricky thing to do, because the data you are collecting may not relate to the new base table as it did to the old base table. (In a more radical example, imagine turning a Content view, which retrieves the node ID, into a User view. That would break because users do not have a node ID.)

So is it completely impossible? Maybe not, especially because node and node revisions are somewhat similar. When you look at the exported configuration (YAML markup) of a "Content" view, you will see a line base_table: node_field_data. In a "Content revisions" view you will find the line base_table: node_field_revision. If I had to try this (disclaimer: I never did!), I would do the following:

Duplicate the view I want to change (so I don't lose the original) and save it without changing anything
Go to /admin/config/development/configuration/single/export to get the config YAML of the duplicated view
Copy the config and paste it into a text editor
Change base_table: node_field_data to base_table: node_field_revision
Delete the duplicated view
Copy the edited YAML from your text editor and import it via /admin/config/development/configuration/single/import
Hope that the import doesn't generate errors
Go to the configuration screen of your newly imported view, see if it reports problems, and try to make it work

Good luck. When you do try the above, I would love to read if it worked for you.


Using a template for a custom admin page made with hook_menu

Have a look at this question on stackoverflow: https://stackoverflow.com/questions/5305114/drupal-7-how-to-load-a-template-file-from-a-module

It basically comes down to this:

Implement hook_theme()
Create the template file
At the end of your newsletter_admin_content_block call theme() with your template key (as defined in hook_theme()) as first argument and any additional variables that you need in your template as an array.

Example:

function hook_theme($existing, $type, $theme, $path) {
  return array(
    'newsletter_admin_content_template' => array(
      'variables' => array('var1' => NULL, 'var2' => NULL, ...),
      'template' => 'newsletter-admin-content-template'
    ),
  ),
}

And at the end of your menu callback:

return theme('newsletter_admin_content_template', array(
  'var1' => $var1,
  'var2' => $var2,
  ...
));


Switch to a stock D7 theme - clearing the cache is not enough if there's a bug in your theme as the buggy code is still going to reload.

Either use drush (highly recommended) to change your default theme to another, or...
Use the techniques mentioned here (should apply to D7): http://drupal.org/node/200774 or...
Rollback to your D6 code/database, disable the borked theme, and then retry the upgrade.


How can I manually add a subscription to an account using Commerce Subscription Product module?

I've honestly only quickly glanced at it right now, but as far as I can tell, a valid subscription is simply the field field_commerce_sp_time having a value, in number of weeks the subscription is valid from today.

Thus, you should be able to simply edit the user entity as you usually would, and set any number of week you want. Note that the module ships with relevant permissions for editing the field, so you need to have the field_commerce_sp_validity permissions.

Similarly, you could directly insert the relevant value into the database with

db_insert('field_commerce_sp_time', 'fcst')
  ->fields(array(
    'entity_id' => $uid,
    'entity_type' => 'user',
    'value' => $number_of_weeks,
  ))
  ->execute();


What is the menaing of print t(); in following code?

Yes, it's Drupal's string translation function.

t()

  Translates a string to the current language or to a given language.


How to use template_preprocess_views_view to pass a variable to a views tpl file

As you would also know, a view has several templates, which can vary depending on the style, for example:

Display output: views-view.tpl.php
Style output: views-view-STYLE.tpl.php
Row style output: views-view-fields.tpl.php
Field content: views-view-field.tpl.php

etc.

Each of those templates has its own preprocess function. What you do in your code is only affecting the display output since you are preprocessing only the views-view.tpl.php (template_preprocess_views_view)

To find out which template files are available to your specific view, you can go to view edit page and under 'Advanced' section at the end of the column click on 'Theme: Information'. You will see which template files your view is using (in bold) and which template files you would use to override them.

The preprocess functions should be named after the template file, replacing the dashes with underscores. For example for views-view-STYLE.tpl.php would be template_preprocess_views_view_STYLE().


How to set the size attribute of a select field?

You might be able to do it with the #size property of the Form API. I am not sure, but you might need to also set the #multiple property to TRUE in order for the #size to be honored.

It it also not clear from the question if you are creating your own form using the Form API, modifying an existing Form API form using a hook_form_alter(), or writing your own form HTML (which I imagine - and hope - you are not doing).


How to filter views results based on entity reference field

Advance View Settings -> Add Relationship -> Select Entity Reference Field

Then in filters -> add Filter-> Select field from the respective entity.

Thanks


How to customize a contributed module's template

To apply changes in templates, you must first rebuild Drupal's theme registry.

Navigate to /admin/config/development/performance and click on "Clear all caches" button.


WYSIWYG Editor with highlighting for PHP code input

For output highlighting, you want the Syntax highlighter module. That syntax highlighting module integrates with a couple of other WYSIWYG modules, and you can find great setup instructions.

For in-editor syntax highlighting, you will want the Wysiwyg CodeMagic module. It depends on CodeMagic, TinyMCE, and Drupal's WYSIWYG module. That will allow you to do input highlighting, as demonstrated here:


In time Drupal will have Drupal 8 -> Drupal 8 migration, but it will be a while since migration from D6 and D7 is more important. Right now there aren't any easy solutions for this.

The most sound solution would be to create a service on the beta site that exposes the data on the beta site and create a script that fetches this.

You can use RELAXed Web Services to help creating webservice on the beta site.


Is it possible to search content by date in combined field filter views?

Yes.  Just make sure you have enabled the Date Views module (part of the Date project).


How can I login to my local drupal site 8.3.1 which was under maintence mode

You can also try to login by enter below url.

http://example.com/?q=admin
or
http://example.com/user