ThemeNegotiator not working for admin pages

The admin theme negotiator is tagged with a priority of -40:

user.services.yml

  theme.negotiator.admin_theme:
    class: Drupal\user\Theme\AdminNegotiator
    arguments: ['@current_user', '@config.factory', '@entity_type.manager', '@router.admin_context']
    tags:
      - { name: theme_negotiator, priority: -40 }

So you have to use at least -39, since the first negotiator returning a theme name wins and on an admin page this core service will return the admin theme.


How can I get major version updates with drush pm-update?

You can explicitly ask Drush to tell you all of the available releases for a specific project using the pm-releases command:

$ drush pm-releases mollom
------- RELEASES FOR 'MOLLOM' PROJECT -------
 Release         Date         Status
 7.x-2.x-dev     2012-Dec-19  Development
 7.x-2.3         2012-Oct-22  Supported, Recommended
 7.x-1.x-dev     2011-Dec-20  Development
 7.x-1.1         2011-Jul-09  Supported, Installed

However, what you want to do -- to have pm-update(code) automatically notify you when there is a newer major release -- is not supported.  I have opened a feature request in the Drush issue queue for you:  http://drupal.org/node/1880970

UPDATE:

Regarding kiamlaluno's comment, you can force the update using pm-download:

$ drush dl mollom-7.x-2.3
$ drush updatedb

I think that it would be more difficult to write a script to check for updates with pm-releases than it would be to enhance pm-updatecode to show this information.  If you'd like to help out, please post a patch at the issue I linked to above.


Multiple filed handlers in Views for a field

You don't. That's not possible.

But you still have options:

Define your own field handler and add support for multiple display formats using configuration options, have a look at this snippet for an example: https://gist.github.com/juampy72/5816530. The key methods to implement this are option_definition, options_form, options_submit and render.
This is more of a work-around. Copy the definition of the first field handler under different database column key, e.g. $data['history']['timestamp_as_date'] = array( .... Then implement your own filter class as before, but also override the query method in order to ensure that the timestamp column is present. Then display that as you like.

There are a lot of code examples out there.


Set a boolean (single on/off checkbox) value while creating a node

Sorry for late response, but I had the same problem few days ago. What worked for me was first of all creating the node and then setting the boolean value:

$node = Node::create([
        'type' => 'calendar_data',
        'title' => 'testing finaly 1111111111111111111111111 ',
        'field_current_month' => date('Y-m-d'),
    ]);
$node->field_date_type_value->value = true,

$node->save();

The 'inline' field setting didn't work neither for some other fields for me. But the explicit version is working very well.


List of D7 contrib modules that create and use custom tables with full Views 3 support

You should take a look at Data & Feeds or Table Wizard & Importer.


Edit the permissions of the folder it self.
The folder "default" set to 0555, set them to 0755 for editing. Don't forget to restore the default values afterwards!


Override Taxonomy Node content for different terms without using views

Change your node.tpl.php file so that it only returns the parts of the node you want, if the current path of the page being viewed is taxonomy/term. Using the Bartik node.tpl.php file as an example, and assuming you only want the title (linked to the node) to be displayed, you could do something like this:

Original ("before"):

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>

      <?php print $user_picture; ?>
      <?php print $submitted; ?>

  <?php endif; ?>

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

  <?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>

      <?php print $links; ?>

  <?php endif; ?>

  <?php print render($content['comments']); ?>

Altered ("after"):

<?php if (!$page && arg(0) == 'taxonomy' && arg(1) == 'term'): ?>
<?php
 // Note:
 // If you want to see all the values available to you at this point, uncomment
 // the next line (not safe for production environments):
 // print '
' . check_plain(print_r($node, 1)) . '
';
?>
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

<?php else: ?>

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($display_submitted): ?>

      <?php print $user_picture; ?>
      <?php print $submitted; ?>

  <?php endif; ?>

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      print render($content);
    ?>

  <?php
    // Remove the "Add new comment" link on the teaser page or if the comment
    // form is being displayed on the same page.
    if ($teaser || !empty($content['comments']['comment_form'])) {
      unset($content['links']['comment']['#links']['comment-add']);
    }
    // Only display the wrapper div if there are links.
    $links = render($content['links']);
    if ($links):
  ?>

      <?php print $links; ?>

  <?php endif; ?>

  <?php print render($content['comments']); ?>

<?php endif; ?>

Hope that helps...

:)


Saving node with a text format another user doesn't have permission for renders it inaccessible

You can't I'm afraid.

Think about it like this: When rendering the text to screen, Drupal has to decide which text format to use to filter it. This means that per field, there must only be one text format, regardless of which users have edited it.

If this wasn't the case, Drupal would have no idea which format to use to render the text. It would have to guess, which is something you don't want a computer doing!

If you want users to be able to edit textarea fields, your admins will simply have to save them in a format that those users have permissions to use. Otherwise the whole point of having different filters available for different roles is kind of lost.

But the main point is that conceptually, if different users edit the same field, with different text formats, then Drupal has no idea which one to use when outputting the field value. This is why you cannot do it.


The best solution for you is using hook_requirements .

function hook_requirements($phase){
       if ($phase =="install"){
         $requirements['php'] = array(
           'title' => 'LDAP extension',
           'value' => "LDAP",
          );
 if (function_exists('ldap_connect')) {
      $requirements['php']['description'] = 'YOU NEED TO install LADAP';
      $requirements['php']['severity'] = REQUIREMENT_ERROR;
     }
    }
return $requirements;

}

and another tricky solution (but NOT RECOMMENDED) is : Create Another module for php_ldap extension (let name it B), and on that module on hook_enable check the php_ldap extension is exists if not,  uninstall module(uninstall B module) , and  set your main module  dependent on first one(I mean Module B) . with this method you will be sure if the extension Available Module B can be installed and consequence Your main Module.

Something like  following snippet could help you to implement that

function MODULEB_enable() {
  if (!function_exists('ldap_connect')) {
        module_disable(array('MODULEB'));
       drupal_uninstall_modules(array('MODULEB'));
       drupal_set_message(t('The Ldap extension needs to be enabled.'), 'error');
  }
}


You have to add a new field on the view, which is custom link.
edit this custom link and rewrite the result to be something like

term

after that click on your jump list settings and chose the newly created field


Remove the URL aliases that don't have a node

A core bug causing this error was fixed for Drupal 8.2 and 8.3:

PathItem::delete() never runs because the path field type is a computed field in disguise

The fix for this problem, then, should simply be updating Drupal (...after having waited several months for this fix to be made and 8.2 released— but a satisfying answer now, i hope!)


Try the Date module

Install the module
Go to Configuration > Account Settings > Manage Fields tab
Add a date field of type "Date" and widget "Select list"
Hit Save
Deselect every date piece except year
Hit Save field settings.
Check Display on user registration form.
Expand More settings and values
Set starting year and ending year and default value.
Save settings

If you must use a text field, the date field gives you that option as well. You wont be able to set a start or end date, but the module will validate the date is in the proper format.


The conditional field module will do this for you. In this module when certain fields are selected, get value, ... other operations (hiding,removing,make it required,...) may happen


How to make an upsert query with two keys?

At this moment I don't know why but if I use only one key the query works as expected (using the two database keys as a key in the upsert, when I only says $query->key('route');):

$route = \Drupal::routeMatch()->getRouteName();
$uid = $this->currentUser->id();

$query = $this->connection->upsert('forcontu_database_counter')
          ->fields([
    'route' => $route,
    'uid' => $uid,
    'user_count' => 1,
    'lastcount' => time(),
  ]);
$query->key('route');
$query->execute();

If I change the uid (using a diferent user in the site) in the same route (page) Drupal insert a new record (don't make an update in the existing route) and I only use one key, in this case route.

EDIT:

This always will work because if you see the code inside the __toString() function the key property is never used:

public function __toString() {
    // Create a sanitized comment string to prepend to the query.
    $comments = $this->connection->makeComment($this->comments);

    // Default fields are always placed first for consistency.
    $insert_fields = array_merge($this->defaultFields, $this->insertFields);

    $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';

    $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
    $query .= implode(', ', $values);

    // Updating the unique / primary key is not necessary.
    unset($insert_fields[$this->key]);

    $update = [];
    foreach ($insert_fields as $field) {
      $update[] = "$field = VALUES($field)";
    }

    $query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);

    return $query;
  }

}

But always you need to set the key, if you don't set the key property you will get an exception:

protected function preExecute() {
  // Confirm that the user set the unique/primary key of the table.
  if (!$this->key) {
    throw new NoUniqueFieldException('There is no unique field specified.');
  }
...

Read more about this at: Why we need the key property in the Upsert class if it is never used?


No - a simple sha512 wouldn't be the same because its lacking the "salt" added by Drupal that prevents the "ability to use pre-hashed lists of candidate passwords" against your database (among other things). Its a security improvement over D5/D6 where a simple md5 update query could reset a user's password.

You might get more mileage out of connecting to the password-hash.sh script (in the scripts folder of your Drupal installation) in your VB script using whatever the equivalent to PHP exec() is in VB..


How do I strip spaces from a Twig variable?

You can use "replace" - much like you would in PHP - and replace the space with no space

{{ anchor_id|replace({' ': ''})

More info: https://twig.symfony.com/doc/3.x/filters/replace.html


TWIG for loop returning first value only

It is displaying the same object 5 times because node.field_featured_resources[0] is referenced 5 times. Use the iterator variable object or use node.field_featured_resources[key] instead.

It also may be better to do this without all of the logic in the template. Off of the top of my head,

In template preprocess for the field (PHP), set the class in Attribute.
In module layer (PHP), add a Field Formatter.

Or if Field Formatter are already available, configure Manage Display to display the fields in the desired format.

In template (Twig), print out the field value in the span directly.

Here's some Twig:

{% for key, object in featured_resource_nodes %}

  {% if object.entity.field_resource_type.value == 'video' %}
    {# @todo: Configure Field Display for On-Demand Webinar instead... #}

      {# @todo: consider object.entity.title instead of .value #}

{{ object.entity.title.value }}

  {% else %}
    {# @todo: Configure Field Display for Resource File instead... #}

      {# @todo: consider object.entity.title instead of .value #}

{{ object.entity.title.value }}

  {% endif %}
{% endfor %}


I think you should make use of proper permissions. If you are using Drupal7 , login in as admin and click on the people->permissions->content type-> add/edit/delete own contents. Once this option is enable and saved the user can modify only his content. I am not clear with your question, it would be glad if you make your question more precise.


How to make user.html.twig template for two different pages (users)?

Platon, you appear to be mixing up the template for the user itself (user.html.twig) and the overall page template (page.html.twig).

If you want to override the user template then you need to implement hook_theme_suggestions_HOOK where "HOOK" is "user" which is the theme hook you are overriding.

Here is an example of what that code would look like if you were using Bartik (but of course in practice you should be using your own subtheme rather than hacking core):

function bartik_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  $suggestions[] =  'user__' . $variables['elements']['#user']->id();
  return $suggestions;
}


Have yet to test it out. I do know that domain specific code CAN be better in comparison to a generalized tool like mod_pagespeed; but I would imagine it would take a lot of effort to beat mod_pagespeed. mod_pagespeed should bring an improvement in comparison to drupal's core aggregation; you will get CSS & JS Compression among some other nice things.

In Drupal land we are working on improving the page load time. Here are some projects for that.

http://drupal.org/project/wpo
http://drupal.org/project/bundlecache
http://drupal.org/project/advagg
http://drupal.org/project/css_emimage
http://drupal.org/project/imageapi_optimize
http://drupal.org/project/closure_compiler
http://drupal.org/project/cdn

Long story short: Use mod_pagespeed today; checkout some of these projects in the future.


print() is a command that doesn't work with arrays. print_r() will print out arrays for debugging but what you want is print render($content). Drupal uses large render arrays to output content, and they cannot be printed directly.


Can't update nodes / node unpublishes itself

This seems to be a common problem when exceeding the max_input_vars on saving nodes. Which might seem your problem regarding the 160+ images on the node.
First, check your server logs for anything related to this error.
Then update php.ini (check for max_input_vars)  to an amount that suits your needs.


Please check:

Folder and file names if they match the directory structure in the warning message
/var/www/html/recruiter/profiles/recruiter/themes/omega/omega/includes/scripts.inc if the selectivizer and respond directory is included or correct
The permissions of the folder and file


Why isn't the custom validation handler fired in hook_form_alter()?

Validate and submit handlers can be placed on the form level or on specific buttons. If they are defined on a button, only those will be executed; it only falls back to the top-level if nothing is defined on the pressed button.

The node form, like all entity forms has the callbacks defined on the button, which is complicated by the fact that there are multiple buttons (save as published, save as unpublished and so on). You must define your validate callback on all of them.

Also, for validation of an entity, you should instead use validation constrains on the fields or the entity.


Generate installed modules into a composer.json for existing site: I need to manage via Composer, not via UI

Composer Generate is a Drush extension. It can be used either with Drupal 7 or Drupal 8. Considering that the latest release available on drupal.org is dated Febrary 25, 2016, it's probable it is not compatible with the Drush version you would be use on your site.

The project page for Composer Generate suggests using the Composerize module, which is available for Drupal 8.

  This module can generate a composer.json from your installed Drupal code base, which can be used to regenerate that code base by running composer install.

Be careful of the warning reported in the project page.

  This module is still in development. It supports very basic Drupal 8 setups, but there are many necessary features it still lacks (e.g., support for patches, JavaScript libraries, distributions, etc). We're working on all that stuff, but this module is definitely not ready for prime time.

The module is supported by Acquia, and the development version has been updated on March 20, 2018.

Alternatively, as the project page suggests, you could use Composerize Drupal, a Composer plugin for converting a non-Composer-managed Drupal site to a Composer-managed Drupal site.


Filter unpublished nodes, even for Admin

Sound like you just want to switch the filter you are using from

Content: Published or admin
Filters out unpublished content if the current user cannot view it.

to

Content: Published
Whether or not the content is published.


How to broadcast a message to several Drupal web sites?

There are a number of ways to accomplish this, but I wouldn't recommend using Feeds for system wide alerts because of issues with the way Feeds locally caches the source RSS based on how often or infrequently it changes.  This also requires maintaining redundant content types, views, and nodes across several sites.  While this could be done with a Feature, there are much simpler ways to do this.

One extremely simple option is to configure each site to with a block that embeds an iframe from a centralized messaging site that isn't even running Drupal.  Update the HTML of the message and it will be shown everywhere. When you are done, update the HTML to no longer display the message. Of course this will require a layout that allows the space for the message to always be there, but empty when there is no message.  Not ideal.

You could accomplish the same thing without the empty space in the layout by including an external javascript that inserts the message when the .js on a main site is updated, but that is getting less simple and could be impacted by each site's javascript aggregation and caching issues.  Not ideal.

For a solution that is only slightly more complicated, but far more efficient and doesn't require any scripting knowledge, implement https://www.drupal.org/project/sharedblocks.  This module allows you to define a View driven block on a the site used to generate the messages as shared and subscribe to that block on every site you'd like to display the messages.  This has the added bonus of being able to configure the messages as a content type that are archived so you have a system history as well.  Just add either an expiration time or a checkbox to limit the message's active state and filter the View so it returns nothing if there is no active message.  The result of an empty block from the parent site on the child sites is the block isn't displayed at all so no need to deal with the space an empty iframe creates.  The cache and cron settings for Shared Block are configurable.

UPDATE: Just reviewed the https://www.drupal.org/sandbox/cecrs/2340909 to be promoted to a full project.  The module is currently limited to a single alert, but the alert is displayed using a block that can be shared across multiple sites.  I've opened a feature request to change that to define an Alert entity, even without that Site Alert + Shared Block is a great solution.


You need to write some custom code to lowercase the query string parameters before the webform is built and displayed.

Another hack would be to pass the query string parameter using a token [current-page:query:collectionId]


How to re-run javascript core code for content loaded with jQuery's ajax()?

Looks like Drupal.attachBehaviors(jQuery("#content")[0]); is working. Some issues still exist though. Like the absence of relevant behaviors when loading from different page.

Taken from https://drupal.stackexchange.com/a/3193/7177


How do I Import users in the database without re-hashing the password

Do this :

<?php
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$old_hash = md5('password');
$hash_count_log2 = 11;

$new_hash = user_hash_password($old_hash, $hash_count_log2);

if ($new_hash) {
  // Indicate an updated password.
  $new_hash  = 'U' . $new_hash;
}
?>

or you may check LINK1 or LINK2

Or you can directly import the data from one table to another :

INSERT INTO NewTable (ID, Name, Password)
  SELECT ID, Name, md5(Password) AS Password
  FROM OldTable
  WHERE ID BETWEEN 100 to 300

Check LINK once.


Search keyword with selectable exposed filters

I think this is the module that you are looking for....

Better Exposed Filters

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

  Views Filters is a powerful tool to refine the results returned by a
  given view. When you expose a filter, you allow the user to interact
  with the view making it easy to build a customized, advanced search.
  For example, exposing the node type field as a filter lets your site
  visitor limit their search queries to just blog entries. Better
  Exposed Filters gives you greater control over the rendering of
  exposed filters.

  Why use this module? Because it provides a better user experience than
  the default option. Try telling a client that they should click on an
  option, then scroll to the next option and ctrl+click on it. Don't
  just click 'cause you'll lose your first selection. Oh, and ctrl+click
  again to unselect an option... Yeah, not user friendly.


As you can see from your Krumo output (plus the very descriptive error message), data is an object, not an array. I'd imagine $display->context['panelizer'] is also an object but it's hard to say as you haven't mentioned in your question how that's populated. You should use either

$display->context['panelizer']['data']->field_centerpage_layout[0]['value']

or

$display->context['panelizer']->data->field_centerpage_layout[0]['value']

Probably the second one.


You should use CSS to style your content. This happens in the theme of your site. The handbook on Drupal.org has a lot of documentation on how this is done.


How can I use node_load with a module created page that requires an argument?

The code executed from Drupal, in index.php, contains the following code.

$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

menu_execute_active_handler() accepts an argument: the path being shown. If that argument is not passed to the function, then menu_get_item(), the function called by menu_execute_active_handler() uses the content of $_GET['q'].
In your case, you would pass to the path you are interested to. Your function should use code similar to the following one:

function mymodule_get_page($path = NULL) {
  $return = menu_execute_active_handler($path);

  // Menu status constants are integers; page content is a string.
  if (is_int($return)) {
    return $return;
  }

  if (isset($return)) {
    return theme('page', $return);
  }

  return −1;
}

The calling function would need to check the returned value: If it is a string, then it the what returned from theme('page'); if it −1, then the menu callback didn't return any value (but could have printed the page content; if it is an integer different than −1, then it's a Drupal error code, i.e. the one reporting the site is off-line, the user is trying to access a page without to have any permission, or the user is trying to access a non existing page.

The only "problem" with this code is that sometimes a menu callback doesn't return any content, but it prints the content directly; this is normally done for content that doesn't need to appear together the rest of the page output Drupal normally adds (e.g. the content for the blocks associated to a page), such as when a module returns XML content that should not mixed up with the HTML output generated from Drupal.
In this case, the function should intercept the output directly printed, with ob_start() and ob_get_flush().

function mymodule_get_page($path = NULL) {
  ob_start();
  $return = menu_execute_active_handler($path);
  $output = ob_get_flush();

  // Menu status constants are integers; page content is a string.
  if (is_int($return)) {
    return $return;
  }

  if (isset($return)) {
    return theme('page', $return);
  }

  return $output;
}


D7 errors given when authenticated user changes password but pwd still changes

Something doesn't add up with what the information you have given. When a user edits their own profile, the default is to simply reload the same page.

You said that you have added a link on their profile (view) page, that points to the user edit page.

I'm guessing that the following is part of the link you've added:

destination=admin/people

If there is, then you need to remove this. Anytime there is a destination=[SOMEPATH] in the URL and a form is submitted, it will redirect the user to the path given in the URL.


Node is flagged, node author comes back to the site, how to show how many new flags since last visit?

To answer your posted question (title), you'll need to extend functionality.

By default, the core comment module & flag module have no default mechanism to store comment/flag view history. You would need to do something like:

Build something like the Drupal core history module that tracks a user's comment/flag views
Build a simple aggregate comment/flag query based on a user's last login/access time
...or maybe find a module that offers this functionality (not sure it exists and module recommendations are off topic here)


How can I change the default system message shown on form submission

That message comes from entityform_edit_form_submit

You could try setting the translatable text string to an empty string in settings.php

$conf['locale_custom_strings_en'][''] = array(
  'The submission has been saved' => ''
);

Or else look into another way to alter drupal_set_message text.


How can I change the "Edit" tab name to something more meaningful?

Use hook_menu_local_tasks_alter see the docs. You can get a dynamic title combining tokens and the translation API.


You could probably do that with Views, clone your Views into three Block Displays, one for each prize (1st, 2nd, 3rd).

Limit the Pager to show only one result, but for 2nd and 3rd set the Offset value to 1 and 2 respectively.

Use Contextual filters to pull node info into the View (node that the Block will be displayed on, basically all food item nodes). Set the Contextual filter settings to Hide View if there's nothing to see, in other places possibly as well.

Then display all 3 Blocks on food item nodes. If there's a "hit" for any prizes the relevant Block will be displayed on that node. If not, then the hiding should take care of it.

I don't think there's a contextual filter for Views counter, that goes a bit reverse, context from Views. It might be useful here, but alas no go.

All that said, depending on your project structure, there are probably better ways of solving this. Flag and Rules modules come to mind. You could create 3 flags, and use Rules to programmatically assign flags based on criteria (they wouldn't be flags that users use).


How do i specify a style for a single exposed filter?

Not sure if you need the template for other reasons, but you can style it directly with CSS, using the ID.  See screenshot.  I happen to be using Better Exposed Filters module, which provides some nice extras controls.


The Workbench module provides you a customizable editorial workflow. Here is a quote about it (from the module's project page):

... provides overall improvements for managing content that Drupal does not provide out of the box. Workbench gives us three important solutions:

a unified and simplified user interface for users who ONLY have to work with content. This decreases training and support time.
the ability to control who has access to edit any content based on an organization's structure not the web site structure
a customizable editorial workflow that integrates with the access control feature described above or works independently on its own

These features benefit the end users as well as Drupal Site Administrators and Technical Support.


The same function can be used to change the type of the field.

Suppose you are the following field defined for the "foo" schema.

$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

You can change its type to "serial" using the following code:

db_drop_primary_key($ret, 'foo');
db_change_field($ret, 'foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar')));

The call to db_drop_primary_key() is necessary because the field is a primary key; for compatibility with any database engine, it is suggested to first remove the primary keys, the indexes, and the unique keys before to edit them.

If in the call to db_change_field(), the third and the fourth parameters contain the same value, then you are not changing the field name.

The documentation for the function contains the following text:

  Change a field definition.

  IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.

To notice that the first line doesn't say "change a field name"; it says "change a field definition," and the field name is included in the field definition.


Run KernelEvents::REQUEST event before hook_node_access?

OK, after a bit more digging, I found the solution.

The "weight" param for ['onKernelRequest', 1] is sort DESC, so the higher weight number will run first.

Adjusting the event listener with weight 1000 as follows means it runs before the hook_node_access invoking listener

  /**
   * The subscribed events.
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 1000];
    return $events;
  }


Check if current node meets conditions, then alter a block's contents?

You can check the content type of current node via preprocessing functions in your theme, but there might be another (simpler) way to do what you want: Drupal adds various information about the current page in the body classes, so you have more options for theming.

To select a specific menu link on all nodes of blog content type you can use the following CSS class: body.node-type-blog and a unique menu link ID (#menu-1000-1).

Add that line to the place where you define the active state of menu items. In your case this will be (in your superfish CSS file):

body.node-type-blog #menu-1000-1 a,
a.sf-depth-1.active, .active-trail a.sf-depth-1 {

Another quick solution would be using jQuery:

if ($("body").hasClass("node-type-blog")) {
  $("#menu-1000-1").addClass("active-trail");
}

Check also Context module for more complex use cases where you need to define a section on your website and apply certain theming/functional changes.


Why (or how) order number increases in Drupal Commerce

If you are certain there are no other users that have access to the order process, it might be caused by abandoned carts or failing payments.

Best is to have a look at example.com/admin/commerce/orders. It should give you a full list of all orders and the states they are in. Like I said if these were abandoned carts or half completed payments, orders might remain in a certain state, in which they are invisible in some other UI pages.

To answer your question. The Drupal Commerce order id is an auto increment field just as any other ID in Drupal, and it should increase with your auto increment value (mostly 1, though I sometimes have heard 5 as well).


Using a different administration theme according to the role

The ThemeKey module lets you set the theme using many different tests. While it doesn't specifically set admin theme in the usual way, it will certainly let you set a theme for a role and a path, achieving the same result. Some more details about this module (from its project page):

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules


Using multiple taxonomy vocabularies for views filters

In the "Advanced" section of your view settings, select Yes for the "Exposed form in block" setting.

Then there will be a block available for your view, which you can assign using drupal core blocks, context, panels, etc.


Did you set a chinese alias for your view page ?
Eg.: your view has an alias set to "my-listing" for the "EN" language.
=> Try to set a chinese alias corresponding to "my-listing" alias, but for chinese...


Joining Taxonomies in an Ubercart Views into a single Field Group (D6)

The solution was adding "Term" as a field.

Then grouping terms by the field "Term" and not "All Taxonomy Terms"


Modifying views exposed filter query string

Came up with a solution using hook_views_pre_render combined with a JS history.replacestate. More of a workaround, but it does the job. Would still like to find a way to modify the view object or a PHP hook though.

Here's a stripped down version of the php hook implementation:

function mymodule_views_pre_render(&$view) {
  if ($view->name == "myviewname") {
    $path_settings = array("mymodule" => array('query_params' => array()));
    foreach ($_GET as $key => $val){
      if (array_key_exists($key, $view->exposed_input)) {
        $path_settings['mymodule']['query_params'][$key] = $view->exposed_input[$key];
      }
    }
    drupal_add_js($path_settings, 'setting');
  }
}

Then in the module's js attached behaviors:

function tidyViewsQueryString() {
  currentLocation = window.location.href;
  for (var key in Drupal.settings.mymodule.query_params) {
    if (Drupal.settings.mymodule.query_params.hasOwnProperty(key)) {
      currentLocation = updateUrlParameter(currentLocation, key, Drupal.settings.mymodule.query_params[key])
    }
  }
  if (currentLocation != window.location.href){
    window.history.replaceState(null, document.title, currentLocation);
  }
}

//From https://gist.github.com/niyazpk/f8ac616f181f6042d1e0
function updateUrlParameter(uri, key, value) {
    // remove the hash part before operating on the uri
    var i = uri.indexOf('#');
    var hash = i === -1 ? ''  : uri.substr(i);
         uri = i === -1 ? uri : uri.substr(0, i);

    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        if (value.length > 0)
          uri = uri.replace(re, '$1' + key + "=" + value + '$2');
        else
          uri = uri.replace(re, '$1' + '$2')
    } else {
        uri = uri + separator + key + "=" + value;
    }
    return uri + hash;  // finally append the hash as well
}


Okay, here is what finally worked: wrap every individual field in {% spaceless %} (not just the whole block) and use render and trim together.  Trim alone makes the variable disappear. Here's my markup:

<p>
  {% spaceless %}{{ content.field_story_program_name|render|trim }}{% endspaceless %},
  {% spaceless %}{{ content.field_story_relationship|render|trim }}{% endspaceless %},
  {% spaceless %}{{ content.field_story_city|render|trim }}{% endspaceless %},
  {{ content.field_story_state }}
</p>

Extra thanks to @Cyclonecode for giving me a variety of tricks to try.


Open Layers map not showing pointers drupal7

I had the same problem when I used a non-default PIN image, the URL it then used was incorrect, it included '?q', so the pin image didnt display. This was using openlayers-7.x-2.0-beta1, and when I applied the openlayers-fix-marker-lang-path-1404912-3.patch (http://drupal.org/node/1404912) it was fixed and worked for me. Hope this helps.


unless you want to add it to a theme setting so that it can be adjusted by UI, the simplest way is probably to override page--front.tpl.php in your theme template directory, and manually add the html to create the background.

For more info on page template naming, see here.


Render image field from node in page.html.twig

I would say that the Twig-ish way is to create a custom filter. The Drupal-ish way is to use a hook_preprocessor. The general idea of the MVC rewrite is to keep logic out of the templates. I couldn't see how to add Twig filters in Drupal 8 (anyone?) so I'll go with preprocessor.

Drupal 8 preprocessor

In your theme's template.php:

function mytheme_preprocess_page(&$variables) {
  if ( $variables['node'] ) {
    $node = $variables['node'];
    // Optionally limit by bundle type. How do you get a bundle in D8?
    // if ( $bundle != 'blog' ) return;
    // Get your image URI.
    $header_image = $node->get('headerimage')->value;
    // Just guessing here: not sure what to do but it may involve styles.
    $header_uri = $header_image->getFileUri();
    // Override the variable that normally stores the header image.
    // Not sure what that would be. Look in page.html.twig
    $variables['headerimage'] = $header_uri;
  }
}


perhaps the Profile module create a profile per store and then show the right store profile fields on the registration page, if needed to work with your logic you could place specific stores on specific registration paths with Profile2 Registration Path.

EDIT

  What is the best way to fix this? ... big changes like this aren't possible ...

You asked a problem, I offered a solution. My opinion on the best way to fix your problem is to do some re-engineering of your site. If you disagree that's fine -- best of luck on finding a solution to your problem.

Modules such as views bulk operations, Rules, Node Convert are examples of modules which exist to make sweeping changes of a website feasible (although not without coordination on your behalf). What you say isn't possible -- I say is merely difficult.


Undefined index: method in drupal_prepare_form()

I hope, this can be useful, to you

http://drupal.org/node/1024298

Probably, there is new patch introduced, please go through the blog above.


You just wanted to add attribute file_directory inside the settings array

  'settings' => array(
    'file_directory' => 'myModule/images',
    ),

Here is other attributes that might be added:

  'settings' => array(
    'file_extensions' => 'png jpg jpeg',
    'file_directory' => '',
    'max_filesize' => '20 MB',
    'alt_field' => 1,
    'title_field' => 1,
    'max_resolution' => '300x200',
    'min_resolution' => '200x125',
    'default_image' => 0,
  ),


Core Search Module in Drupal 7.14 and Hidden Fields

This behavior is the correct behavior for Drupal search out of the box. The default search module only indexes fields that are not hidden in the default display view mode as Clive suggested on 8/10. This prevents anonymous users from searching and returning results hidden from their view, yet exposed via search. The exact mechanics of it vary in application from D6 to D7 but both use a concept of search index version of the node which is used to create the indexes in the database.  You can alter what the search indexes by modifying this view of the node.

In D6 you would be able to get around this by altering the node_api for the search index as shown here: http://drupalib.interoperating.info/node/246.

In D7 you can choose to enable fields to be indexed that are normally hidden in the default view.  Edit the content type and go to the manage display tab of that edit screen. Below the fields portion of that edit screen is a collapsed portion of the page for custom display settings.  Open this section and select the Search Index view mode. This will now allow you to alter the fields used to index the node.  Keep in mind the relevant results portion of the node will be blank in search results unless you also alter the search result view mode.  In this way you can have different results indexed than the visible fields in other node view modes.

You may also choose to implement the search api module, or make this field visible to the world in your default view mode and handle obscuring it through css or the theme layer.


404 page not found error even though the page exists

I finally resolved this after a lot of hair-pulling and gnashing of teeth by adding a URL alias from node/133 to node/1. Google Webtools now validates, and do does w3 link validator.

I discovered the solution by looking in the error logs:
 - admin/reports/page-not-found

I noticed that the specific page throwing the error was node/1 . Neither google Webmaster Tools, nor the validator helped as they reported only the 404 on the main domain name.


Change the e-mail value during user registration ?  form_set_value()

If you need to set the value for the form field used to contain the email address, then you should use code similar to the following one:

function _ta_module_user_validate(&$form, &$form_state) {
  if (!empty($form_state['values']['mail_first']) && !empty($form_state['values']['mail_last'])) {
    form_set_value($form['account']['mail'], $form_state['values']['mail_first'] . '@' . $form_state['values']['mail_last'], $form_state);
  }
}

As an example of how form_set_value() is used, see system_site_information_settings_validate(), which contains the following code:

// Check for empty front page path.
if (empty($form_state['values']['site_frontpage'])) {
  // Set to default "node".
  form_set_value($form['front_page']['site_frontpage'], 'node', $form_state);
}
else {
  // Get the normal path of the front page.
  form_set_value($form['front_page']['site_frontpage'], drupal_get_normal_path($form_state['values']['site_frontpage']), $form_state);
}


how to pass param to js for custom page in drupal 8 ?

You only see the variable in the preprocess hook of the custom template hook_preprocess_test_template(). But you don't need a preprocess hook at all, because you can attach the drupal settings in the controller directly:

return [
  '#theme' => 'test_template',
  '#attached' => [
    'drupalSettings' => [
      'test' => [
        'data' => 'test1',
      ],
    ],
  ],
];


Change the default value of a checkbox element

This code find the checkboxes in the 'submitted' element and check it by default.
If you make a screenshot of dsm($element['submitted']) message I can check if this code is correct ^^

function module_form_webform_client_form_31_after_build($element, &$form_state) {
  foreach ($element['submitted'] as $key => &$value) {
    if ( $value['#type'] == 'checkbox' ) {
      $element['submitted'][$key][1]['#checked'] = TRUE;
    }
  }
  return $element;
}


how to theme select box drupal for css framework

You need to override theme_select(), which you can do in your theme's template.php file:

function MYTHEME_select($vars) {
  // Your code to produce the markup you need. You can find all pertinent data in $vars.
  // The original form element is at $vars['element'], so the options array is at
  // $vars['element']['#options'].
}


Output different menus based on site section (URL)

You should be able to use standard path based visibility conditions.

Just put both menu blocks into the same region, and configure each to only be shown on paths like /project-a/* and the other on /project-b/* and so on.


This is the best tutorial I'm aware of: http://www.istos.it/blog/mapping/openlayers-and-addressfieldis


How to properly attach Google Maps Api to Drupal behaviors in Drupal 7?

As you've figured out, your problem is one of closures. In the code that is not working, you have initMap() enclosed in the anonymous function (function($){}(jQuery)). This means it's not part of the global scope, and therefore cannot be called from the global scope.

The solution to this is to set your function to be available globally. But of course, you don't want namespace collisions, which is the whole point of wrapping code in an anonymous function in the first place.

There is a happy medium here. You create a global variable, and add your callback to that from within your anonymous function:

// Initialize your global object. Set the value to itself (if it exists)
// or an empty object otherwise.
var GoogleMaps = GoogleMaps || {};

// Start your anonymous function.
(function($, Drupal, GoogleMaps) {
  Drupal.behaviors.someKey = {
    attach:function () {
      GoogleMaps.initMap = function () {
        // Initialize your map here
      };
    }
  };
})(jQuery, Drupal, GoogleMaps);

Use &callback=GoogleMaps.initMap in google maps api script embed.

You can also initialize your map from any other scripts using GoogleMaps.initMap()


Implementing different user registration

I would argue that you only need one type of user, but want multiple types of profiles. It sounds like you are looking for the profile module. From the module description:

  Why use profiles instead of user account fields?

  With profile, user account settings and user profiles are conceptually
  different things, e.g. with the “Profile” module enabled users get two
  separate menu links “My account” and “My profile”.
  Profile allows for
  creating multiple profile types, which may be assigned to roles via
  permissions (e.g. a general profile + a customer profile)
  Profile supports private profile fields, which are only shown to the user owning the profile and to administrators.

It also supports multiple registration forms to allow users to register and create their profile in one form.

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


Drupal 8 Installation Symphony routing error

Clearing cache at config/development/performance worked for me.


Delete old files from server when content is updated

This is already discussed topic.
I found some source.

Drupal Forum and Original Source

After that I would create a cron job (Implementing hook_cron). And insert this snippet.

I hope it works out for you.

Alternatively, if you dont want this action to happen once per day, you can insert it in hook_submit, or hook_update. But I would go for the first method.

Do it once per day/week/whatever time period you like.


How can I create a view to display a secondary tab on a node?

Try adding a View page with path

node/%/view/secondary-task

Make it a "Default task" or "Default menu tab" in the View menu settings.


How to grant User Points equal to the price of a Commerce Product?

At first I tried to answer your question using rules and userpoints module, but I saw that while adding Grant points to a user as action there is no such data selector for selecting the user who has created the product. I found the data selector for selecting the user who is the owner of order, but that is not your requirement. (That is why I clarified this in comments).

I found a module solution to your question. The module uses hook_commerce_checkout_complete(). From the hook page:

  Allows modules to perform business logic when an order completes
  checkout.

  This hook coincides with the "Customer completes checkout" event. Only
  business logic should be performed when this is invoked, such as
  updating the order status, assigning the order to a user account, or
  sending notification e-mails. Interaction with the user should instead
  occur through checkout panes on the checkout completion page.

This is the coding of the module I designed:

YOURMODULE.info file:

name = YOURMODULE
description = Module description
dependencies[] = commerce
dependencies[] = commerce_cart
dependencies[] = commerce_checkout
dependencies[] = userpoints
core = 7.x

UPDATE
As suggested by Clive, I have changed the module file so that this custom module will also work with multilingual sites.

YOURMODULE.module file:

/**
 * Implements hook_commerce_checkout_complete().
 */
function YOURMODULE_commerce_checkout_complete($order) {
  // Iterate through every commerce line item added in product.
  foreach (field_get_items('commerce_order', $order, 'commerce_line_items') as $line_item_id) {

    // Load commerce line item by line item id.
    $line_item = commerce_line_item_load($line_item_id['line_item_id']);

    // We do not want to include shipping cost in userpoints.
    if ($line_item->type != 'shipping') {
      // Load commerce product by product id.
      $product = commerce_product_load(field_get_items('commerce_line_item', $line_item, 'commerce_product')[0]['product_id']);

      // Create parameters.
      $params = array(
        'uid' => $product->uid,
        'points' => commerce_currency_amount_to_decimal(field_get_items('commerce_line_item', $line_item, 'commerce_total')[0]['amount'], field_get_items('commerce_line_item', $line_item, 'commerce_total')[0]['currency_code']),
      );

      // Grant userpoints programmatically.
      userpoints_userpointsapi($params);
    }
  }
}

Reference links:

userpoints_userpointsapi($params)

commerce_checkout API

commerce_line_item_load($line_item_id)

commerce_product_load($product_id)

Userpoints: deduct points programmatically

commerce_currency_amount_to_decimal()


Just for anyone who is looking to implement something similar, i done this using a http redirect to an authentication page, passing and authenticated using the token generated from drupal_get_token() (important not to use the session id).

The important steps to follow are to override the GLOBAL $user with the newly generated session user details and then regenerate the session using drupal_session_regenerate().


How to add a text Autocomplete Widget programmatically

Ok, so if you're trying to do it through hook_form_alter, you have to read the documentation on altering CCK fields.

The short version: the CCK fields are processed after the form is built. If you want to change anything in them, you have to add a callback to $form['#after_build'] (but do not replace the array, just add to it). Then implement the function, change values in $form and return the $form.


Redirect Module doesn't redirect from node/{nid} to alias

LEL - it's so stupid, I have to clarify this. The redirect module works without any problem. Everything's just like I wanted it. Maybe it's pointed out anywhere, but I didn't read it.

When the page is set to maintenance mode, it doesn't work. I have some dummy-users that can bypass the "maintenance-page" and use the site. While the site is in maintenance mode, the node/IDs are accessible. When I turned off maintenance mode, the module was redirecting...


How to add active-trail class to a links in a view?

One solution is to add an invisible PHP-field to a view (let the field identifier will be php).

Set a setup code to

$static = module_exists('crumbs') ? crumbs_get_trail() : menu_get_active_trail();

Set a value code to

$href = 'taxonomy/term/' . $data->tid;
foreach ($static as $item) {
  if ($item['href'] === $href) {
    return 'active-trail';
  }
}

And at last add a custom CSS class to a link field with token [php]


How do you call ubercart's shopping cart block?

I was able to render the code using the following;

<?php
  $block = block_load('uc_cart', 'cart');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>


image in newsletter does not apply image style (defaults to original size)

Disclaimer: I've not personally tested this in detail...

To apply specific formatting to an image token (thus applying an image style to the URL) I think you'll have to define a "token" view mode for relevant node content type. Once this view mode is setup you should be able to configure display settings on your field_image field (within this view mode) which should used when the token is rendered.

Some instructions on that are available here.

To get full field token support, and therefore this feature, I think you have enable the actual token module. It looks like core's token support does not fully cover field tokens in this way.

It may also be worth looking into the imagecache_token module. If I'm not mistaken it would allow you to declare an image style on your token directly via chaining, something like [node:field_image:style_name]. However, that module is not available as a stable release yet, and it's compatibility with field tokens is not totally clear.


Where does Drupal 7 clear my custom set cookies and how do I stop this?

Please find more about setting cookies using php setcookie function.

As explained in above link, please look into third and fourth params in above function

Path

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

Domain

The domain that the cookie is available to. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.

Please check your code where you are setting cookies matches Drupal Site Domain name and Path where you are trying to access or print them.

You can set cookies in Drupal using user_cookie_save function.

For Example

user_cookie_save(array('key'=>'value'));
print $_COOKIE['Drupal_visitor_key']; //outputs value


Language switcher doesn't work with my views

It is possible to solve this with Views, here is how:

Go to your view's edit page.
Add a Filter Criteria called 'Content translation: Language'
In the popup that comes after that, select 'Current user's
language'
Save the Filter Criteria and your view as well.

After this, this view will only show items that are the same language as the language you are using at the moment on the website.

You can however set a specific language to your view as well with the same criteria. You just have to select a language instead of 'Current user's language' and that view will only list content that are in that specific language.


What you could do is hooking into the pager function and changing its functionality in that page.

I would also recommend using mini pager instead of pager since its much shorter and easier to manipulate.
take a look  here
and here


Filter Content Cronologically Based on Current Month

I can't think of a 'clean' way of doing it within the Drupal interface, but it should be doable by using a template. An override of views-view-table.tpl.php (or the list version of that) and then test the dates as they come through.
It would be a little tricky to know which block has been previously put up (and therefore where to start the next block) but I think it is possible.

In more detail.

Create a view with the listing that you want (for all months).
Create three blocks within that view (they can be the same).
Using the Theme Information tab, find the name of the template that
handles the rendering of the rows.
Put code in that template to only take a months worth of dates at a
time.
Set a flag that 'Feb' is done, so next iteration will be 'Apr'.


You wouldn't actually need to write any custom code to implement something like this.

A possible solution is outlined below. It is aimed at Drupal 7. Some of the functionality mentioned may not be ready for Drupal 8 so you might need alternate modules or custom code in those cases.

Create a new content type, which would be named "Exam paper" or similar. There would be one node per student per exam.
Add a multiple value file field to the content type. Make sure it uses the private file system. Using the private file system will mean that only users with access to the node will be able to access the files attached to the node.
You can use the file field paths and token modules to make it so that the file directory structure and file names match the pattern you want. With the tokens you can easily reference student, teacher or exam information from fields on the node in the path or file name. This has no effect on access control but might make things better for you in other ways.
There are a number of ways you can handle access control as there are a variety of access control modules available for nodes, however I would be inclined to go with the node access user reference module. So you would add an entity reference field on the content type that references users with the student role. You can then set permissions so that the referenced user can access the node and other users cannot.
You can use the rules module to notify the user under various circumstances.
You can use Drupal core comments to have comments on exam paper nodes.
Due to using nodes you can leverage the wide variety of add on modules that focus primarily on nodes.
If you want to store additional data with each specific file, you can install the file entity module, which will allow you to add fields at the file level as well as the node level.


How can I change the default link to the email contact form?

You have two options to solve your issue:

CSS Option: You can replace text with image using css, add the following code to your css file and make sure to replace field name accordingly

.field-name-field-custom .field-item a {
  display: block;
  text-indent: -99999em;
  background-image: url('../images/image_name.ext');
  background-position: left top;
  background-repeat: no-repeat;
}

Note: field-custom should be replaced with your email field

Field Formate Option: You can create a new field formate in a new module and then you can choose from Field UI the new formate that you created.

Implement the following code in a Drupal module.

/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
    'email_contact_image' => array(
      'label' => t('Email contact form image link'),
      'description' => t('Display an image link to a contact form.'),
      'field types' => array('email'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'email_contact_image':

      $ids = entity_extract_ids($entity_type, $entity);

      if ($ids[0] !== NULL) {
        foreach ($items as $delta => $item) {

          $img_vars = array(
            'path' => drupal_get_path('theme', 'THEME_NAME') . '/images/IMAGE_NAME.EXT',
            'alt' => t('Contact person by email'),
            'title' => t('Contact person by email'),
            'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
          );
          $img = theme('image', $img_vars);

          $options['html'] = TRUE;

          $element[$delta]['#markup'] = l($img, 'email-contact/' . $entity_type . '/' . $ids[0] . '/' . $instance['field_name'], $options);
          // Since email is always sent to first item's email, break after any email address found.
          break;
        }
      }
      break;
  }

  return $element;
}

Notes:

make sure to replace mymodule with your own module name
make sure to replace THEME_NAME with your own theme name
make sure to replace IMAGE_NAME.EXT with your own image name

Creating modules - tutorial


Will deleting the Body Field from one Content Type also delete this field from other Content Types?

Yeah is safe, but directly you can't delete the body field, in the page where you admin the fields there is no link for delete it.

The way to delete it is when you create a new content type in the field where you put a label for "body" just let it in blank.


I believe you are looking for template suggestions, see Drupal 6 Template Suggestions, one of the Drupal provided theme suggestions will do it for you.

I think the one you are looking for is page-node-[node-id].tpl.php

Alternatively you can create your own theme suggestions, see Working with template suggestions

Edit: It depends on what you want the code to accomplish if this answer is correct or not, if it's something related to display then templates may be correct, but if it's data manipulation then you may be better off with template_preprocess_node

Alternatively if you want to execute arbitrary code not directly related to just the theming of the node, I think you would use hook_nodeapi or hook_view


As @Smalution pointed out, this is generally done using the site Slogan option which is set at /admin/config/system/site-information.

This is the standard way of doing this but relies on the theme you are using have the line

<?php print $site_slogan; ?>

Some where in the page.tpl.php

If you are creating your own theme, or hacking some one elses make sure this is in there. But, in some themes (this goes for Garland that ships with D7) you will see something like

<?php print $site_name_and_slogan ?>

in the page.tpl.

This is because the page template has gone through a preprocess function in the template.php i.e function garland_preprocess_page(&$vars) and the slogan has been wrapped with the title and a new variable created :

$vars['site_name_and_slogan'] = $site_name_text . ' ' . $slogan_text;

So if you can't see $site_slogan straight away that's probably why.


Same tax for all territories and tax-free products

(Answering my own question.)

I ended up not using Commerce's Tax module but coding my own.  I added a "Taxable" field to products and created an Order Processor plugin to calculate the tax amount and add it to orders as an adjustment.

It took much longer to figure out how to do it than to actually do it.


I found myself problem. Export full create different .yml file than export single. That why it make some fields lost.
Besides, the export function might ignore hidden fields in .yml files. In this case it should add fields manually to avoid conflict.


How to get rid of Re geocode and delete radio boxes on Location module?

There isn't a template to edit the location module's form elements. You'll need to alter its form element. You can drop the following functions into a custom module to alter the form element so that it doesn't display the Recode/Delete checkboxes.

function MYMODULE_element_info_alter(&$type) {
  if(isset($type['location_element'])) {
    $type['location_element']['#after_build'][] ='MYMODULE_location_element_post_render';
  }
}
function MYMODULE_location_element_post_render($element, &$form_state) {
  $element['delete_location']['#access'] = FALSE;
  $element['re_geocode_location']['#access'] = FALSE;
  return $element;
}


How to set images path on libraries JS file in Drupal 8?

Weel, I found s solution, quite simple: just use {{directory}} on the template. ;)


How and where to use/place database queries when a webform is submitted?

You can use hook_webform_submission_insert to insert data in custom table

ie :

function hook_webform_submission_insert($node, $submission) {
  // Insert a record into a 3rd-party module table when a submission is added.
  db_insert('mymodule_table')
    ->fields(array(
    'nid' => $node->nid,
    'sid' => $submission->sid,
    'foo' => 'foo_data',
  ))
    ->execute();
}

As mentioned in above example you will find all submitted data in

$submission

variable.


Is there anyway to get more control over when CRON runs?

You can use "Elysia Cron" or "Cron Control" module to control the cron.

I have not worked on "cron control" module, but I have used "Elysia Cron" module to manage different cron in the site.

Elysia Cron: http://drupal.org/project/elysia_cron
Cron Control: http://drupal.org/project/cron_control


Update: Changes made to work for Drupal 6 as your tag states 6.

It looks like the system is using the standard block.tpl.php with this code:

<div id="block-<?php print $block->module .'-'. $block->delta; ?>" class="clear-block block block-<?php print $block->module ?>">

<?php if (!empty($block->subject)): ?>

<?php print $block->subject ?>

<?php endif;?>

<?php print $block->content ?>

What you need to do is add another block template file, and take away the
 tags you want to eliminate.  To do this, add a template named block-module-delta.tpl.php to your active theme.

For block-module-delta.tpl.php

Module = the module that's creating the block (views, block, etc)
Delta = the internal id assigned to the block

So if the block module made the block, and it has an id of 4, you'd name the template file block-block-4.tpl.php, and you'd put this PHP/HTML in the template file:

<?php if (!empty($block->subject)): ?>

<?php print $block->subject ?>

<?php endif;?>

<?php print $block->content ?>

Notice how I eliminated the
 and
 from the template.


Password protection for section of a drupal website

Introducing password protection to parts of a Drupal website means that you enter the the wild (and somewhat mysterious) world of node access control.

Out of the box, Drupal 7 (and previous versions) only provides a single global permission to grant a role the right to view a node (i.e. view published content in Drupal 7).  To get more fine grained access control to published content, you must use a node access module.  There are several node access modules to choose from.  This page gives a good introduction to the rules that govern node access, and lists the major modules that help you manage node access, along with capsule reviews of each.

There are no single "best" module.  Each module have different characteristics.  I suggest you identify those you think are the best fit for your site, and check them out, before committing to one of them.

Your plan (to have a company user with a company password) have some logistical problems (see last paragraph), but can be implemented (sort-off) by means of a role based access module.

A better approach (IMHO) would be to create a set of node access "groups" (this can be roles, OG groups, or ACLs - depending upon the module you choose to use), where each "group" consists of all the users associated with a single company. I.e. you assign existing users to these groups. Now users can authenticate with their primary password, but you can set up node access grants to be determined by each user's "group" membership.

The approach you suggest (with a company user and company based password) will have the problem that the company user's password can not be protected against changes without a custom module.  Also, you may run into problems if a user leaves one company and joins another.  Then the old company's passwords must be changed so that this user may no longer have access, and the new password must be communicated to all existing employees of that company.  If you do this the way I suggest, you just remove this user from the group belonging to the old company, and adds him to the group belonging to the new,. That is all that is needed to make sure that he loses access to the content belonging to his "old" company, and gains access to the content belonging to the "new" company.


Drupal 7 custom block not showing in block list

That is because your module_block_view() function is not written properly. the content is not passed into any of the blocks you defined in your module_block_info()

function bloque_buscador_block_view($delta = '')
{
        $block = array();
        switch ($delta)
       {
        case 'bloque_home':
            $block['subject'] = t('Syndicate');
            $block['content'] = YOUR CONTENT IN HERE,

        );
        break;
        case 'bloque_sidebar':
            $block['subject'] = t('Syndicate');
            $block['content'] = YOUR CONTENT IN HERE,

        );
        break;
      }
    return block;
 }


How to change facebook og:image to post image link?

The Metatags module supports OpenGraph meta data with token support, patterns, overrides for individual nodes and so on. It's a really handy module for this kind of stuff.

http://drupal.org/project/metatag

If you're getting the wrong image show up in Facebook you could point it to the correct image using this module's token support.


services.yml files are not service providers.

ServiceProviders are to dynamically add or modify service definitions, a yml file is just content that's parsed and merged together with everything else.

If that's not loaded then my guess is that you named it incorrectly, but you didn't include the filename, please add that including the other files you have, specifically the info.yml file.


Why can't I set radios default value (when after build is done)

The assignment of the default value doesn't seem correct. I think it should be like this:

$form['field_shift'][LANGUAGE_NONE][0]['value']['#default_value'] = 'early';

See the following questions and their answers for more information:

Programmatically set the default value for a field
Why is hook_form_alter() so messy?


How to position an element using jQuery UI .position method?

I think the problem is that you need to also load the UI libraries using the newer jQuery version. jQuery UI is a jQuery plugin, so it attaches to jQuery itself. Within your function $ refers to jQuery 10, while the UI plugin is loaded for Drupal's jQuery.

To fix this you have to use jQuery Multi to also load the libraries with the newer jQuery. You can use hook_jqmulti_files():

function mymodule_jqmulti_files() {
  return array(
   'path/to/file.js',
   'another/full/file/path.js',
  );
}

You'll need to specify the file paths, which you can put together using drupal_get_path() or get using drupal_get_library(). Once you do that jQuery Multi will automatically load those files in the newer jQuery context and then .position should be available to you in your function.


How and where to create a prefix key for memcache?

All those settings are added to settings.php

usually sites/default/settings.php

$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['memcache_key_prefix'] = 'k1';
// Use database for cache_form
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

You only need a memcache key prefix if you're using memcache with more than one site on that server. Adding a short key, e.g $conf['memcache_key_prefix'] = 'k1'; is good practice.


View showing ONLY taxonomy children terms and NO parents

Super simple but impossible to guess solution :

With a normal filter set the "Parent term" filter not equal to "0".

This will filter parents


exporting/importing nodes without losing disqus comments / social media stats

To export single nodes you can use the Node Export module. This one allows you to export a node, it's fields and contents to a text file which can be imported on another site with the Node Export module.

Assuming you are using the Disqus module: To export comments and social media stats you will have to use the Disqus Migrate submodule. To use either Import/Export, you have to register an Application with Disqus and fill in both your public and private keys in the main Disqus settings page. Make sure your authentication method is set to the deprecated legacy method. Download the PHP API implementation here and upload the disqusapi folder to your sites/all/libraries folder.

Export:

Export your comments using the XML method until the API method is fixed, and save the file to your computer.
Upload the XML file to your Disqus site in the Tools section (generic WXR method), and wait for the import to complete.
Check for errors after importing, but most comments should have been imported successfully. They will appear automatically on any Disqus-enabled nodes on your website.

Import/Sync:

You can do a one-time import at Comments->Disqus Import. Specify the timestamp you want to import from.
You can have comments automatically import from Disqus on an interval basis. Turn this on in the import settings at Site Config -> Disqus -> Import. Turning on syncing will query Disqus for any comments that came in since the last import.


If you only have 3 types and you don't plan on changing often, the easiest way to do that might be to create views of those three content types and use views_embed_view.

You could potentially override the search results in your theme using search-results.tpl.php. A more complex, and possibly better way would be to write a custom module that implements hook_menu_alter and redirects the default search callback to a custom view in your module.

I have done something like that before and it's not a trivial undertaking (take a look at the apachesolr_search module if you want a complete example).

Something like (untested)...

function mymodule_menu_alter(&$menu) {
  if (isset($menu['search/mymodulesearch/%menu_tail'])) {
    // redirect default search to this module's view
    $menu['search']['page callback'] = 'mymodule_search_view';
    // create a menu linkspecifically for this view
    $menu['search/mymodulesearch/%menu_tail']['page callback'] = 'mymodule_search_view';
    $menu['search/mymodulesearch/%menu_tail']['weight'] = -20;
  }
}

function mymodule_search_view() {
  $keys = search_get_keys();

  // do something with views_embed_view here
}


Is there a way to get a value of a multi value field of an entity reference (reference a field value of a referenced term)?

You can do this in a custom field type based on the core reference field, adding  a second property and dynamically filling the options of the select list depending on the first property.

For the multi-value part of your question a non-coding solution would be a paragraph containing both fields. Adding the dynamic behavior can then be done in a form alter hook or you can try Business Rules and adjust this recipe to your requirements: https://www.drupal.org/docs/8/modules/business-rules/advanced-usage/dependent-field


Drupal Commerce : Shipping Calculator for Shipping Service

I think you're looking for a module that do a very specific behavior, some shipping providers don't offer this option and if they do, maybe the drupal module doesn't implement it yet.

The basics of calculating shipping is knowing what the item measures and weights, for that you've got the modules Physical field and Commerce Physical product. With that you've got a field for dimensions and another one for weight, that would help you communicate with your shipping providers to get a quote before the user goes on with the checkout.

Commerce Fedex module seems to offer integration with the
physical modules mentioned above.
Commerce USPS also claims support for physical modules in the project description page
Commerce UPS also seems to provide physical module support.

Once you've got everything set up and your products have the information needed, you can start filtering out the shipping methods offered for every context and user. Depending on the visual requirement and behaviors you'll need to customize it further, but these collection of modules should provide a basic shipping calculation service.


Compare Two Select Lists, and Require User to Select Different Values

For the Drupal form API, this would be handled with your validation handler. Have it check your 2 form values for equality, and throw an error if so.

function MYFORMBUILDER_validate($form, $form_state) {
  if($form_state['values']['person_primary'] == $form_state['values']['person_backup']) {
    form_set_error('person_primary', t('The primary and backup person must be different'));
    form_set_error('person_backup', t('The primary and backup person must be different'));
    array_pop($_SESSION['messages']['error']); //Remove duplicate message
  }
}


Show teasers from both content type and Users together in a view

Since you say that you would like to show a page with separate blocks of companies and users, there's no need to do this all in the same View.

Create two different Views with Block displays. One for the teasers of Company content type, one for the teasers of the Users. (You have done this much already.)

Then, place both of those Blocks in theme regions on the same page, and they should both appear ... together, but separately.


When the block visibility is set to 2, $block[0]['pages'] needs to be a string that can be passed to drupal_eval() as first argument. In fact, the code which handles the block visibility is the following one.

  // Match path if necessary
  if ($block->pages) {
    if ($block->visibility < 2) {
      $path = drupal_get_path_alias($_GET['q']);
      // Compare with the internal and path alias (if any).
      $page_match = drupal_match_path($path, $block->pages);
      if ($path != $_GET['q']) {
        $page_match = $page_match || drupal_match_path($_GET['q'], $block->pages);
      }
      // When $block->visibility has a value of 0, the block is displayed on
      // all pages except those listed in $block->pages. When set to 1, it
      // is displayed only on those pages listed in $block->pages.
      $page_match = !($block->visibility xor $page_match);
    }
    else {
      $page_match = drupal_eval($block->pages);
    }
  }


How to display featured or new products on main Ubercart catalog page?

Create a view and make a block in that and then expose that on the /store page above your content or what you see fit. that should do it.


At a high level, you could do something like this with a custom module:

Create a custom VBO action (see docs) to take action on your selected nodes.
Have your custom VBO action redirect to /node/add/payments with some query parameter that encodes your selected nodes (e.g. /node/add/payments?my_nids=1,2,3).
Add hook_form_alter() invocation in your module to read this query parameter (e.g. $nids = explode(',', \Drupal::request()->request->get('my_nids')) and pre-populate the entity ref field with your values.


Easiest way to add popup dialog with snippet of html/text using a wysiwyg editor?

Here is a recipe for that:

CKEditor Link: Used for linking to other content in your Drupal. In this case, I would create another Content-Type, e.g. Popup Snippet or sth similar. This is an optional component, depending on your exact requirements.
Colorbox Node: Used for presenting node content in a popup, stripped of the surrounding regions and other theme elements. It also provides an easy way to turn links into popups, by providing a 'magic' class, colorbox-node. This is the main component, and the main idea, allowing the user to 'popify' links by adding a class name to the link's properties in CKEditor.

Below are some screenshot of the result on a D7.

Linking to content

Setting the colorbox-node class

End-result

Good luck!


How to update url_alias after SELECT FROM url_alias

Regarding the query, you can do the query using a temporary table:

CREATE TABLE `tmp` ( alias varchar(255));

INSERT INTO tmp (SELECT alias
FROM url_alias LEFT JOIN node
ON CONCAT('node/',node.nid) = url_alias.source
WHERE node.type = 'forum');

UPDATE url_alias
SET alias = REPLACE(alias, 'content/', 'forum/')
WHERE alias in (SELECT alias FROM tmp);

DROP TABLE tmp;

But if there are lots of those aliases with all different cases, it's better to follow the following steps:

Delete all records from the url_alias table.

TRUNCATE TABLE url_alias;
Go to your admin interface at yoursite.com/admin/config/search/path/patterns and define the patterns for the needed node types.
Go to the 'bulk updates' tab of the URL Aliases definitions (yoursite.com/admin/config/search/path/update_bulk) and bulk update all content paths.


How to set up a field to provide a publish/unpublish feature?

I would use the Flag module. Excerpt from its project page (bold markup added here):

... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

So by using a "global flag" (whatever you'd call such flag), you could just "mark or do not mark" something as published. If appropriate, you could also consider Attaching fields to flags.
If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.
Refer to Flag's Community documentation for (way) more details.
PS: near the bottom of the Flags setup is an option 'Display link as field', which will include it as a field, for views, Panels, etc (if that's why you want a field).


Getting 401 / 406 error from node creation with authentication

Change the URL to http://localhost/drupal/myrest/node, the application type to  application/json, and the request method to POST; then, it should work.


As far as I understand your question, you want to get rid of the "Edit" pen icon, displayed when you put the mouse over a node.

This is not provided by the "Quick Edit" module. You have to disable "Contextual Links" if you want to get rid of that menu.

Alternatively, if you are using those links for managing blocks for example, you might want to force hiding contextual links on nodes via CSS.

For example:

.your-node-selector .contextual {
  display: none!important;
}


it may be posible with a node view, not with tokens, with field values: contextual filter, nid from url, provide a default value, php code, like:

  $node = menu_get_object();
  if ($node->type == 'cars')
  {
         $mynodefiield = node_load($node->nid)->field_car_make[und][0][target_id];
      return $mynodefield;
  }

note: [target_id] is if field is an entity reference (node or taxonomy);

that view will return only nodetype=cars, and your token [cars:make] that have the same value as field_car_make.

sorry, i do not know how to do it with tokens, i hope it helps.


Making both Site name & Site slogan to be one single link in mini-panels

I see three options that I think you could do.

Update the content in the theme layer which you can try to check in this page and it's other related pages. https://www.drupal.org/node/1678810
Use panel pane hooks to add additional settings for the Site Slogan panel pane.
Create a custom panel pane


One of the best way to learn how to do develop various common tasks is with Examples module.

Check especially the form_example module which has all necessary instructions and code examples.


How about using the Unique field module for this? Here is a quote about the module's project page:

  This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.


product in cart but when clicking on cart it shows empty

If you do a quick search of the issue queue for "Views results empty", you should turn up the solution: you've probably customized your shopping cart View to include a product relationship, but your test user must not have access to view all products. When Views goes to render the results and performs the access check on the View results, it won't show anything as a result.

If this is the case, my recommended solution would be to edit the View, open the advanced settings fields, and edit your query settings to disable SQL rewriting for the View.


After registration, store email address and redirect to to another page

In your submit handler, you could use drupal_set_message to set the message like this:

function custom_user_register_submit($form, &$form_state) {
  $form_state['redirect'] = 'content/welcome';
  drupal_set_message('Your mail is @mail', array('@mail' => $form_state['user']->mail));
}

You could also save it in the $_SESSION if you don't want to use drupal_set_message and get it from there.


Force an image to display as block (not inline)

This looks to be a CSS issue, not a Drupal issue. Leverage "display:block" and "min-width:100%" on whichever wrapper div you want to stay on top. But you'll need some CSS massaging and experimenting to get it working as you need.


How do you modify the form after it validates and show's errors

You need to set the form to rebuild on validation fail.

$form['#rebuild'] = TRUE;   // cause form rebuild after validation failed

Then you can use your $form_state['values'] inside your hook_form_alter().

OR

You can create a custom function and use the #after_build property.


Adding validation to widget settings form

Once again, I've found the solution to my issue. Although I said that I had tried #element_validate in my original post, I must have messed something up, because that turned out to be the solution. Here is the code:

class SomeWidget extends WidgetBase implements WidgetInterface
{
  public function settingsForm(array $form, FormStateInterface $form_state)
  {
    $element['my_field'] = [
      '#type' => 'textfield',
      '#title' => t('My Field'),
      '#default_value' => $this->getSetting('my_field'),
      '#required' => TRUE,
      // Add your validation here
      '#element_validate' => [
        // settingsFormMyFieldValidate() is arbitrary. Choose something descriptive
        [$this, 'settingsFormMyFieldValidate'],
      ],
    ];

    return $element;
  }

  public function settingsFormMyFieldValidate($element, FormStateInterface $form_state)
  {
    $submitted_value = $form_state->getValue($element['#parents']);
    if($submitted_value != 'something it should equal')
    {
      $form_state->setError($element, t('You submitted a bad value'));
    }
  }
}


As far as I know, Drupal doesn't cache submitted form data. However, generated HTML Code is cached in many places.

I've come upon this problem when rendering a form in a block produced by a custom module. If block caching is active and the form is sometimes rendered with some fields pre-filled (The user's name, the previously used search term), that version of the form might be cached and displayed to other users.
This particular case is easily fixed by setting $block['my_block']['cache'] = DRUPAL_NO_CACHE; in your module's implementation of hook_block_info.


You are looking for set_items_per_page()(6), set_items_per_page()(7). Essentially the function does what you are already trying to do, but probably you are calling it on the wrong object, so use the function instead, and Views will ensure it's the right object. :)


How do I check the logged-in user username/password/role using a function to validate them?

To check login credentials in Drupal 6&7:

$uid = user_authenticate($username, $password);

In Drupal 8:

// Inject user.auth service..
$uid = $this->userAuth->authenticate($username, $password);
// or
$uid = \Drupal::service('user.auth')->authenticate($username, $password);

To check roles:

/**
 * Check User roles
 * @param $role
 * @param null $user
 * @return bool
 */
function user_has_role($roles, $user = NULL) {
  if ($user == NULL) {
    global $user;
  }
  if (!is_array($roles)) {
    $roles = array($roles);
  }
  if (count(array_intersect($roles, $user->roles))) {
    return TRUE;
  }
  return FALSE;
}


How get empty record on date field with entityQuery?

Since the field is stored in a single table, this is how i get all empty record from my entity where my custom field is empty :

 $query = \Drupal::entityQuery('test_entity');
        $query->notExists('field_date');
        $ids=$query->execute();


entityQuery with multiple conditions on taxonomy terms returns no result

The reason you can't do that is that both of these fields are entity reference to the same entity. That means that the base table is the same base table.
You are asking Drupal to Join the taxonomy_data table to the node table and then make an impossible AND condition on it.
P.S.
You can use condition('field_tags', 1); instead of condition('field_tags', [1], 'IN');
And as mentioned in the comments, the AND condition group is the default, so you don't need to specify it.
P.P.S.
You should have both conditions use the referenced id to be consistent.


How to access $user_profile in page.tpl.php or $page in user-profile.tpl.php in Drupal 7?

As for including regions in user-profile.tpl.php here how you do it.

In your custom theme add the following code to template.php file

function mytheme_preprocess_user_profile(&$variables) {
  // List of all regions for the current theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    // Add content to $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

Then copy user-profile.tpl.php to your custom theme and then place the following code between any HTML tag.

print render($region['region_name']);


Letting users remove webform submissions they've made earlier

Implement sign ups as nodes instead of as webform submissions. Then you can grant the delete own [node type] nodes permission to allow users to cancel the sign up.


Are there any working Form Modules in Drupal 8 yet?

As of 29 mar 2016, there is a dev version of webform, but they're not confident in it enough even to publish it as dev: https://www.drupal.org/node/7404/release?api_version%5B%5D=7234

There's also eform, which is a D8 version of the entityform module: https://www.drupal.org/project/eform

When you're digging through dev versions, a good metric is looking at how many people are using that version-- check the per-version usage stats.  Ideally you want thousands or tens of thousands of sites reporting, but we're not there yet.

For now, I'm hacking the d8's core contact module.  I hope that a more complete solution will be available soon.

People who say you shouldn't use dev modules on production sites are living in the past.  Drupal 7 would have been functionally unusable to a huge chunk of its user base for a long time if no one put dev modules into production.  There are still dev modules that are integral to the function of thousands of substantial d7 sites.  Drupal 8 is nothing but a toy without relying on dev modules-- the form question being an excellent illustration.


Search page shows empty fields of unpublished content

In your view, besides FILTER click on add, select Content Published (YES)


In order to achieve this on Drupal 7, you need to develop a custom module that does the following:

Register a menu hook that will act as the endpoint where your javascript will send the data for the node to be created.

Create a function that will be the callback of the hook and handle the actual creating and saving of the node. It can be something like this as mentioned in the answer above:

$data = json_decode($_REQUEST['title']);
$node = new stdClass;
$node->type = 'article';
$node->title = check_plain($data->title);
node_save($node);
echo json_encode(array('Status' => 'OK'));
drupal_exit()

Notice drupal_exit() is needed otherwise you get the whole page rendering.
In order to set other properties for example the body, you need to know the structure, it is usually something like

$node->fieldName[language][delta]['value'] eg, $node->body['und'][0]['value']

That's all it needs on the php side, now on the javascript side you will be needing to create an array containing the values for the node and submit it via ajax. Using jQuery it can be done like this:

jQuery.ajax(
{
    url:  Drupal.settings.basePath + queryPath,
type: 'POST',
dataType: 'json',
data:  {'data': JSON.stringify(queryParameters)},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
    console.log(JSON.stringify(XMLHttpRequest));
    console.log(JSON.stringify(textStatus));
        console.log(JSON.stringify(errorThrown));
},
success: function (data)
{
    console.log(data);
    }
});

Data can contain anything returned from php...

Have fun

Update:

A more general and concrete solution is available through the use of the Services module that allows you to define a REST api over the various content types you create. This way you don't need to write any custom code on the php side,


Show profile2 fields only to specific user register path

You could apply that patch to profile2_regpath.module which simply show all profile fields to its registeration patch posted here


No, you can't. drush pm-update has been deprecated for a while. The command is still available in the Drush 8.x branch but in later revisions it only exists as a signpost to inform the user how to move to Composer:

  The pm-updatecode command was removed. Please see composer update --dry-run and composer update.

Noting that Drush 8 isn't supporting revisions past 8.3.x or 9.x, you should look into upgrading Drush and moving to a Composer-driven upgrade process.


How to embed Drupal content in other websites?

You can use the Views module to output content as XML/RSS and add a widget to your target site that can build links based on the content in your XML feed.

Depending on your target site there may be pre-built (Wordpress, Drupal, Joomla, Blogger) plugins/addons available to do exactly what you're hoping to accomplish.


How to protect thumbnail and library images from media browser from being deleted?

You could try this module:

Soft delete

  This module allows selected users, based on a permission, to soft
  delete nodes. To users the operation looks like delete but the node is
  unpublished. It's useful if you want to prevent accidental deletes or
  bring back content that wasn't supposed to be deleted.

  Note that this is a very simple module, adding just a tab called
  Delete next to View and Edit on nodes that the user can unpublish. A
  more advanced and customizable alternative is the Content
  unpublish module.


How to hook into access control of node/add menu handler?

node_hook() is not an hook; it's a helper function Drupal uses to verify a content-type hook exists. In the code you are showing, the function is verifying the module implementing the $type->type content type implements hook_form().

To alter the access control for a node, you have two options:

Implementing hook_node_access()
Implementing hook_node_grants() and hook_node_access_records()

Implementing hook_node_access() is easier, but that hook is not used in node listings (lists of nodes generated from a select query, such as the default home page at path 'node', an RSS feed, a recent content block, etc.).

Notice that, since _node_add_access() is an access callback, you could change the access callback used by node/add. I suggest not doing it because that would by-pass all the node access control implemented by Drupal.

Reference

Node access right


I solved the problem.

Taking inspiration from this thread, I figured out that, for some obscure reason, I need to set the email setting under "Administration > Configuration > System > Basic site settings > E-mail address" to an existing email address on my hosting service.

So, I created a new email with cPanel, noreply@mydomain.com, then I setted this email address in the above configuration.

Now seems that all is working perfectly.