How to make an existing private OG group and its nodes public?

How to make your private OG group public, and existing posts in it:

Make the group node public. Edit the group node and set "Privacy settings: Any site member can contribute". You did that already. It should be all there is to do, but due to bugs we have some more steps:
Make existing content nodes public. Set the group_content_access field of existing posts to "Public - accessible to all site users". For that, run the following command, replacing 3183 with the node ID(s) of your own affected group node(s). We use drush here, but you could also run it in the database directly.

drush sql-query "UPDATE field_data_group_content_access
  SET group_content_access_value = 1
  WHERE entity_type = 'node' AND entity_id IN (
    SELECT etid
    FROM og_membership
    WHERE entity_type = 'node' AND group_type = 'node' AND gid IN (3183)
  )"

(Note to self: Don't copy&paste such commands to a Freemind rich text node for adapting before executing. Saving, re-editing and then copying the node content will convert spaces to non-breaking spaces, making the SQL commands fail with confusing error messages.)
Check results. Check that the group_content_access field is now 1 for all nodes in your group. To do that, execute this, again replacing 3183 with your group node ID(s):

drush sql-query "SELECT entity_id, group_content_access_value
  FROM field_data_group_content_access
  WHERE entity_type = 'node' AND entity_id IN (
    SELECT etid
    FROM og_membership
    WHERE entity_type = 'node' AND group_type = 'node' AND gid IN (3183)
  )"

Make future content nodes public. Due to a bug, the Drupal Commons setting "Any site member can contribute" that we changed above does not properly change the relevant OG setting. This causes new posts to be still "Private - accessible only to group members" (value 1, in this case). So we have to change the OG setting ourselves. To do that, execute this, again replacing 3183 with your group node ID(s):

drush sql-query "UPDATE field_data_field_og_access_default_value
  SET field_og_access_default_value_value = 0
  WHERE entity_type = 'node' AND entity_id IN (3183)"

Rebuild permissions. Either do click the button in admin/reports/status/rebuild, or run:

drush php-eval "node_access_rebuild();"

Background knowledge and details

Setting the group node to "Privacy settings: Any site member can contribute" as you did does not affect already existing group content nodes because they have a separate field group_content_access that has been set at node creation to value 2, according to the then-active group settings (2 means "Private - accessible only to group members", as can be seen when editing a content type's group_content_access field via the Drupal CCK interface). So you have to set this field somehow manually to 1, which means "Public - accessible to all site users".
In order to change the group_content_access field, when using vanilla OG modules you can just change that in the node create / edit form as the field shows there. In your version of Drupal Commons however, it does not show there. This is a tweak via a hook, since Commons wants to simplify the group visibility logic by introducing the group-wide "Privacy setting" field. It means we had to resort to direct database manipulation above.
The "Group content visibility" (group_content_access) field has a third value 0, meaning  "Use group defaults". Using it leads to a fallback to the value of the "Group visibility" (group_access) field of the containing group, as confirmed here. It does not mean a fallback to group_content_access field of the containing group, as confirmed here (that field only exists if the group is simultaneously group content). Anyway, this fallback behavior is confusing and inflexible, as the fallback value does not allow to have a publicly visible group node with private content nodes. A rework is under discussion.
Drupal Commons 3.x-3.12 and newer has a workaround for this that enables having a publicly visible group node with private group content nodes. It's done with the combination of the group's privacy settings you used ("Joining requires admin approval" plus "Hide contributed content from non-members"). This is only a workaround however, since it means that all group content nodes have to set their "Group content visibility" field to an explicit value (1 or 2) rather than the fallback (0). It leads to the manual effort when wanting to change a group from private to public later, as you tried. This should be considered a bug that is still awaiting its real fix. I want to report this to Drupal Commons, but have to re-test with the newest release 7.x-3.19 first.


Keep file download list of each authenticated users

The Download Count module may be useful. The module page says

  The download_count module tracks downloads of private files attached
  to nodes via the core upload or contributed filefield modules for d6
  and private core file fields for d7.

But it has only development version for D7.


Devel : what kind of information devel_boot, devel_shutdown and php tweak describes?

devel_boot is the memory in use during hook_boot. It is the amount of memory Drupal is using just getting bootstrapped and ready
to run module and theme code.
php peak is the maximum amount of memory in use during your page request. It is provided by the PHP function
memory_get_peak_usage. This is probably the most important metric to consider.
devel_shutdown is the memory in use at the last possible moment it can be measured with code in a request. It is registered
via drupal_register_shutdown_function() which registers functions to be called once all other PHP code has finished executing.

Memory is important to monitor, but it doesn't seem like you are having issues with memory use. I can see from your screenshot that you are using 42MB of memory - that is nothing to be concerned about in most cases.

I would be more concerned about your slow cache queries (highlighted red in your screenshot). Try and figure out why they are taking so long to run.

There are a lot of resources on the web and drupal.org on improving performance. The biggest wins will come from caching and improving SQL performance - then you can start honing in on code profiling to figure out where your time is best spent.

Some resources that may help:

Performance articles on drupal.org
Tuning mysql
Presentation at Drupalcon London

Best of luck!


How to link a custom menu to a custom button in drupalgap?

When put in the header or footer block, just give the page id the block name. Here is the code:

/**
 * Implements hook_block_info().
 */
function footer_intrfc_block_info() {
  var blocks = {};
  blocks['footer_intrfc_block'] = {
    delta: 'footer_intrfc_block',
    module: 'footer_intrfc'
  };
  return blocks;
}

/**
 * Implements hook_block_view().
 */
function footer_intrfc_block_view(delta, region) {

var html = '<div>';
var btn_setup = theme('popup', {
            content: theme('jqm_item_list', {
                items: [
                  l('View profile', 'user'),
                  l('Login', 'user/login'),
                  l('Logout', 'user/logout')
                ]
            }),
            attributes: {
               id: drupalgap_get_page_id() + '_footer_intrfc_block'
            },
            button_text: 'Setup',
            button_attributes: {
              'data-icon': 'gear'
            }
        });
html += btn_setup + '</div>';
return html
}


You can attach the drupalSettings in any form / build / preprocess etc.

Something like :

function HOOK_preprocess_html(&$variables) {
 $variables['#attached']['drupalSettings']['path']['themeUrl'] = \Drupal::theme()->getActiveTheme()->getPath();
}


Can I put batch api callbacks in an include file?

Actually, there is a file directive in the batch array. I found it was necessary to include drupal_get_path to fully reference the file's path.

'file' => drupal_get_path('module', 'MY_MODULE') . '/includes/my-batch.inc'


How to update Twig - does it need to be updated?

Drupal core may update that dependency if it complies with the Allowed changes during Drupal 8 release cycle documentation page. A library may be updated to a more recent version in a minor release of Drupal (such as 8.1.0 or 8.2.0). Any feature requests or bug reports should be discussed in the issue queue for Drupal core.

Composer dependencies do not update automatically, but are based on running the composer command on the composer.json (or lock file).

However a contrib module may add its own Composer dependencies, which could alter dependencies added by Drupal core outside of a release. Composer looks through the entire dependency graph to choose a version to install, and this might update Symfony or Twig or Behat for instance. You can learn more about how Composer deals with semantic versions, which is similar to npm (node.js).

It is probably not safe to update to an arbitrary version of Twig because that may break core or contrib, but it is possible to update to a compatible version without waiting for an update in Drupal core.


How can authenticated users of a site join a group implemented using Groups module?

Drupal 7

Download and activate Group.
Activate submodules Group add (gadd) and Group node (gnode).
Click on Group that now appears in your menu bar next to Content (/admin/group). This is the main overview for administering Group, here is where new functionality will appear when you activate more submodules.
Go to Group Types, in a tab on the page (/admin/group/type)
Add a group type, you only have to choose a name
Click "edit permissions" (/admin/group/type/manage/partner/permissions)
Activate suitable permissions. "Outsider" are logged in users that are not part of the group. Add at least view and add permissions for one content type for members, and "View group" permission.
Go back to the Groups start page (/admin/group)
Create a new group
Click on your group name, then click Add member
Add some members
Log in as one of those members, go to your account, click the Group tab, click on "view group"
Add some content

Now you have the basics of a group. Users, content, permissions and some ways to interact. Look through the rest of the tabs on all pages you visited, go into the detailed settings screens, activate more submodules, group roles, group permission etc. Extend using the group api hooks. Set up a suitable user interface using standard tools (views, VBO, rules, fields on the group).

For other settings you can visit following urls :

https://www.drupal.org/node/2711123
https://www.drupal.org/node/2711049
https://www.drupal.org/node/2711119
https://www.youtube.com/watch?v=w2Ol19OzNAQ

Drupal 8

Watch this video for a excellent and complete use-case configuration.

Hope this will clear all doubt.


This is what I tried and it works perfectly,

http://test/api/node?parameters[nid]=1&parameters[field_category]=1


How to get Tb Mega Menu working in Chrome?

After so much time I found an answer. I Just increase the z-index for that li and the dropdown start working for me.


How to change the image style used in a field in specific view results?

The bad news is that you can't use that approach anymore. Due to the performance improvements like this one, fields are all rendered via #pre_render callbacks, and run through the same build process as normal entity rendering.

The good news is that hook_entity_display_build_alter() will run, the very same hook that runs for displaying an entity.

Views doesn't pass any additional context to this hook. Depending on how you were deciding which one to alter, you may still be able to accomplish this.


user_login_finalize() logins the user, but I remain anonymous

You mean that the user remains anonymous in the browser session, right? (In Drush, you must pass -u uid on every invocation to specify the user, because Drush is stateless.)

Make sure that the Drupal session cookie is being set in the browser.  If, for example, you set the cookie in the secure context (https) and then redirect to http, the cookie will be inaccessible, and the user will remain anonymous.

Edit: user_login_finalize requires a $form_state parameter; see: http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_login_submit/7  It's hard to see which fields of the form state are relevant, since it is just passed to user_module_invoke.  However, if you compare what is in $form_state during a normal Drupal login, and supply the same information in your function, then it should work fine.


To merge fields you should override a template in your view. ( Views 3 and HTML5 - how to override output for markup? )

I'm new to theming in drupal and wanted to merge fields myself to make collapsible fields few days ago as well, but with no luck. Then I used a css-only workaround  without merging fields or modifying any markup. I used it recently in a comision work:

http://aelasoca.cat/web/

The frontpage is an unformatted view using fields. Each 'new' has the standard separate fields in separate divs (Title, image, date, intro-text, category). I used relative/absolute css positioning and opacity to show/hide text and put it over the image. Then with :hover behaviors and changing opacities and positions again I can make appear or dissapear fields. I've used this as reference:

http://www.sohtanaka.com/web-design/css-on-hover-image-captions/


How to add a country to the location module?

So maybe my question wasn't worded in the best way, but I have found the answer.

All countries in Drupal (at least in 7) are taken from the /includes/iso.inc file. This includes Location and Address Field.

You can add countries to this list via drupal_alter

An example:

<?php
function hook_countries_alter(&$countries) {
  // Elbonia is now independent, so add it to the country list.
  $countries['EB'] = 'Elbonia';
}
?>

Putting this in a custom module will enable you to add countries as you require. You must use a 2 letter iso code!


Organic Groups Permissions and Site-wide Roles

In order to solve this we had to use an additional content access module, and we picked Simple Access.

Using the OG user roles built into OG for D7 we got our editing permissions under control, but that did not allow us to control viewership permissions for the content at all.

By utilizing Simple Access in addition to OG, we have the solution that we needed.


I finally decided to add a 'Cover' cck field to the Album type. I could not find a way in Views to correctly relate an Album to a View of photos for this purpose using Relationships.


The problem is that Drupal is unable to find the element #abcd in the further calls.

Since you are returning the values alone, it will replace the element #abcd with the value; so the element #abcd will be removed from the document, and it will not be available for further processing. That's why it is not updating the values in the second time.

To overcome this in form_example_dynamic_myajax(), you need to return the values like in the following code.

 function form_example_dynamic_myajax($form, $form_state) {
   return '
' . $form_state['values']['tables'] . '
';
 }


Adding own variables on user registration to created user

How about using the Profile 2 module for this? Exceerpt from its project page:

  Designed to be the successor of the core profile module, which is deprecated for Drupal 7. In contrast to the deprecated module this module provides a new, fieldable 'profile' entity ... leverage the power of fields!

Refer to this video for an introduction to Profile 2 also.

Maybe you also want to consider something like the answer to How to display a profile form using profile2 module ?


Fatal error: Class 'Drupal\module_name\DOMDocument' not found

You need to rename the form class file CamelCase and make a namespace declaration at the top. The namespace will be Drupal\module_name\Form. Place the form class file in directory module_name/src/Form/.


How would I get taxonomy info using the taxonomy term ID, in order to theme it?

taxonomy_term_load() looks promising.

  Return the term object matching a term ID.

  Parameters

  $tid A term's ID

  Return value

  A term object. Results are statically cached.


This is perfectly normal.
Every module you have enabled declares its own set of requirements. In your case, it seems that one module requires a version of PHP greater than the Drupal 7 default minimum PHP version of 5.2.4. Because of this, you will see two entries in the status report:
The first entry shows you what version of PHP you are using. This is always present.
The second entry shows you a status message from one of your enabled modules. This also shows you the version of PHP you are using, but in a slightly different format. This is only present if you have a module that checks the PHP version in hook_requirements().
If you want to find out which module you are using requires a non-standard PHP version, search your modules directory for hook_requirements. This is usually found in the <modulename>.install file for the module.
You will commonly see multiple entries for a variety of things. In my experience, the most common (in Drupal 7) is for cURL support - many modules require cURL, so you may see two, three, four or even more lines in the status report that tell you cURL is enabled. Again, perfectly normal.


If you are using Twig Extender , try updating it to version 8.x-2.0-rc1. It worked for me


I am not sure where you encounter RSS, but I am only aware of it being on the front page. That feed is generated from a second display on the frontpage view:

Other modules might define their own feeds in a similar fashion, but I have not found them yet.

There is no such thing as 'disable RSS', so you cannot disable it globally.


In Drupal 7, what is the proper syntax to call the theme function for a node, passing an argument?

The function you're looking for is node_view():

$view_mode = 'teaser'; // Or 'full'
print render(node_view($node, $view_mode));

It's the same function that Drupal internally calls to display the node page/teaser so your template files will be honoured as you'd expect.


Exclude specific nodes from a view based on role permissions

Views does not respect hook_node_access which is what this module uses. Module creator should've used hook_node_access_records along with hook_node_grants instead.
You could try comment #3 as a workaround.

/**
 * Implements hook_views_pre_render().
 */
function example_views_pre_render(ViewExecutable $view) {
  $user = \Drupal::currentUser();
  $vapn_config = \Drupal::service('config.factory')->get('vapn.vapnconfig');
  $vapn_node_types = $vapn_config->get('vapn_node_list');

  foreach ($view->result as $key => $row) {
    if ($row->_entity) {
      $is_vapn_bundle = FALSE;
      if ($bundle = $row->_entity->bundle()) {
        $is_vapn_bundle = in_array($bundle, $vapn_node_types);
      }

      if (!$row->_entity->access('view', $user) && !$view->query->options['disable_sql_rewrite'] && $is_vapn_bundle) {
        unset($view->result[$key]);
      }
    }
  }
}

credit: ash2303


page which display only $content (no header,footer,sidebars)

Drupal works its way down a function call stack to find and use hooks defined in other places. So, in much the same way that THEMENAME_preprocess_page() works, so does MODULENAME_preprocess_page - See http://drupal.org/node/223430 for the specific order that these preprocess functions are called.

Now, as for setting up the template. You define it using http://api.drupal.org/api/function/hook_theme - As an example from the block module:

function block_theme() {
return array(
'block' => array(
      'render element' => 'elements',
      'template' => 'block',
    ), // Omitted remainder.

Notice the 'template' attribute. That maps to block.tpl.php. So assume the following:

function myModuleName_theme() {
return array(
    'my_themehook_special' => array(
        //notice I am setting this up to look for the file in a subdirectory of the module
        'template' => 'moduleSubdirectory/filenameOfTemplate',
        'arguments' => array('yourArgumentObject' => null),
    )
);
}

That would register your template. Check out this blog post for more: http://www.trevorsimonton.com/blog/tplphp-hooktheme-drupal-variable-template-module


There are a number of different ways to build your own taxonomy term lists via views-driven output. One of these methods, which appears to be the one that you are working on, is to override the core taxonomy/term/% path with a view display. This "routing-level" override just ensures that all requests to a taxonomy/term/[id] page are handled by your view instead of the core term list callback. In order for this to work however, your view needs to use the exact same path as the core taxonomy term path (i.e. taxonomy/term/%), and implement a contextual filter for the term id. This path is independent of any path alias patterns you may have setup for your taxonomy terms. So if one of your term vocabularies is aliased with a pattern menu-tags/resource/[term-name], the actual Drupal path that views needs to respond to, and override, is still taxonomy/term/[id].

It's also worth pointing out that this technique has some drawbacks. Most notably you don't have the ability to define different view displays for different taxonomy vocabularies (as all vocabularies use taxonomy/term/% as their raw path by default). Because of this you may want to consider an alternative approach of using the taxonomy display module. Instead of overriding just the term path, this module overrides the actual rendering of the term page itself, and therefore has a bit more flexibility. It's also fairly easy to setup, just check out the documentation.


How to display content of a link in a tooltip on hover

Beauty Tips is a drupal module and a jQuery plugin that will allow you to display content tooltip style via hover, click or a range of other events.

There is to my knowledge not built in support for loading content from different placed, but this is near trivial with the power of jQuery AJAX APIs.


I am not sure if following is what you're looking for, it helped me when I was doing something similar
$sql_snippet = <<<EOF

ROUND(
CASE $this->tableAlias.$unit_column
WHEN 'kg' THEN $this->tableAlias.$this->realField * :kg_coefficient
WHEN 'lb' THEN $this->tableAlias.$this->realField * :lb_coefficient
END
, :precision) = :value
EOF;
// The difference in this invocation of ::addWhereExpression() compared to
// the invocation in the filter handler is that here part of the DB
// placeholders come from $this->options (such as precision) and others come
// from the actual argument we have received, i.e. derived from
// $this->argument.
$this->query->addWhereExpression(0, $sql_snippet, [
  ':value' => round($arg['value'], $this->options['precision']),
  ':kg_coefficient' => $kg_coefficient,
  ':lb_coefficient' => $lb_coefficient,
  ':precision' => $this->options['precision'],
]);

}
Lifted from Here


Views "Load More" replacing results instead of appending

You can also try Views Infinite Scroll module.

  Views infinite scroll allows you to load and display pages of any view
  inline, using AJAX (this has been called infinite scrolling, load
  more, autopaging, endless pages and more). The pager can be triggered
  with the press of a button or automatically as the user scrolls to the
  bottom of the view's content.


How to install a specific version of drush?

The recommended way to install Drush is via composer.

composer global require drush/drush:5.9.0

See the Drush README for instructions on installing composer.


You can get the current node like this:

if ($node = menu_get_object()) {
  if ($node->type == 'foo') {
    ...
  }

But don't put that logic directly in a template file - move it out to a preprocess function instead.


How do you render a table within a custom module in drupal?

Here's a tutorial which should answer your question:
https://www.drupal.org/node/156863

It's difficult to say much about the way you're querying the database without knowing more about how your data is stored. I will say that you might benefit from defining an Entity type for your achievements.

When it comes to rendering the table you should be returning the output of the 'theme' function, passing 'table' as the first arg, then the header and rows as the second and third:

return theme('table', $header, $rows);

The API page for your version of Drupal will tell you how to structure those variables:
https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_table/7


List of people who flagged me since my last login

In the filter criteria add flaggeds time filter.
An operator with is greater than or equal to and write a date whatever you want, doesnt matter wich one, because where are going to modify programmatically later.

Then in your module we have to rewrite that filter to put the last login from the user.

/**
 * Implements hook_views_pre_view.
 */
function YOUR_MODULE_views_pre_view(&$view) {
  if ($view->name == 'VIEW_NAME') {
    global $user; //Load user
    $view_filters = $view->display_handler->get_option('filters');
    // Put the user last login in the flag filter we created before
    $view_filters['timestamp']['value']['value'] = date('Y-m-d H:i:s', $user->login);
    $view->display_handler->override_option('filters', $view_filters);
  }
}


No class for images when working with a specific theme (no .field--name-field-)

The most likely scenario is that the theme does not implement those field classes. Not all themes implement classes the same, but rather take a bottom up approach - the theme starts off very "clean" with only enough classes to support core behaviours etc, leaving it to the themer to add more classes as required. An example of this is the Stable base theme.


Well i think you could do a hook_form_alter and alter the edit page when they go there.  You would need to do a user_load($user) to get the information and then alter the form with those values.  The tricky part is the password is encrypted so that may be an issue.

Example of user load

global $user
$user_info = user_load($user);

Example of hook alter on profile page

function mymodule_form_user_profile_form_alter(&$form, &$form_state)
{
 //Code here
}

http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load/7
http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7


How to create nested paragraphs items programmatically?

After two days, finally, i got it working.
Step 3 is not necessary. My error was in step 2, where I wrote badly the bundle name :-(
so it was

new ParagraphsItemEntity(
    array(
      'field_name' => 'field_acordeon_hijo',
      'bundle' => 'acordeon_hijo'))

note the underscore in acordeon_hijo


How can I add to the class name of a form element?

I think it needs to be an array.

Try this:

$form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));

You can also call it directly from hook_form_alter().
For example in your themes template.php you could add:

function YOURTHEME_form_alter(&$form, $form_state, $form_id)   {
  if($form_id == 'YOUR_FORM_ID') {
    $form['grant_opportunity_end_date']['#attributes'] = array('class' => array('datepicker'));
  }
  // this displays some general info so you can check
  drupal_set_message("Form ID is : " . $form_id);
  drupal_set_message(dprint_r($form, TRUE));
}


If you want inline javascript in order to pass some computed variables, then it seems that the only way to do it in D8 is to use a combination of drupalSettings and an attached library.  The following snippets are copied from Attaching configurable JavaScript in the official docs.
In mymodule.libraries.yml, declare a library containing your javascript file, with a dependency on drupalSettings (and on jQuery):
cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Then, when building (or altering) your render array, attach the library and save something to the settings:
$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

Presumably, you have something more interesting than 'bar'.  Finally, access the setting in your javascript file as drupalSettings.fluffiness.cuddlySlider.foo.


Where can I set cardinality for a custom field?

Yes, you can limit a custom field to single value by defining a cardinality in the annotations of the field type.

I don't know if you can find this in the docs, but you can use the core comment field as example:

/**
 * Plugin implementation of the 'comment' field type.
 *
 * @FieldType(
 *   id = "comment",
 *   label = @Translation("Comments"),
 *   description = @Translation("This field manages configuration and presentation of comments on an entity."),
 *   list_class = "\Drupal\comment\CommentFieldItemList",
 *   default_widget = "comment_default",
 *   default_formatter = "comment_default",
 *   cardinality = 1,
 * )
 */
class CommentItem extends FieldItemBase implements CommentItemInterface {

When you add a comment field to a content type the cardinality form element is hidden and instead this message is displayed:

  Allowed number of values

  This field cardinality is set to 1 and cannot be configured.


Everything you mentioned in the post is achievable by Drupal.

But not with just one module or a theme. Each functionality has its own module

1) Theme
There are lots of themes available in drupal download section which you can go through and decide on the theme that matches your requirement or you could build one on your own.

2) The profile page with in the Drupal has option to add the required fields. But if you want to extent it you can go for http://drupal.org/project/profile2

3) These additional two modules can show the percentage of the profile completed and if the profile needs to be completed. http://drupal.org/project/pcp and http://drupal.org/project/complete_profile

4) User approval is in build in Drupal.

5) To achieve the admin type you are looking there are two options one is organic groups and make each geographic location a group and give group admins the right to admin the members of that group. Another option would be to create a user role per geographic location and have the user select the role during the registration process using the autoassign role module and the use http://drupal.org/project/administerusersbyrole module to assign admin rights per role.

6) Once you use profile2 each profile is a content with in drupal and you can do all the searching that is default to drupal or you could also create views with exposed filter to do the searching on specific fields.

7) You could add a tag field to the profile and create a view to display the profiles with the tags as the argument to the view page.


filter view by parent of a taxonomy term

There is a view filter as Content: Has taxonomy terms (with depth) which describes as -

Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.

You can select one of the parent term and set the depth of its child terms too.


The revisions are added to the existing entity. There is an EntityRevision destination in core.

See core/modules/node/migration_templates/d7_node_revision.yml here for an example of how you'd migrate revisions.

Note: translated node revisions are not yet supported, but you can look at a good starting point at #2746541.


How can I get the tid (term id) using the id of my node in .theme

I wrote this answer thinking the question was for Drupal 7. This is not accurate for Drupal 8.

If you debug the $node object, you will see that it's more complicated than that. It has a language and probably a value index. So, you could access the TID this way:

$variables['tid'] = $node->field_category[LANGUAGE_NONE][0]['target_id'];

But, don't do it that way. It would be better to use EntityMetadataWrapper. The code should look something like this:

$wrapper = entity_metadata_wrapper('node', $node);
$variables['tid'] = $wrapper->field_category->raw();

If you want the whole term object, you can do this:

$variables['term'] = $wrapper->field_category->value();


Where is the php_error.log file in Acquia Dev Desktop?

Just checked in my installation of DevDesktop and found that my PHP logs are located in /Applications/DevDesktop/apache/logs/error_log.

Although it says Apache logs, PHP errors get logged there as well.

You can find the log locations via 'Preferences' => 'Logs'. DevDesktop version 2 (Apr 13, 2017).


What's the differences between these 2 queries to publish/unpublish nodes?

Let me explain you with all details....

Your First Query is update statement on node table in drupal database which sets node to publish for a particular nid...

db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
    ,array(':nid'=>$node->nid));

Node table is a base table which stores node related information..

Your Second Query is on node_revision table which stores node revisions if you track node revisions which are nothing but updates...

db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND  `vid` =:vid;"
    ,array(':nid'=>$node->nid,'vid'=> $node->vid));

It's discouraged in Drupal to run queries directly on Drupal for certain actions.. For example in your case you are updating a node and setting status to published.. Drupal works using concept of hooks which are events and actions.. If any module is implementing any node related hooks they won't fire if you run queries directly.. So it's discouraged..

Right way of doing above action is using node_save api function in Drupal 7...

$node = node_load($nid);
$node->status = 1;
node_save($node);


Can I create views for error logs?

Yep, you can create Views for pretty much any type of data. There are a couple of existing modules that already do this:

Views Watchdog
Better Watchdog UI

Or you could of course write your own.

To expose Views as services, you can use the Services Views module, or, again, you can write your own resources for the Services module if it doesn't do exactly what you want.


I don't know of a "drupal" way to do this but The calling function will be in the backtrace. I have two helpers I use strictly for debugging. It's not a pretty solution but you might be able to check calling function.

Calling function:

// Returns the name of the calling function.
// Since this function call adds to the stack [0]
// The function calling this adds to the stack [1]
// That means [2] is the desired function name.
function getCallingFunction()
{
  $callers = debug_backtrace();
  return $callers[2]['function'];
}

Full stack:

// Returns the full stack.
function getCallingFunctionStack()
{
  $callers = debug_backtrace();
  $stack = array();
  foreach ($callers as $caller)
  {
    $stack[] = $caller['function'];
  }

  return implode('->', $stack);
}

I do not see a way to prove you are in a cron run but You can check if cron is running with:

if (!lock_acquire('cron', 0)) {
  // cron is running.
}

But this does not mean you are a cron user. It just means cron is running during this access attempt.

You could do something like store the cron session id in a variable on hook_cron_queue_info then check if that is the current session id. Kind of dirty but pretty much guarantees you are in cron.

Several other ideas can be found on this question.


Testing installation profile with custom tasks

I typically find it best to leave your installation profile as bare bones as possible, and put tasks like this into hook_enable of a site specific module.  Similarly, any updates that need to be made should be put into hook_update_N functions in the same module, while updating the hook_enable implementation.

This makes it much simpler to test and has the added benefit of keeping all of your setup and updates in one place.


How to display an "Out of Page" (PopUp) ad from Google DFP on a Drupal 6 site?

Looks like I solved it. Below is how ...

Finally got the process of creating a pop up on DFP figured out, now onto the Drupal part of it. https://productforums.google.com/forum/#!category-topic/dfp/inventory-management/dfp-small-business/e4vUwjgd4lk

UPDATE:

Got it working this way...

OK. Looks I mostly have it.

Just bypassed the Google Admanager module and generated a tag from the ad unit page. Then I put it in my theme page.tpl.php header enclosed in this (to make sure it is only front page):

<?php if ($is_front) { ?>
<script>......</script>
<?php } ?>

And then put the rest in the block with php enabled. I also made sure to remove the adslot generated other than the popup.

Hackish but it does the trick.

But if anyone knows how to make it work with Google Admanager, would love to look at it.


Why don't you use THEME_preprocess_views_view_fields(&$var) function? In this function you may get every field of the view, and do any processing you want just before loading the view. just install devel module, and use kpr to see what variables are available.


Removing the comment sign at "RewriteBase /" fixes my problem on migration of Drupal 7.
in the .htaccess file to fix.


How to call a check for a product class in Ubercart

The function to use is:
uc_product_is_product($node)

This returns a boolean variable indicating whether the node is a product type.


Cache + random + hook_form_user_register_form_alter

When the forms cached, it caches the original, unprocessed $form array, and the builder functions are not called again.

you can explicitly set cache off by setting $form_state['no_cache'] = TRUE;. Note that this has potential to break Ajax forms.


Custom Block Form Not redirecting to New Page

Looks like the issue I was having was twofold. First I need to add some settings:

$form['node-action'] = array(
        '#type' => 'radios',
        '#title' => t('Select Action'),
        '#options' => array (
            edit => t('edit'),
            delete => t('delete'),
            add => t('add'),
            ),
        '#required' => 1,
    );

Then added:

$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('edit_node_submit'),
    );

And lastly my submit function:

function edit_node_submit($form, &$form_state){
    $node_id = $form_state['values']['node-id'];
    $node_action = ($form_state['values']['node-action']);
    $form_state['redirect'] = TRUE;
    if ($node_action == 'edit') {
        $form_state['redirect'] = ('node/' . $node_id . '/edit');
        }
    if ($node_action == 'delete'){
        $form_state['redirect'] = 'node/' . $node_id . '/delete';
    }
    if ($node_action == 'add'){
        $form_state['redirect'] = 'node/add/hospitalist-schedule';
    }
}

Everything is working for the most part.


How can I override Drupal\Component\Datetime\DateTimePlus::createFromArray

As @Daniel Wehner suggests, this can easily be done by wrapping the calling code in a try - catch block. That's what it is for.


How do I unset/hide certain fields from being indexed by the core search module?

Goto the Manage Display page for each content type (eg, admin/structure/types/manage/page/display).

Click on the tab for Custom Display Settings.

You will see the view modes that your system knows about.  Tick Search Index and save.

You can now configure which fields get indexed from the tab for that new display mode (eg admin/structure/types/manage/page/display/search_index)

Dump the search index from Configuration -> Search -> Search Settings ( admin/config/search/settings), and cron runs will re-index everything.  Or, do a drush -y search-reindex; drush -y search-index from the command line.

Start reading from node_update_index() which is invoked from search_cron(), and you will eventually see a node_view($node, 'search_index');, which is how that display mode gets used.


Unable to load css files using ['#attached'] or drupal_add_css

The pathing was wrong after all. The preceding "/" was messing things up. Strangely, this was not an issue for javascript attachments. For example:

$form['#attached']['css']['css2'] = '/sites/all/libraries/data_search/tagme/tagme_jquery-ui.css'; //fails
$form['#attached']['js']['js2'] = '/sites/all/libraries/data_search/tagme/tagme_jquery-ui.min.js'; //works
$form['#attached']['css']['css2'] = 'sites/all/libraries/data_search/tagme/tagme_jquery-ui.css'; //works


Add 2 filters for a single field in views

It depends on your version of views, best way is to create the view in views and then export it, you can then tweak the code as needed.

Here is an example if you had a Node Type Filter and a Date Filter

/* Filter: Node: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'rfp' => 'rfp',
);
/* Filter: Date: Date (node) */
$handler->display->display_options['filters']['date_filter']['id'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['table'] = 'node';
$handler->display->display_options['filters']['date_filter']['field'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['operator'] = '>=';
$handler->display->display_options['filters']['date_filter']['value']['min'] = '2012-01-01 00:00:00';
$handler->display->display_options['filters']['date_filter']['value']['max'] = '2012-01-01 00:00:00';
$handler->display->display_options['filters']['date_filter']['exposed'] = TRUE;
$handler->display->display_options['filters']['date_filter']['expose']['operator'] = 'date_filter_op';
$handler->display->display_options['filters']['date_filter']['expose']['label'] = 'Date: Date (node)';
$handler->display->display_options['filters']['date_filter']['expose']['identifier'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['expose']['single'] = TRUE;
$handler->display->display_options['filters']['date_filter']['date_fields'] = array(
  'node.changed' => 'node.changed',
);


Blocks display in the wrong place and can't be turned off

After nearly going insane I noticed that the module, "Context", was overriding my blocks.


Twig templates for nodes in different views

Do not use node--view-* templates. They are broken.

Two views with entity view mix up rendered templates

The quick solution:

create unique view mode for your CT
display views with content
use unique view mode for your view


This is not the correct answer, but i found a different way. If the og_group_ref is set to checkboxes (these checkboxes are essential) (look at admin/structure/types/manage/[YOURCONTENTTYPE]/fields/og_group_ref), you can set the default audience.
Now i just hide the field 'audience' for certain roles and new nodes are saved to the right OG.

Again, this isn't the way i asked to do it with rules. When someone knows the right answer how to do it, i'm eager to hear it.


Can Search API filter "Index full entity" be used in Search API views?

This should be possible. I did the same thing with Search API + Elastic search (No Views module though). And yes it did speed up the results. However, in retrospect I may have been better of using Render Cache module in conjunction with an object cache like Redis and or Memcache.

The main pain point that I ran into doing full storage of HTML in the search server was that nearly every theming/template change required rebuilding the search index.

All that being said, if you want to keep going down this route I suggest using Solr's built in inspection tools to first validate that the user profile HTML has made it into Solr at all.


Pulling CiviCRM data into a custom Drupal module based on checksum/hash link

I am assuming you want to show the organization information of logged in contact.
So I would do following:

Get the contact id of logged in contact (or anonymous user who used a checksum link, via the cid field in the URL, as @petednz noted).
Get the current employer id
then retrieve address of current employer


For a block, the form_id should be:

  search_block_form

and for a page:

  search_form

To easily find this information, install the Devel module:

  A suite of modules containing fun for module developers and themers

and use something like this in your theme's template.php file:

function myTheme_form_alter(&$form, &$form_state, $form_id)
{
    dpm($form);

}

This will show a hierarchical display of all forms on the page - you can then scroll quickly through the info to find what you need. Very handy for searching arrays.


Is there a dummy field to provide additional instructions to the users on node add form?

Try the Markup module:

  This module adds the ability for site admins to add "Markup" widgets to the form. These essentially let designers of cck content-types insert additional markup into the node/edit form to display to content-authors. This is the equivalent of adding additional elements to $form of the type '#markup'.


How to transfer data from the program's created field to the standard text, while saving the node?

I would suggest you create the 'cell' fields through the Drupal UI (admin/structure/types/manage/xxxx/fields) so they are registered correctly as part of the content type, then their values will be available in hook_node_presave().


How can I control access to group-private content based on organic groups roles?

I needed somewhat similar functionality for a drupal 6 site and gave up on using OG for this.
Instead I made a vocabulary that defined my groups and used tac_lite for setting access.
The setup is being ported to drupal 7 right now, and I haven't had any problems implementing the same functionality in d7 so far.
Maybe tac_lite is a solution for you? http://drupal.org/project/tac_lite


Should I use contextual filters to limit the view results for each type of administrators?

Contextual filters

I suggest you review the (free) video about Contextual filters with paths. It covers topics such as:

Using contextual filters for filtering Views result.
Using input from the view path to set contextual filter values.
Using contextual filter values for changing the view title.

If you like its content, you may also want to watch about 5 subsequent videos, also related to contextual filters (sometimes called "arguments" also).

Content Access

Even though your question is specific to Views, it seems like you should give it a thought to also get the Content Access module involved in your setup. Here is a quote from its project page:

  This module allows you to manage permissions for content types by role and author. It allows you to specify custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Just use this module to give appropriate access to each of the groups of users for each of the content types you have. After you do, the view you currently already have will probably not need any (or just a few) refinements. Because Content Access (if configured correctly) will make sure that the view results only include the news from each faculty.

Bonus: you'll find other use-cases for this module soon!

Organic Groups

Organic Groups is possibly an alternative also, which provides 'Groups' for Drupal users, and management of Access Control based on these groups.

In your case, each faculty would probably correspond to 1 such "group". And similar to using Content Access, the view you currently already have will probably not need any (or just a few) refinements.

Bonus: you'll find other use-cases for this module soon!


Create a vocabulary  with fields

taxonomy_vocabulary_save((object) array(
      'name' => 'Vocabulary Name',
      'machine_name' => 'vocabulary_machine_name',
    ));

// Create a field
 $field = array(
    'field_name' => 'field_your_field',
    'type' => 'text',
    'label' => 'your label'
  );
  field_create_field($field);

  // Attach the field to our taxonomy entity
  $instance = array(
      'field_name' => 'field_your_field',
      'entity_type' => 'taxonomy_term',
      'bundle' => 'vocabulary_machine_name',
      'label' => 'Label',
      'description' => 'Description',
      'required' => true,
      'widget' => array(
        'type' => 'text_textfield',

      )
  );
  field_create_instance($instance);

You can create terms like below :

 $term = new stdClass();
    $term->name = ‘Your Term name’;
    $term->vid = 'vocabulary id';
    $term->field_your_field[LANGUAGE_NONE][0]['value'] = ‘data’;
    taxonomy_term_save($term);


Stream_flush in not being called while using stream wrapper

I Just changed the stream wrapper type to STREAM_WRAPPERS_LOCAL_NORMAL and implements the chmod function and it works seamlessly.


How can I display more than 5 nodes on a taxonomy view for one vocabulary?

There is two things you should check.

Re-check if the taxonomy(tags) are referenced correctly in each content.
Secondly check the pager section in views, for pages, offset and more link settings.


You can modify the form by implementing hook_form_alter() either in a custom module or in template.php in your theme.

Here's a code snippet that brings the table above the other form elements by lowering its weight (source):

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (strpos($form_id,  'your_vbo_form_id') !== FALSE) {
      $form['output']['#weight'] = -99; //Decrease the weight of output to rise it above other elements.
  }
}


This is the part of .htaccess, which controls the access to php files:

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

You can see, how the access for statistics.php is allowed. You can add your own rules (at your own risk).


Node referencing: How do you display a node with all its references?

Install views and have it manage your home page, then add a content type filter so that it only shows issues on your home page. This will stop your home page being a mix of articles and issues.

Then, go to each content type and go to "manage display", in there you can specify the format, by default this is set to title (link). You also have an option for "full rendered node" which will display the whole referenced content inline.

Alternatively you could use views and create a block with the nid as a argument so it displays references content in a way you can choose fields to display etc


It sounds like what the client really wants is something like the Paragraphs module:

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

It's a good solution for creating flexible, yet structured, content.

Take a look at this video for a good idea of the promises (and pitfalls) of this approach:

https://www.oomphinc.com/notes/2018/11/component-based-design-system-drupal-8-paragraphs/


You need to enable the Slick UI, then press on configure.

Click on the List tab, and edit the default.

You need to add some breakpoints, make sure you select the correct skin.


Custom page with panels in two languages

You can only have one page as the front page, which I assume is what you want. The way to do this, is using a "Selection rule" on language, and two variants, not two pages.

See Learn Page manager for a deeper introduction to Page manager.


Looking to create a taxonomy term path with a query string

Well, I finally figured it out.

    function cin_rd_init(){

    //first I see if this is a taxonomy page
    if (arg(0) == 'taxonomy') {

    //then I get the termID from the argument
    $termid=arg(2);
        $newterm=taxonomy_term_load($termid);

        if(!empty($newterm)){
        $thetermname=str_replace(' ','-',$newterm->name);
        $thetermid=$newterm->tid;
        $newtermvid=$newterm->vid;

        //Next I check the vocabularyID to see if it should be redirected
        //Important, I also check to see if my parameter string is set already so I don't have an endless redirect.
        if($newtermvid==18 && (!isset($_REQUEST['shs_term_node_tid_depth']))){
        drupal_goto('/Events/All/'.$thetermname.'/', array('query' => array('shs_term_node_tid_depth' => $thetermid)));
        }
        //I can change the destination and query string depending on the vocab I am using
        if($newtermvid==19 && (!isset($_REQUEST['features']))){
        drupal_goto('/Events/All/'.$thetermname.'/', array('query' => array('features[]' => $thetermid)));
        }
} //not empty
} //end if taxonomy
} //end function

So now, anyone who goes to a taxonomy term page will either go directly to the term page, unless the term belongs to either of these vocabularies.

If so, then it will redirect those with a query string.


Create Empty User as Admin, and force entering info on login

It's not possible to create a new user without email, username and password.

The only workaround for this is to create placeholders. E.g. always enter username@example.com in the email field where username is the machine name of the user's full name.

As for creating the user without entering the required fields I think it's best to create a custom form. This form would only contain a textfield Full name.

On submit you dynamically generate the username, email and password (see drupal_clean_css_identifier to easily generate a machine name) and create the user object.

Here's a code example:

$full_name = $form_state['values']['full_name'];
$username = drupal_clean_css_identifier($full_name);
$email = $username . '@example.com';

//This will generate a random password, you could set your own here
$password = user_password(8);

//set up the user fields
$fields = array(
  'name' => $username,
  'mail' => $email,
  'pass' => $password,
  'status' => 1,
  'init' => 'email address',
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  ),
  // If you have custom field 'Full name' do this:
  'field_full_name' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => $full_name,
      ),
    ),
  ),
);

//the first parameter is left blank so a new user is created
$account = user_save('', $fields);


What are valid entity_id and entity_type values for node content?

This error can be caused by having a term reference field that references a deleted term. This reference is not deleted when a term is deleted.

You can check if this is the case using this query

SELECT nid, title from node WHERE nid
   IN (select entity_id from  field_data_field_some_ref
   WHERE field_some_ref_tid not IN (select tid from taxonomy_term_data))

https://www.drupal.org/node/1778572#comment-7256200

There are other cases where this error can occur. Read the issue comments in the link for more info.


Yes, it is possible. you can try the following query to find all entries in 'cache_config' that contain 'to_email':
SELECT cid, data
FROM cache_config
WHERE data LIKE '%to_mail%'

This will get you all the blobs that contain the given field.
Even more than that, you can look for what follows 'to_mail' to get the actual mail by using the LOCATE and SUBSTRING functions.


I want to uninstall l10n_client which may be duplicated

I ran "drush config-delete l10n_client_ui.settings".
I was able to install the module.


Vagrant Drupal Development (VDD) Up Stalls

Hah! I simply added c:\Program Files\Oracle\VirtualBox to my PATH and all is well. I guess it was wanting to use vboxmanage command. I'm happy now.


Unable to save content language configuration

I tried the max_input_vars fix and that didnt work (i have alot of custom entities on the page and was hoping this would work).
I had to check the entity, pretend it was called MyCustomEntity in 'Custom language settings' at the top... but also scroll down to the individual MyCustomEntity settings further down on the page, and also check that checkbox. When I saved, now it worked


Execute pending queues using batch? Possible?

Check: https://drupal.org/project/queue_ui

  Process queue with Batch API


Why Can't Panels Select My Organic Groups?

The way I accomplished this was with Views Contextual Filters and the Views Content Panes module, displaying only content belonging to the particular groups I wanted to see the content.  This approach, however, requires the content being viewed to have a field instance of the group ID that it belongs to (and, incidentally, a field instance for "other" groups the content will be visible in).  Note, in order for the two contextual filters to work properly here (i.e. for the content pane to be visible in two or more groups) I had to install the "Views Contextual Filters OR" module (I can't link twice because no rep).

I couldn't comment because I don't have enough rep, but this approach worked for me, but it might not work in your specific use case.  It should be noted that if nothing matches the filter, the pane is omitted from display entirely (which is what you are ostensibly trying to accomplish).  So many ways to skin a cat with Drupal.


Where is comment admistration template located?

If, for some reason, the whole Author fieldset is hidden, be sure to check the HTML first, then you can also use the devel module for some dpm-ing in yourtheme_form_comment_form_alter.

Something like this should force the fieldset to be rendered:

function yourtheme_form_comment_form_alter(&$form, &$form_state) {
  $form['author']['#access'] = user_access('administer comments');
}


I have used Navicast (but not a free) platform to develop a webtv module for Drupal 6. It is based on Output APIs. There are few limitation with the platform APIs that I reported. Navicast Studio a desktop application build around their input APIs used to upload video and adjust video properties. The platform has built in tagging system to categorize videos. Comments on video contents is also managed by the platform.

I used it with Flow Player API module.

I developed Web TV around my own entities.


Existing orders with deleted coupon throw EntityMetadataWrapperException

If time is a factor you could just create a new coupon that matches the machine name of the old one.

Then when you are ready to fix them, first edit the orders to remove the coupons from them.once all are removed, then delete the coupon.


How to add autocomplete to a textarea on a form?

Textareas don't support autocomplete out of the box, you have to get a bit creative to make it work.

First you'll need to override the attach method of the autocomplete behaviour; add a library with a JS file containing this:

(function ($) {
  Drupal.behaviors.autocomplete.attach = function attach(context) {
    var $autocomplete = $(context).find('input.form-autocomplete,textarea.form-autocomplete').once('autocomplete');
    if ($autocomplete.length) {
      var blacklist = $autocomplete.attr('data-autocomplete-first-character-blacklist');
      $.extend(Drupal.autocomplete.options, {
        firstCharacterBlacklist: blacklist || ''
      });

      $autocomplete.autocomplete(Drupal.autocomplete.options).each(function () {
        $(this).data('ui-autocomplete')._renderItem = Drupal.autocomplete.options.renderItem;
      });

      $autocomplete.on('compositionstart.autocomplete', function () {
        Drupal.autocomplete.options.isComposing = true;
      });
      $autocomplete.on('compositionend.autocomplete', function () {
        Drupal.autocomplete.options.isComposing = false;
      });
    }
  };
})(jQuery);

The function is a straight copy of the core attach method, with the textarea added to the selectors, and a few references altered.

Then you'll need to add the autocomplete process method to the form element (it's not there by default), and also reference your library:

use Drupal\Core\Render\Element\Textarea;

...

$form['text_area'] = [
  '#type' => 'textarea',
  '#title' => t('Test text area'),
  '#default_value' => $authentication_configuration->get('text_area'),
  '#autocomplete_route_name' => 'my_module.autocomplete_name',
  '#process' => [
    [Textarea::class, 'processAutocomplete'],
  ],
  '#attached' => [
    'library' => [
      'mymodule/autocomplete'
    ],
  ],
];

Clear the cache and you should see the results immediately.


I think you need to render send the element as html out put since there is no any theme function defined. See how this output process here.

So your return array should be:

 return array(
          '#markup' => $node_rendered
        );


How to change page CSS based on parent menu item?

If it is just additional classes you need, you can add additional and unique classes to menu items using the Menu CSS Names or Menu Attributes modules.

Or, you can effect the element of another DIV on hover using pure CSS like below...

HTML

Menu Item

Change This Background

CSS

#container {
    background:blue;
}

#menu-item:hover + #container {
    background:red;
}

See Fiddle here... Affect Another Div on Hover


How do I specify in which database my schema should be created?

I have achieved this with the information provided by Berdir. My code looks like:

<?php
function mymodule_schema_otherdb() {
  $schema['mytable'] = array(
    'description' => 'My table description',
    'fields' => array(
      'myfield' => array(
        'description' => 'My field description',
        'type' => 'serial',
        'size' => 'medium',
        'not null' => TRUE,
        'unsigned' => TRUE,
      ),
    ),
    'primary key' => array('myfield'),
  );
  return $schema;
}

function mymodule_install() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_create_table($name, $table);
  }
  db_set_active();
}

function mymodule_uninstall() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_drop_table($name);
  }
  db_set_active();
}


Howto override a function in privatemsg.module?

The _privatemsg_format_participants() function is called from template_preprocess_privatemsg_recipients() function, which is a template preprocess hook. You can simply override template_preprocess_privatemsg_recipients() into your module's .module file or theme's template.php file. Check the example below:

/**
 * Implementation of hook_preprocess_privatemsg_recipients().
 */
function [MODULE/THEME_NAME]_preprocess_privatemsg_recipients(&$vars) {
  $vars['participants'] = ''; // assign a default empty value
  if (isset($vars['thread']['participants'])) {
    $vars['participants'] = _[MODULE_NAME]_format_participants($vars['thread']['participants']);
  }
}

/**
 * Format an array of user objects.
 *
 * @param $part_array
 *   Array with user objects, for example the one returned by
 *   _privatemsg_generate_user_array.
 *
 * @param $limit
 *   Limit the number of user objects which should be displayed.
 * @param $no_text
 *   When TRUE, don't display the Participants/From text.
 * @return
 *   String with formatted user objects, like user1, user2.
 */
function _[MODULE_NAME]_format_participants($part_array, $limit = NULL, $no_text = FALSE) {
  global $user;
  if (count($part_array) > 0) {
    $to = array();
    $limited = FALSE;
    foreach ($part_array as $account) {

      // Directly address the current user.
      if (isset($account->type) && in_array($account->type, array('hidden', 'user')) && $account->recipient == $user->uid) {
        array_unshift($to, $no_text ? t('You') : t('you'));
        array_shift($to, $no_text ? t('You') : t('you'));
        continue;
      }

      // Don't display recipients with type hidden.
      if (isset($account->type) && $account->type == 'hidden') {
        continue;
      }
      if (is_int($limit) && count($to) >= $limit) {
        $limited = TRUE;
        break;
      }
      $to[] = privatemsg_recipient_format($account);
    }

    $limit_string = '';
    if ($limited) {
      $limit_string = t(' and others');
    }

    if ($no_text) {
      return implode(', ', $to) . $limit_string;
    }

    $last = array_pop($to);
    if (count($to) == 0) { // Only one participant
      return t("From !last", array('!last' => $last));
    }
    else { // Multiple participants..
      $participants = implode(', ', $to);
      return t('Between !participants and !last', array('!participants' => $participants, '!last' => $last));
    }
  }
  return '';
}

Note: Make sure to change [MODULE_NAME] with your module/theme name.


TinyIMCE not working: looking for image files

I believe the image component of TinyMCE is a licensed product you have to buy, see http://www.tinymce.com/download/download.php at bottom. You might want to try IMCE module http://drupal.org/project/imce which is free and integrates nicely with the WYSIWIG interface. If you do decide to go that route, afteryou install IMCE make sure you turn on the check box for IMCE in the TinyMCE options inside the WYSIWIG Admin Tab in Admin -> Configuration. Works like a charm for me.


where is the breadcrumb printed at in the omega kickstart theme?

By default it's printed in in the omega/templates/zone--content.tpl.php template file in the Omega theme itself.

<?php if ($breadcrumb): ?>
  <div id="breadcrumb" class="grid-<?php print $columns; ?>"><?php print $breadcrumb; ?>

<?php endif; ?>


I managed to get this to work but welcome better options. I prefer not to alter the theme, but rather use a function or something else instead so that this module can stand alone and not be affected by themes and subthemes and other design team changes.

Here's what I did:

body.node-type-answers-question .page-title {
  visibility:hidden;
}

The source code of the loaded page, which is from a node content type called answers-question. I noticed that there was a "page-title" class in the h1 title. Making the visibility hidden worked for me.


Passing Argument from URL in Panel to View Pane or Block

Example scenario:

There is a panel containing View Content Pane.

Panel URL: /panel_url

Example with argument: /panel_url/term_name

With BEF: /panel_url?category=123

How to set up (having existing panel and added Content Pane):

Add Contextual filter to the View.
E.g.: Views contextual filters taxonomy name
Change settings in 'View -> Pane settings -> Argument input' to load the argument 'From panel argument' (e.g. First).

Done.

In addition, if you're using Better Exposed Filters, you could do the following improvements.

To set the current active link based on the argument (if you're using select_as_links):

/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select_as_links(&$variables) {
  $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
  $selected = end((arg()));
  if (array_key_exists($selected, $options)) {
    $variables['element']['#value'] = $options[$selected];
  }
}

To set the current active link based on the argument (if you're using select):

/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select(&$variables) {
  switch (arg(0)) {
    case 'panel_url':
      if (@$variables['element']['#name'] == 'category') {
        $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
        $selected = end((arg()));
        if (array_key_exists($selected, $options)) {
          if ($variables['element']['#value'] <> $options[$selected]) {
            $variables['element']['#value'] = $options[$selected];
          } else {
            // drupal_goto('panel_url');
          }
        }
      }
    break;
  }
}

To make the links SEO friendly, you can try something like:

/**
 * Implements hook_url_inbound_alter().
 */
function foo_url_outbound_alter(&$path, &$options, $original_path){
  if (arg(0) == 'panel_url') {
    // Convert URL like: /panel_url?category=29 into /panel_url/term_name (SEO friendly)
    $path_info = parse_url($path);
    switch (@$path_info['path']) {
      case 'panel_url/term_name':
      case 'panel_url/term_name2':
        $path = 'panel_url/all'; // Convert loopy urls into base url
    }
    if (strpos($path, '?category=') !== FALSE) { // Convert term id into human name
      list(, $tid) = explode('=', current(explode('&', $path_info['query']))); // get tid from URL
      $term_name = strtolower(taxonomy_term_load((int)$tid)->name);
      $path = '/panel_url' . '/' . $term_name; // See also: $path_info['path']
    }
  }
}


Because form input is always a string, is better to use is_numeric().

See is_float() note.


delete users and all its related records

No.

You can install the Delete All module which provides some command line Drush commands to remove all content and users safely.

  This module is used to delete all content and/or users from a site.
  This is mainly a developer tool, which can come in handy in several
  cases, listed below.

  The usual way to do this is to go to Administer -> Content then select
  all the nodes and delete them. This works if you have a handful of
  nodes only. If you have hundreds or thousands of nodes, then it is not
  a practical solution.

  Another option is to directly delete the nodes from the node table in
  the database. This does not work properly, since there are also
  comments, and many tables for add on modules that needs to be cleaned.

  This is a test site that the client was using for a period of time,
  and they must clean it up before starting with real data.
  You are
  testing something that creates a lot of nodes (e.g. aggregator), and
  want to do it over and over again.
  You created a site in the past and
  want to replicate it again, but with new content.

  Note that for nodes,
  comments and all additions to nodes that contributed modules may have
  added. For users, any additional module data will also be deleted.


About shaping the Drupal "add content" pages

I like to work with Panels to customize the Add content pages. I'll write down a small step by step tutorial to give you a starting point and maybe a better understanding how to module works if you are not familiar with it.

Once you have Panels installed you navigate to » Administration » Structure » Pages in the menu. Then enable the Node add/edit form variant.

When the variant is enabled click Edit and then Add a new variant. Click Create variant, choose layout and click continue on the next step click continue.

Now add the form elements you want in the respective regions by clicking the cog wheel in the top left corner of the region.

Under the category Form you will find all form elements.

In the example below I've added the title and body field to the left and the menu settings and the submit button to the right.

Under selection rules in your panel you can say that this variant is valid for the content type "Page" for example and have another layout/setup for other content types. If you don't add a selection rule the variant will take over the content creation page for all content types.

You can add new Panel layouts to a module/theme if the standard provided doesn't work out for you.

A gotcha
One small gotcha I've experienced is that if a field is not placed in the panel, let's say an image field. And you re-save existing content it will remove the image from the node. When the node is saved the submit function interprets the value as empty. To avoid this add the pane General form to one of your regions and click the cog wheel for the pane and css properties. Under css class enter element-invisible. This way all form elements are present but hidden by css to avoid the missing image situation :)


How to create a single slideshow combining several image fields?

<?php if ( ($image_slide == 'true') ): ?>

                <?php while ($img_count < $counter) { ?>

                                <a class="bwWrapper single-image link-icon" href="<?php print $node_url; ?>">
                                    <img src="<?php echo file_create_url($node->field_image['und'][$img_count]['uri']); ?>" alt="" >

                  <?php $img_count++; } ?>

        <?php endif; ?>

Put something like above snippet in your node.tpl.php
This will create links of images and their links if any. Then apply normal css/js to make it in slideshow


It's Drupal, so yes you can add an extra field to the site content type on /admin/structure/types/manage/site/fields.

Warning: you must enable first the field_ui module, as it's disabled by default in Aegir installation profile.

I started a documentation page about this: http://docs.aegirproject.org/en/3.x/extend/frontend/


Alter a view so it adds a custom field ->textbox

When you create the content type does it reference who test scores they are? Without any reference's to who's score it is this would be hard. You could use entities I believe as you can create relationships you need then you could use views to display it.

http://drupal.org/node/1261744


Ajax form submission error when using use-ajax-submit

The following dependencies need to be added to the library attached to the form in order to use use-ajax-submit.

my_module.libraries.yml

my_module.my_library:
  dependencies:
    - core/drupal.ajax
    - core/jquery.form

The library needs to be attached to the form:

$form['#attached']['library'][] = 'my_module/my_module.my_library';


Why does in Drupal 8 there are two different namespaces for test cases?

They're just different kinds of tests, with different requirements/dependencies, and so they're split up.

From PHPUnit file structure, namespace, and required metadata:

  File structure and namespace

  There's a special relationship between the location of test files within the file structure, the namespace they use, and the class which they extend.

  Drupal Unit Test Suites: Auto-detected Tests

  Drupal 8 uses a number of test suites to allow for choosing between different kinds of tests to run.

  Drupal 8 has the following test suites:

  Simpletest: Legacy tests based on the Drupal version of the Simpletest framework.
  Unit: PHPUnit-based tests with minimal dependencies.
  Kernel: PHPUnit-based tests with a bootstrapped kernel, and a minimal number of extensions enabled.
  Functional: PHPUnit-based tests with a booted Drupal instance.
  FunctionalJavascript: PHPUnit-based tests which use PhantomJS to perform tests of Javascript functionality.

  Drupal's test system can discover these different test suites for core, core extensions, and contrib extensions, as long as the tests are placed within the proper directories so they can be discovered as belonging to one of the test suites listed above.

  Simpletest-based tests must be placed in an extension, within that extension's src/Tests directory. They will have a namespace of \Drupal\$extension\Tests.

  PHPUnit-based: Generally, the other suites must be within a tests/src/$suite_type/ directory. These tests will have a namespace of \Drupal\Tests\$extension\$suite_type.

  Traits: The third class is traits. It is possible to write a trait which will be discovered and can be used by the various different test types. Each test suite will discover the trait if it is placed in the tests/src/Traits directory, and the trait will have a namespace of \Drupal\Tests\$extension\Traits.

  Note that the class names must END with the word Test. The test methods within the class must START with the word test.

Simpletest Class, File, and Namespace structure also provides a bit more insight.


missing cet_enable field in product type settings (Commerce Event Ticket)

Could this be related to some type of permission that is still missing? Also, consider adding a LINK in your question to point to the issue you created (it may help to further enhance this question also).

Did you receive any eMails by using this module?


By allowing only if the value is set the error disappeared.

if (isset($li[$li_id]->field_wa_thick['und']) {
  $wt = $li[$li_id]->field_wa_thick['und'][0]['value'];
}

Also applying the isset if the value is used elsewhere.


If you select the 'forms' tag and select its mini menu option 'info', you will see a link to the Drupal pages for the form API and a great basic explanation on how it is used.
You should not use PHP in the view. PHP in content of any sort presents a security risk. The best place to do this is in a custom module.
The form API provides documentation on both.
$form_state is used as central storage for all information about the form. Any part of the $form_state array can be read and written to by any function at any time.


How to get the File Description programmatically?

The description is stored on the file field, not on the file entity. To access it, use $node->yourfilefield->description.


In the Counter module the Visitors "This Year" count is decreasing. How can I get it to increase instead?

I've checked the module and i can confirm that the behaviour of the module is like previously i explained in comments. So, it is not a problem related to a module. It's a problem related to marketing analysis. Probably the "Visits" and "Hits" are absolute values ( they are always increasing ). On the other hand, the "This Year" value is a calculated value for 365 last days.

At this time last year, you had lots of visitors.


How to locate the Entry Points of a Drupal 8 Core module?

Entry points will equate to routes in Drupal.

Modules will normally define their routes in a YML file named MODULE_NAME.routing.yml, but routes can be defined programmatically as well, check out this article from Acquia about routes:
 https://dev.acquia.com/blog/coding-drupal-8/defining-and-altering-routes-in-drupal-8/22/03/2016/9891

Also the 'routing' table in the database lists all the paths and their corresponding routes (I believe all).  Note the use of '%' and '{some_value}' to indicate dynamic route values.

Hope that gets you started.


No results behavior not working when using contextual filter with content id from url

Assuming you are working with the default Article content type of Drupal 7.x
Your Content Type

You should add something similar to this in your NO RESULT BEHAVIOUR of your IMAGE field in your VIEWS

I'm attaching the exported VIEWS code, you can check that, create 2 dummy ARTICLES one with IMAGE and another without an IMAGE but remember to store a no-result.png image in your sites/default/files/styles/thumbnail/public
Views Code
$view = new view();
$view->name = 'preview';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Preview';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Image View';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['empty'] = '<img src ="../sites/default/files/styles/thumbnail/public/no-result.png" />';
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => '',
  'image_link' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'preview';

Using the above VIEWS code you can access the output at http://<your-host>/preview/<nid>
Let me know if you face any issues.
Cheers!


Programmatically Change Administrative Area in AddressField

Here is an example, You need to use ajax. I think you will just need to alter the form structure a bit from what I have but the basic logic is there.

$country_list = array(0=>'USA',1=>'Canada');
$value_country = isset($form_state['values']['country']) ? $form_state['values']['country'] : key($country_list);

$form['country'] = array(
    '#type' => 'select',
    '#title' => t('Select Country'),
    '#options' =>  $country_list,
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'mymodule_ajax_callback',
        'wrapper' => 'name_replace',
        ),
 );

$form['state'] = array(
    '#type' => 'select',
    '#title' => t('Select State'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' =>  mymodule_find_states($value_country), //pass country, run query, return correct states
    '#default_value' => isset($form_state['values']['country']) ? $form_state['values']['country'] : '',
 );

Add this function make sure this function is NOT inside form_alter function

function mymodule_ajax_callback($form, $form_state) {
    return $form['state'];
}


Flood control is just for failed login attempts and some other stuff like forms being filled out.  It will not keep your bad bot from the site.

Assuming you have an Apache server, you can modify the .htaccess file in the root of your site to block specific ip with the DENY FROM {ip} directive. E.g. adding something like this to the top.

order allow,deny
deny from 255.0.0.0
deny from 123.45.6.
allow from all

If you don't have Apache / .htaccess support, the process will be different.


Referencing/relating content between content types

Take a look at the Entity Reference Module:

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field
  Four widgets:

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

  Two formatters:

  A "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.)
  A "Rendered entity" formatter, that renders the references entity using a
  configurable view mode

  Integration with Views (for both forward and
  backward references)
  Integration with Entity Metadata (and as a
  consequence with Search API and the like)
  Integration with Devel generate
  Integration with Feeds and Migrate (>= 2.3) for painless data import

That should get you started.


How to redirect all unpublished nodes of a certain type

I ended up going with the first option and using the following solution to make sure the redirects never got out of hand:

Basically when a job advert goes down it will get given a 301 redirect. Then I remove every redirect for a job advert older than 3 months.

Hopefully this will remove the worst of the 404 problem because: If Google crawls the link in the three months then it will be redirected and change its index.

If a person comes across it in the three months they'll be correctly redirected and if no-one has bothered to try it for three months then I've probably avoided the 404 problem.

The code just involved calling an extra cron job and then altering a version of the redirect_purge_inactive_redirects(); function.

function redirect_purge_job_redirects(array $types = array('redirect'), $interval = NULL) {
  //set interval in code to 3 months in seconds
  $interval = 7776000;
  $query = db_select('redirect');
  $query->addField('redirect', 'rid');
  if (!empty($types)) {
    $query->condition('type', $types);
  }
  //add in condition here to select all redirects
  //for the job adverts.
  //the path for all the job adverts begins with job
  //so I look for that.
  $query->condition('redirect', 'job'.'%', 'LIKE');
  $query->condition('access', REQUEST_TIME - $interval, '<');
  $query->addTag('redirect_purge');
  $rids = $query->execute()->fetchCol();

  if (count($rids)) {
    redirect_delete_multiple($rids);
    watchdog('redirect', format_plural(count($rids), 'Removed 1 inactive redirect from the database.', 'Removed @count inactive redirects from the database.'));
    return $rids;
  }
}


Hide form fields unless 'add node image (etc) link is clicked

Try the Conditional Fields module. It's still in -dev state for D7 but maybe it works for your case.


Pathauto unable to bulk update contents alias with AJAX error

I have just find the cause of the issue. It is just two records of node table among about 13K records has no type field value.

To solve it, using PHPMyAdmin I have filled them with the machine name of an available content type. in my case it is archieve


Yes. You can reorder any Drupal form elements by altering its #weight property. To make the auto assign element appear above the other account registration elements just adjust its weight lighter.

This can be done in hook_form_user_register_form_alter() invocation:

/**
 * Implements hook_form_ID_alter().
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Set the autoassignrole_user element 1 unit lighter than account form element
  $form['autoassignrole_user']['#weight'] = $form['account']['#weight'] - 1;
}


You can call the decrypt() function as seen in _webform_encrypt_decrypt_nested_values:

/**
 * Helper function to recursively decrypt values in a webform structure.
 */
function _webform_encrypt_decrypt_nested_values(&$element, $key = '#default_value', $restrict = array()) {
  // Determine if we are checking access.
  $access = empty($restrict) ? TRUE : user_access('view encrypted values', $restrict['account']);

  // Loop through each item and decrypt the value.
  foreach (element_children($element) as $name) {
    $component = &$element[$name];
    if (!empty($component['#webform_component']['extra']['encrypt'])) {
      if (is_array($component[$key])) {
        foreach ($component[$key] as &$value) {
          $value = $access ? decrypt($value, array('base64' => TRUE)) : t('[Value Encrypted]');
        }
      }
      else {
        $component[$key] = $access ? decrypt($component[$key], array('base64' => TRUE)) : t('[Value Encrypted]');
      }
    }

    // Recurse if the current item has children.
    _webform_encrypt_decrypt_nested_values($component, $key, $restrict);
  }
}

So in your own code you want to call something like decrypt($value, array('base64' => TRUE)) where $value is (saved) encrypted webform submission data.


As per function definition:

   /**
    * Creates an AccessResultInterface object with isForbidden() === TRUE.
    *
    * @param string|null $reason
    *   (optional) The reason why access is forbidden. Intended for developers,
    *   hence not translatable.
    *
    * @return \Drupal\Core\Access\AccessResultForbidden
    *   isForbidden() will be TRUE.
    */
   public static function forbidden($reason = NULL) {
     assert('is_string($reason) || is_null($reason)');
     return new AccessResultForbidden($reason);
   }

So the $reason is only intended for developers.


How do I change page callback for a particular menu?

In Drupal 8 You don't have hook_menu and the are changed to "Routers" now.

Drupal 8 has a new menu system, there is no hook_menu and no hook_menu_alter anymore.

If you want to alter an existing route, it is a little bit more complicated in comparison to Drupal 7.

In your module you have to create a class file at YOURMODULE/src/Routing/CLASSNAME.php that extends RouteSubscriberBase:

/**
 * @file
 * Contains \Drupal\YOURMODULE\Routing\RouteSubscriber.
 */

namespace Drupal\YOURMODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get the route you want to alter
    $route = $collection->get('system.admin_content');

    // alter the route...
  }
}

You can take the RouteSubsciber class of the node module as an example.

To let your RouteSubscriber be recognized you also have to create a YOURMODULE.services.yml file in the root of your modules directory:

services:
  node.route_subscriber:
    class: Drupal\YOURMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

To get a better insight to the new menu system I would recommend the following articles:

D7 to D8 upgrade tutorial: Convert hook_menu() and hook_menu_alter() to Drupal 8 APIs
What Happened to Hook_Menu in Drupal 8?
Edit:  the menu system has a different structure now, which has nothing to do with D7's menu system, so there is no such thing as a menu type anymore.


why Cache-tags is different if i am logged?

You don't need to render a node to bubble up its cache tag. There are other reasons, for example access checks, which heavily depend on the current user. A negative access check still could bubble up the node cache tag when the result depends on field values. So the tags of not rendered nodes could be unpublished nodes in views or menus. When you publish one of those nodes you want that the page gets refreshed to include the now published node.

Edit

You can replace the core menu block with a custom menu block, see

  Rendering menus

  Once you have created menus (that contain menu links),
  you want to render them. Drupal provides a block
  (Drupal\system\Plugin\Block\SystemMenuBlock) to do so.

  However, perhaps you have more advanced needs and you're not satisfied
  with what the menu blocks offer you. If that's the case, you'll want
  to:

  ...

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21menu.api.php/group/menu/8.8.x

By doing so you have the options to not use access checks at all, add your own version of an access check tree manipulator or use the core one and remove the cache tags from the tree access objects afterwards with AccessResult::resetCacheTags


Checkout the Commerce Affiliate module that is used with Drupal Commerce (or UC Affiliate if you're using Ubercart).


For Drupal 7 sub-domain installation is sites.php the same as 6's use of symbolic link folder?

sites.php exists so you can fake out the normal multi-site operation, like mapping 'localhost' to 'foo.mysiteroolz.com'. Ideally you wouldn't use it in a production server.

In a live-to-the-internet site, you don't want to have sites.php (unless you specifically know why you do), and you want your subdomain to resolve to the same IP and directory as the domain. Then just have a subdirectory in /sites. So:

drupal/sites/default/ will have settings.php and files for mydomain.com

drupal/sites/mondo7.mydomain.com/ will have settings.php and files for mondo7.mydomain.com.

Then in your dev setup, you'd have a sites.php file that says something like 'localhost' => 'mondo7.mydomain.com' This tells Drupal which site directory gets the attention when a request comes for localhost.

HTH.


How to dump a single table from database using drush?

You can use --tables-list option on drush command to dump specific tables.

drush sql-dump --tables-list=node,system > exportdb.sql

Above command will only make sql-dump for node and system tables.

Source


How to set up an email notification if a user gets a new role?

I suppose this is for manually promoting a user. I would try creating a rule using the Rules module for modifying the role and sending a mail to the user about his/her new role on the site.

I'm still learning how to use Rules, so I won't be able to give you a detailed recipe here, but after watching the excellent Rules screencast series at the NodeOne site, you might be able to do this quickly without making a custom module.


There is an option to add fields to comments.

From Structure -> Content Type select manage fields for the content type that needs image attached

There is a tab called "Comment Fields".

Select that, add and image field to it and that should do it. You would see an upload button in the comment.


can't change the value of ONE button (search page SEARCH button)

Did not realize the search page is structured different than a block search here is the solution that worked posting for anyone might have the same problem

function MODULE_NAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if(in_array($form_id,["search_block_form"])) {
    $form['actions']['submit']['#value'] = "Custom Search Value";
  }
  elseif(in_array($form_id,["search_form"])) {
    $form['basic']['submit']['#value'] = "Custom Search Value";
  }
}


Ok, I figured out you can directly insert html into view titles and it will work. Wrapping the different view panes in an <a> tag solved the issue.


I finally got this to work by adding on my template.php:

function YOURTHEME_quicktabs_alter($quicktabs) {
if ($quicktabs->machine_name == 'YOUR_QTABS_NAME') {
  $currYear = date('Y');
  for ($i = 0; $i <= 3 ; $i++ ) {
    $yr = ($currYear-$i);
    $quicktabs->tabs[$i]['title'] = t($yr);
  }
}

}
}


How to automatically update field values for all translated nodes

There is a Synchronize Translations module which is part of the Internationalization Module and which allows you to synchronize one (or more) fields across translations.

Once you have the module installed and enabled you can navigate to the content type in question and in the Synchronize Translations-tab check all fields you want to synchronize.

Check the Documentation here: Synchronize translations.


The issue is addressed in the thread you referenced. Not all methods for the select class return the new query object. In particular, innerJoin() returns an alias string, not the query object.

Assign your query object so you can reference it outside of the method being called:

$query = db_select('users', 'u')->extend('TableSort')
$query->innerJoin('members', 'm', 'u.uid = m.uid');
//@TODO: add ->fields() ->execute() etc...


Drush site-install working with profile_name_install_tasks and forms

Drush si command has key=valueargument.
The key is in the form [form name].[parameter name] on D7 or just [parameter name] on D6.

drush site-install standard install_configure_form.site_default_country=FR

See more: http://www.drushcommands.com/drush-6x/core/site-install