Given a File ID (fid) how can I get the HTML that represents that fid? I'm looking to do something like this

$fid = 15;
$file = (array)file_load($fid);
$content = drupal_render($file);
echo $content;

file_load()
drupal_render()

And specifically this fid is from the 7.x-2.x version of the media module.

This works for me. For videos via the media module:

<?php
  $file = file_load($fid);
  if (strpos($file->filemime, 'video/') !== 0) {
    return;
  }
  $key = 'media_' . substr($file->filemime, 6) . '_video';
  $formatter_info = file_info_formatter_types($key);
  $content = array();
  $content['#theme'] = $key;
  $content['#uri'] = $file->uri;
  if (isset($formatter_info['default settings'])) {
    $content['#options'] = $formatter_info['default settings'];
  }

  $rendered = drupal_render($content);
  return $rendered;
?>

And for images; this shows you what presets are available (#style_name)

<?php
$styles = image_styles();
echo '<pre>' . print_r($styles, TRUE) . '</pre>';
?>

And this will render the file

<?php
$file = file_load($fid);
$image = image_load($file->uri);
$content = array(
  'file' => array(
    '#theme' => 'image_style',
    '#style_name' => 'large',
    '#path' => $image->source,
    '#width' => $image->info['width'],
    '#height' => $image->info['height'],
  ),
);
echo drupal_render($content);
?>

Note that image_load performs I/O.

And for the reverse; given a filename get a fid.

<?php
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'file')
  ->propertyCondition('filename', basename($filename))
  ->execute();
foreach ($result['file'] as $values) {
  $fid = $values->fid;
  break;
}
echo $fid
?>

Given media embed code, get a FID.

<?php
$file = media_parse_to_file($embed_code);
if (empty($file->fid)) {
  return FALSE;
}
return $file->fid;
?>


Local simpletest drupalGet() always gives "returned 0 (0 bytes)" I want to run tests locally with simpletest module.

I tried this with the cli scripts/run-tests.sh, and also in the admin UI.
I tried different tests shipped with Drupal 7 core, such as the ContactSitewideTestCase test.

Whenever a test wants to make a http request with $this->drupalGet(), the test reports a fail saying e.g. "GET http://d7git.localhost/user returned 0 (0 bytes)."

I think to remember that something needs to be configured for simpletest to make http requests. But I cannot remember what it is, and cannot find documentation that would explain it.

This error means that your test cannot reach your website.

I had a similar issue using something based on docker for drupal. For me the solution or hack the hosts file on the php container and change to point the domain you want to test to to the ip of the proxy server, in my case traeffik.

So in my host file I had something like this:

172.18.0.5      domain.internal

once that is done you can use curl to test the connection:

curl -v domain.internal

In my case I had an issue with a self signed certificate.

Rebuilt URL to: https://domain.internal/
Trying 172.18.0.5...
TCP_NODELAY set
Connected to domain.internal (172.18.0.5) port 443 (#0)
ALPN, offering http/1.1
successfully set certificate verify locations:
CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: none
TLSv1.2 (OUT), TLS handshake, Client hello (1):
TLSv1.2 (IN), TLS handshake, Server hello (2):
TLSv1.2 (IN), TLS handshake, Certificate (11):
TLSv1.2 (OUT), TLS alert, Server hello (2):
SSL certificate problem: self signed certificate
Closing connection 0
curl: (60) SSL certificate problem: self signed certificate
More details here: https://curl.haxx.se/docs/sslcerts.html

curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.

However this should allow you to run your simpletest(s) in your browser.

Ideally there should be a way to configure this in your docker-compose file but I am not sure how?


How to move the Forena report parameters block further down and give it a separate heading? Can the Forena parameters block be moved further down and given a separate heading?

The Forena Parameters block sits at the top of the page, but I would rather have it further down the page after some report headers, and with a different title like Conditions or Settings.
I would also prefer it to be opened rather than collapsed the first time the report is opened.
Is there some way to set this, preferably without editing the code for the module?

Rendering of the report parameters input form

Forena's custom renderer FrxParameterForm allows you to customize various aspects of the rendering of the report parameters input form. More details about it can be found in the tutorial included with Forena, located at relative path reports/help.renderers#frxparameterform. Here is part of what it says:

  Use it on a div tag anywhere within the body part of your report to control various aspects of the rendering of the parameter form.

Here is a sample of how to use it within the body tag of your report:

  put your actual report parameters here ...

{submit}

  here goes the rest of your report specifications ...

Some more details about the above example (also from the same documentation):

frx:title: The title of the parameters field set.
frx:collapsible: Indicate if the form should be collapsible or not:

set to "1" to make the parameter form collapsible.
set to "0" for a parameter form that cannot be collapsed.

frx:collapsed: Indicate how a collapsible parameter form should be shown:

set to "1" for a collapsed form.
set to "0" for a not collapsed form.
The default behavior is to expand the form only if no data was returned by the report.

frx:submit: The label of the submit button.

Theming the report parameters input form

For the actual positioning of the parameter form, I suggest you use a custom (new) CSS file, by adding 1 line to the "skin" used in your report (which is either the default skin, or your custom skin). To do so, just add a line that looks like so (name the CSS file whatever fits):

stylesheets[all][] = custom_forena_styling.css

Within that CSS file, you could (eg) add this CSS coding to make the parameter form be shown to the very right of your page (I prefer to do so by showing it "collapsed" as detailed above):

/* Apply some styling to the parameters form */

#parameters-wrapper fieldset.collapsed {
  float: right;
}

More details about "Report Skins" can be found in the tutorial included with Forena, located at relative path /reports/help.skins, or in the demo site. An example that uses these skins is to enable dataTables (to enhance the display of tabular reports).

Summary

With that, it's up to your own imagination to make the parameter form of your report (or chart) fit your needs, ie:

using the custom renderer options.
add whatever xHTML tags you want.
style it using your custom CSS.

Disclosure: I'm a co-maintainer of Forena.


How to execute a query taken from views in custom module Please don't suggest query builder, this is the single query I need run from my custom module with passing arguments.

I create a View with desire fields and copy/past the query in phpMyAdmin the query is not showing the actual values for columns instead showing value as NODE :(

Is there any way to achieve this?

Thanks

Goto admin/structure/views/settings and enable the setting

  Show other queries run during render during live preview

As the help text for the setting reads, probably during the view rendering time there are some changes that could be happening. Enabling this setting will give you an insight into what is happening.


Creating a Date Field that will display 'Year' to 'Current' I want to create a field that will ask the user for the date they started their job to when they left. If they are still currently working at the job, the user will click 'I currently work there' or something similar.   The date module currently can be setup to have a 'to' and 'from' field.  The tricky part is how do I save 'Current/Present' to the database.  How do I go about this?

This is doable using Conditional Fields despite its rather minor limitation (http://drupal.org/node/360824). You can't trigger fields' display by a checkbox's off value. That will require you to negate the "I currently work here" checkbox to something like "Past position". You can still decide if you want it checked by default or not, and using JavaScript you can hide the "Past position" checkbox and control its value using the desired checkbox with the opposite meaning.

Saving 'Current/Present' to the database is not an issue really. You only need to check the value of the checkbox field and you can disregard the 'Current/Present' value if this is an ongoing position. To make the To date field work as expected, though, make it Required and choose an arbitrary Default value for it, which will be used even when the field is not displayed. Now would be a good bet.

Here's an image which pretty much wraps up the 5 minute content type setup.

It's obviously going to take a little more than that to make the form look and behave the exact way you want. For information on theming the resulting form, see Theming a form with conditional fields.

Also see Conditional Fields Docummentation


How to implement some super admin feature to facilitate password retrieval for existing users? I'm aware that Drupal 7 saves the user's password in a more compact way and it's really hard (impossible?) to convert such password back to a human readable text format (even not into database).

Actually I do not want to implement any hack to Drupal, but it's a requirement that a super admin can somehow view the username along with its password for any user. Super admin is a trust worthy role and actually will help through secured communication media to other users after forgetting their password.

So there is a need to create a block to show all the usernames with their corresponding password, which can only be used by a super admin.

Any suggestions about how I could implement all this?

Note:  Users are not allowed to reset passwords, I just want only super admin can access their usernames and passwords and then re-assign to other user if any of them forgot his password.

You can't. Drupal passwords are hashed, not encrypted, the key difference being hashes are one-way.

With Drupal 6's non-salted MD5 hashes, a rainbow table might get you there, but with D7's salted SHA512 hashes would be much tougher. The time spent trying to do this would be better spent trying to find an alternative to your need of listing all user/pass.


Inserting images and preventing the layout from breaking The client has asked for an auto resize of images (when inserting via the ckeditor) so to avoid the breaking of the layout, and including images that are just too big. Is there a way to automate this process? Do you normally offer this? Or do you just make the client aware of the width and height settings in the image properties window?

Image styles are built into Drupal 7. You can define image styles to have a particular size, by either cropping, scaling, or some combination of the two. Drupal 7 also supports scaling only down but not up.

If you want to do this in Drupal 6, you do it by installing the Imagecache module and configuring your styles with that.


Image not displaying in email I have views with three fields (Title, Image, Price). I want to send this view as email to registered user. I am using Mime mail to send email.

Email works fine but images are not displaying in email. Thanks.

I had this same problem few days back. Try to Inspect that broken Images, your Image might have source like this: src="https://ci4.googleusercontent.com/proxy/a0ulmqxF3B*******************************************gMzBa5MRdHDhrBXYc8KaMYIvFZ2HAf3P_lOwFrg=s0-d-e1-ft#http://yoursite/logo.png"

So if you are trying to send email from your local then probably they did not get cached by some google service because probably google can't access your local, try access.log for any issues.
Some other are also facing the same problem:
https://productforums.google.com/forum/#!topic/gmail/q47KoUYQXPw

this problem still persists on my local it has nothing to do with mime mail, or any other module, in fact I was able to send emails with images using only print-email- module try this https://www.drupal.org/project/print

Hope this helps you.
al
PS: If nothing helps try to send mail form live or your development site, you won't face this problem there, because there problem here is google not given access to your images at local machine.


Views: Display block based on taxonomy term I have a vocabulary (Alive or Deceased) that has 2 terms (alive and deceased).
If the node is under "alive" category there should be displayed block A, otherwise no block should be displayed.

How can I do that using views?

Thanks.

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


How do I modify a menu link title dynamically? This seems so simple, there -must- be a way, right?

I want to modify the title of a menu link dynamically. I've tried the techniques in this question:

Change menu link title dynamically?

...The last one ( using menu_token() module) seemed promising, but that threw an error when I tried to apply it to the menu item in question.

I also tried the technique here: https://www.drupal.org/node/1538094

...but that only modifies the Page title... not the link of the -menu-.

So I tried the following code, which doesn't appear to do anything (although I am sure that the variable is being assigned.)

Any other ideas? I must be missing something -obvious-, right?

function MY_THEME_preprocess_menu_link(&$variables) {
    if (isset($variables['element']['#original_link']['menu_name'])) {
          if($variables['element']['#original_link']['menu_name'] == 'secondary-navigation') {
        if($variables['element']['#title'] == 'Cart') {
          $new_title = 'Cart(4)'            ;
          $variables['element']['#original_link']['link_title'] = $new_title;
          $variables['element']['#title'] = $new_title;

    }

}

}
}

EDIT: I also tried this:

function MYMODULE_menu_link_alter(&$item) {
    // add in an if statement here to just target the links you want to change on the fly
    $item['options']['alter'] = TRUE;
}

function MYMODULE_translated_menu_link_alter(&$item, $map) {
    if($item['mlid']==1166) {
     // the watchdog fires properly
     watchdog('test', '' . print_r($item, 1) . '');
     $item['link_title'] = 'Cart(x)';
     $item['title'] = 'Cart(x)';
    }
}

...and the above did not work either.

This has gotta be something obvious, right?

It looks like the other answer on that post you linked to is quite relevant. It references hook_menu_alter() as a tool to:

  ... add a title callback that will be called every time a link to the menu item will be rendered

However, I'm not sure if that solution would work for manually-created menu links items with custom title text. The other, possibly more universal, option that I can think of is using hook_menu_link_alter() along with hook_translated_menu_link_alter(). The former is used to "flag" a link as alterable (when the link is saved), and the latter is used to actually alter it (at render time).

Actually, it looks like this post covers both these options in even more detail, so I won't repeat any of their code samples here.

This distinction about which alter hooks fire at save/cache-clear time vs. render time is important as it often means that you have to leverage a hook + callback, or 2 hooks, to implement dynamic alterations. For example, if you choose the second option you use hook_menu_link_alter() to declare the link as alterable, and though that hook does not fire each time the link is rendered, it "registers" the fact that hook_translated_menu_link_alter() should in fact be called at render time for that specific link.


Get file or image path as string from uid I need to get the relative path to a file, in this case, what i need is:

/sites/default/files/pics/DSC00873_39.JPG

But all I seem to be able to get is the following:

$file = file_load($pic);
print $file->uri; // public://pics/DSC00873_39.JPG

Any ideas please?

Yep. There is a function for that.

http://api.drupal.org/api/drupal/includes%21file.inc/function/file_create_url/7


How to add revisions tab to a custom content entity and list revisions? I've just created/generated a custom content entity module using Drush. I've checked I would like to use revisions, but I cannot see its tab.
How can I add the revisions tab to this custom content entity and list its revisions?

To support revisions, the annotation used for the entity class needs to:

Declare the revision tables
/**
  *   revision_table = "node_revision",
  *   revision_data_table = "node_field_revision",
  */

Tell Drupal to show the revision UI
/**
  *   show_revision_ui = TRUE,
  */

Tell Drupal which fields in the database match the revision entity fields
/**
  *   entity_keys = {
  *     "id" = "nid",
  *     "revision" = "vid",
  *     "bundle" = "type",
  *     "label" = "title",
  *     "langcode" = "langcode",
  *     "uuid" = "uuid",
  *     "status" = "status",
  *     "published" = "status",
  *     "uid" = "uid",
  *     "owner" = "uid",
  *   },
  *   revision_metadata_keys = {
  *     "revision_user" = "revision_uid",
  *     "revision_created" = "revision_timestamp",
  *     "revision_log_message" = "revision_log"
  *   },
  */

In the links section, tell Drupal which links are for the revisions
/**
  *   links = {
  *     "canonical" = "/node/{node}",
  *     "delete-form" = "/node/{node}/delete",
  *     "delete-multiple-form" = "/admin/content/node/delete",
  *     "edit-form" = "/node/{node}/edit",
  *     "version-history" = "/node/{node}/revisions",
  *     "revision" = "/node/{node}/revisions/{node_revision}/view",
  *     "create" = "/node",
  *   }
  */

(I used the annotation used from the \Drupal\node\Entity\Node class to show which keys needs to be used and as example of values to assign to those keys.)
Then the module implementing the entity must define the routes used for the revision pages. The Node module does it in the node.routing.yml file, but the route_provider class (which implements EntityRouteProviderInterface) could define them too.
entity.node.version_history:
  path: '/node/{node}/revisions'
  defaults:
    _title: 'Revisions'
    _controller: '\Drupal\node\Controller\NodeController::revisionOverview'
  requirements:
    _access_node_revision: 'view'
    node: \d+
  options:
    _node_operation_route: TRUE

entity.node.revision:
  path: '/node/{node}/revisions/{node_revision}/view'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::revisionShow'
    _title_callback: '\Drupal\node\Controller\NodeController::revisionPageTitle'
  requirements:
    _access_node_revision: 'view'
    node: \d+

node.revision_revert_confirm:
  path: '/node/{node}/revisions/{node_revision}/revert'
  defaults:
    _form: '\Drupal\node\Form\NodeRevisionRevertForm'
    _title: 'Revert to earlier revision'
  requirements:
    _access_node_revision: 'update'
    node: \d+
  options:
    _node_operation_route: TRUE

node.revision_revert_translation_confirm:
  path: '/node/{node}/revisions/{node_revision}/revert/{langcode}'
  defaults:
    _form: '\Drupal\node\Form\NodeRevisionRevertTranslationForm'
    _title: 'Revert to earlier revision of a translation'
  requirements:
    _access_node_revision: 'update'
    node: \d+
  options:
    _node_operation_route: TRUE

node.revision_delete_confirm:
  path: '/node/{node}/revisions/{node_revision}/delete'
  defaults:
    _form: '\Drupal\node\Form\NodeRevisionDeleteForm'
    _title: 'Delete earlier revision'
  requirements:
    _access_node_revision: 'delete'
    node: \d+
  options:
    _node_operation_route: TRUE

The entity class should also extend EditorialContentEntityBase, a base entity class with extended revision and publishing support. Using it, adding the revision and publishing fields is simple as adding $fields = parent::baseFieldDefinitions($entity_type); to the baseFieldDefinitions() method of the entity class.


Alter Block render array and add another block's content I am attempting to attach a block to another block via hook_block_view_alter. The source block is a menu_block and the block to be attached is a view block, but the type of block shouldn't matter to the solution.

Here is the code used to attach the block. Assume that block_attached_block is populated with the bid of the block and at the point where I am altering the render array I have a fully rendered block.

function MODULE_block_view_alter(&$data, $block) {
  if (!empty($block->block_attached_block)) {

    // load the attached block from the database
    $attached_block = db_select('block', 'b')
      ->fields('b')
      ->condition('b.bid', $block->block_attached_block)
      ->execute()
      ->fetchObject();

    // render the block
    $block_content  = _block_render_blocks(array($attached_block));
    $build          = _block_get_renderable_array($block_content);
    $block_rendered = drupal_render($build);

    // attach the block
    $data['block_attached_block'] = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('block_attached_block'),
      ),
      'block' => array(
        '#markup' => $block_rendered,
      ),
    );
  }
}

If I render $data at this point I see the attached block rendered perfectly.

drupal_render($data);

However, when I load the page the attached block is missing. The documentation is pretty light.

My question is how do I get the rendered block to output on the page.

Here is an updated function taking into account some of the various types of blocks that we can attach blocks to.

function MODULE_block_view_alter(&$data, $block) {
  if (!empty($block->block_attached_block)) {

    // load the attached block from the database
    $attached_block = db_select('block', 'b')
      ->fields('b')
      ->condition('b.bid', $block->block_attached_block)
      ->execute()
      ->fetchObject();

    // render the block
    $block_content = _block_render_blocks(array($attached_block));
    $build         = _block_get_renderable_array($block_content);

    // create attached block render array
    $block_attached_block = array(
      '#type' => 'container',
      '#attributes' => array(
        'class' => array('block_attached_block'),
      ),
      'block' => $build,
    );

    // attach the block
    switch ($block->module) {

      // menu block module blocks
      case 'menu_block':
        $data['content']['#content']['block_attached_block'] = $block_attached_block;
        break;

      // views module blocks
      case 'views':
        $data['content']['#markup'] .= drupal_render($block_attached_block);
        break;

      // block module blocks
      // webform module blocks
      case 'block':
      case 'webform':
        $data['content'] .= drupal_render($block_attached_block);
        break;

      // all other module blocks
      default:
        $data['content']['block_attached_block'] = $block_attached_block;
        break;
    }
  }
}

Thanks Clive for getting me started on the right path.


Accessing user's custom field in html.tpl.php In my html.tpl.php , I was printing this:

    print $user->name;

which displayed username.

But now I need to print Custom field "First Name" instead of username.

So I tried this:

   print $user->field_first_name[und][0]['value'];

which is not printing anything  although the field "First Name" has some value.

Where am I going wrong ? Am I missing some obvious thing ?

Thank you .

If you are using the global variable $user, it doesn't always contain a full initialized object. In fact, during the bootstrap, $user is initialized with the data contained in the "users" table, from the following code.

  if ($is_https) {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
    if (!$user) {
      if (isset($_COOKIE[$insecure_session_name])) {
        $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
          ':sid' => $_COOKIE[$insecure_session_name],
        ))
        ->fetchObject();
      }
    }
  }
  else {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
  }

  // We found the client's session record and they are an authenticated,
  // active user.
  if ($user && $user->uid > 0 && $user->status == 1) {
    // This is done to unserialize the data member of $user.
    $user->data = unserialize($user->data);

    // Add roles element to $user.
    $user->roles = array();
    $user->roles[DRUPAL_AUTHENTICATED_RID] = 'authenticated user';
    $user->roles += db_query("SELECT r.rid, r.name FROM {role} r INNER JOIN {users_roles} ur ON ur.rid = r.rid WHERE ur.uid = :uid", array(':uid' => $user->uid))->fetchAllKeyed(0, 1);
  }

If you want to be sure to get a fully loaded user object for the currently logged-in user, you should use the following code.

$account = user_uid_optional_load();

After that, you can get the value of any user field.

$fullname = field_get_items('user', $account, 'field_first_name');

You can also get the rendered value of the field using the following code.

$rendered_value = field_view_field('user', $account, 'field_first_name');

The other reason for which $user->field_first_name['und'][0]['value'] could not contain any value is that the language-neutral value of the field is not be set. ('und' is the value of the constant LANGUAGE_NONE, or LANGUAGE_NOT_SPECIFIED in Drupal 8.) If you use field_get_items(), or field_view_field(), you are sure to get the correct value.

As side note, it is preferable to keep the logic in the template.php file, in functions that are called from the template files.


How to use expert class settings for display suite for images? I've tried different combinations, but it's now working or showing up in chrome inspector...

I'm also using Bootstrap template, could that by a problem?

Or maybe I'm not filling out the information correctly in the field boxes?

Have you tried  Image Class.

  Extends the Image formatter by adding an option to add an element
  class.

It does not work in combination with Display Suite unfortunately as per this post: Merge Image Class into Display Suite


Dropdown as an unexposed field in views I'm developing a complaint portal for administration. All complaints are submitted by sites users. I'm fetching these complaints using views and don't know how to add active/Inactive as drop down options in each complaint. As everybody knows complaints' status stays active until it resolves. Active/inactive field is not existed in content type form.

This is for admin ease, admin can change the status of the complaint active or inactive.

Please let know if anyone has any experience regarding this.

You can use the Field Permissions module according to module's page:

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

Then set permissions for your active/inactive field to be for admins only, then the field will not show for general users but admins will be able to change the status when they view each complaint.


Does db_affected_rows() works well with PostgreSQL? This is a clean installation and I was starting to develop a module.
So I have the following code (and nothing more apart from the hook_menu()):

$result = db_query("SELECT * FROM {variable}");
return db_affected_rows();

I used the variable table as an example since it was likely to be populated (and it is, of course!). Well, to my surprise db_affected_rows() always returns 0.
Is there any reason why it doesn't work? Are there any reported bugs that I may have missed?

Setup:

Drupal 6.22
PostgreSQL 8.4
PHP 5.3.8

To summarize for Drupal 6:

db_affected_rows() gives you number of rows returned by a select if the database is MySQL but not if it's PostgreSQL.
In Drupal 6 if you are using PostgreSQL you can run pg_num_rows() on the query to get the number of rows.

It is indeed database specific.

[Reference: this comment in the Drupal documentation]


How can I make Apache Solr Autocomplete work in search Views? I'm trying to work with Apache Solr search in my view and make this autocomplete.

Apache solr is configured correctly and I've added a solr view. I can search on fields, that's no problem. But how can I make the autocomplete work?

Have you tried to search in google? before asking. Have you tried to do anything?
 I noticed you're constantly asking questions to which the answer can be found by spending a little time searching.
Try to do something by yourself before asking. thanks.

ApacheSolr Autocomplete module - This module should solve your problem.


How to programmatically add a user to a group in Drupal 7 I am trying to programmatically create a group node and add a user to that group in Drupal 7. The group node is being created just fine but the user is not being added to the group and I am not getting any errors. I am guessing I am using the og_group function incorrectly but I am not sure. What am I doing wrong?

function MYMODULE_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1;
    $node->promote      = 0;
    $node->comment      = 1;

    $node->og_description   = t("OG Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    $account = user_load(2);

    og_group($node->nid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => "OG_MEMBERSHIP_TYPE_DEFAULT",
            ));

    drupal_set_message(t("Finished"));
}

I figured it out. It ended up not working because the group ID is NOT the same as the node ID for that organic group. Here is the working version:

function MYMODULE_page_form_submit($form_id, $form_values) {
    global $user;

    $node = new stdClass();

    $node->type     = "group";
    $node->uid      = $user->uid;
    $node->title        = t("Group Node Title");
    $node->body     = t("Group Node Body");
    $node->status       = 1; //(1 or 0): published or not
    $node->promote      = 0; //(1 or 0): promoted to front page
    $node->comment      = 1; //2 = comments on, 1 = comments off

    $node->og_description   = t("OD Description");
    $node->og_register  = 0;
    $node->og_directory = 0;
    $node->og_private   = 1;
    $node->og_selective = 3;

    $node = node_submit($node);
    node_save($node);

    // Get the group ID from the node ID
    $group = og_get_group("node", $node->nid);

    // Load the user we want to add to the group (ID #2 was my test user)
    $account = user_load(2);

    // Add the user to the group
    og_group($group->gid, array(
                "entity type"       => "user",
                "entity"        => $account,
                "membership type"   => OG_MEMBERSHIP_TYPE_DEFAULT,
            ));

    // Changes the users role in the group (1 = non-member, 2 = member, 3 = administrator member)
    og_role_grant($group->gid, $account->uid, 3);

    drupal_set_message(t("Finished"));
}


Get all user profiles from list of users I am evaluating some custom code in a rule. I want to get a list of users, then load all of the associated profiles from the profile2 module. My code below, loads all the users, and I got an array of the UIDs to put into the profile_load_multiple() function but it is just returning one user profile, I want to return all profiles. Eventually I want to compare a term from a field (project resources) in the node 'project' I am creating with a field (resources) that is in each user main profile.  My intention is  using rules to accomplish this.

$users = entity_load('user');
$arrayuids = array();
foreach ($users as $user)
{
array_push($arrayuids, $user->uid);
}
$profile = profile2_load_multiple($arrayuids, FALSE);
dsm($arrayuids);
dsm($profile);

Your first problem is that you send uids instead of pids. First argument of profile2_load_multiple is $pids which are profile2 ids.

Try this code:

$users = entity_load('user');
$arrayuids = array_keys($users);

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'profile2')
    ->propertyCondition('uid', $arrayuids, 'IN');

$profile = $query->execute();

dsm($arrayuids);
dsm($profile);

I haven't tested it but it should work.


Google Analytics Drupal browser "Drupal" is showing in our Google Analytics as the top browser. We're using Drupal 7 with the google_analytics module. What could cause this?

Do you use many modal frames or many functions like $result = drupal_http_request($url, $options); on your site?

In both these cases the user agent is set to "Drupal".


db_update() with joins Is there any way to db_update() for the following query?

UPDATE field_data_field_TEST as ft
left join node as n on ft.entity_id = n.nid
set n.type='test'
where n.type='foo'

I tried using db_update()->join(); but it didn't work.

db_update() doesn't implement any interfaces that have join()/innerJoin()/etc. methods so I think you're stuck with using db_query() and writing the query string out manually.

$sql = "
  UPDATE field_data_field_TEST as ft
  left join node as n on ft.entity_id = n.nid
  set n.type = :type1
  where n.type = :type2";

$args = array(':type1' => 'test', ':type2' => 'foo');
db_query($sql, $args);


Where is documentation for $entity->data property? I.e. $commerce_order->data I've searched google and the Drupal API, but I can't seem to find documentation for the data array that serializes/unserializes automatically that is attached to entities and stored in the data column on some entities, particularly commerce_order. Searching for the world "data" is like searching for the word "the." Where/how is the data array serialized and unserialized?

The data attribute is part of the Commerce Entity definitions, and I think this might be part of the larger de facto Entity API setup for contrib entities (don't quote me on that ;).)
If you want to find the documentation on properties and how they are handled you need to review the EntityController class, which each Commerce module has in its includes folder.
commerce_order.controller.inc#n135
/**
 * Unserializes the data property of loaded orders.
 */
public function attachLoad(&$queried_orders, $revision_id = FALSE) {
  foreach ($queried_orders as $order_id => &$order) {
    $order->data = unserialize($order->data);
}

The database layer automatically serializes, if I recall correctly. However controllers need to unserialize.
Hopefully this this question and other entity related items (also make sure to review hook_entity_info() implementation.)


Display custom comment field in admin I created some custom fields for the comment form for specific content types.

One field for instance is the email fields, it's used to contact posts after they won a contest.

But when I look at the comments in the admin, there is no option to view these custom fields.
Is there a way to change this?

So I want to add custom fields to the admin overlay for comments

I think you could create a view for that, and select which fields to show.


node_save not responding inside module Drupal: 7.31
Php: 5.5.9-1ubuntu4.3

I am trying to create node type 'recibo_promocion_type', after create nodes of type 'offer_type' (diferent type).
I am using hook_node_presave.
I run the code in the development environment 'run php code', successfully, but the same code within in my personal module does not respond, getting a blank page.
I did debug and the line of code that fails is 'node_save ($node)'.

function nuevo_Recibo_Promocion($nid, $uid, $ruta){

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
$nodeConfigura=node_load($nid);
$node = new stdClass();
$node->nid=0;
$node->type = 'recibo_promocion_type';
$node->uid = $user->uid;
$node->name = $user->name;
$node->title = $nodeConfigura->title;
$node->language = 'es';
$node->field_organizacion = $nodeConfigura->field_organizacion;
$node->field_enlace['und'][0]['url']=$ruta;
$node->field_enlace['und'][0]['title']=$nodeConfigura->title;
$node->field_enlace['und'][0]['attributes']['target']=0;
$node->field_fecha_promocion = $nodeConfigura->field_fecha_promocion;
$node->field_cliente_envio['und'][0]['target_id'] = $uid;
node_object_prepare($node);
$node = node_submit($node);
node_save($node);

}

This is the test code with moc parameters from 'ejecute code php' of dev module, and save node successfully.
The moc parameters was extrated from dpm($node) replace save_node($node) in a module.

//moc paraeters
$ruta='http://...';
$uid=184;
$nid =81;

$nodeConfigura=node_load($nid);
$node = new stdClass();
$node->type = 'recibo_promocion_type';
$node->uid = 1;
$node->title = $nodeConfigura->title;
$node->language = 'es';
$node->field_organizacion = $nodeConfigura->field_organizacion;
$node->field_enlace['und'][0]['url']=$ruta;
$node->field_enlace['und'][0]['title']=$nodeConfigura->title;
$node->field_enlace['und'][0]['attributes']['target']=0;
$node->field_fecha_promocion = $nodeConfigura->field_fecha_promocion;
$node->field_cliente_envio['und'][0]['target_id'] = $uid;

node_object_prepare($node);
$node = node_submit($node);
node_save($node);

the node save successfully.

This is the result to repace 'node_save($node)' for 'dpm($node)' in function  'nuevo_Recibo_Promocion' inside my module:

I tried also:

1)Use drupal_register_shutdown_function but the bug is the same.

2)I have created  a xmlrpc service, and replace instead the nuevo_Recibo_Promocion call function.
The xmlrpc creates successfully the node, but if it's invoked  from 'execute php code' (dev module). if xmlrpc it's invoked  from  from my module, it doesn't created the new node.

$methods = xmlrpc('http://...', array('reciboPromocion.new' => array($nid,$ruta,$uid)));

3) I have disabled all my modules to avoid confict with othes modules (loops Infinite)

4) use try{} catch(exception $e){}... to get the bug.

5) use hock_cron(), but not save the new node.

6) I've tried the user custom permissions, the function node_access($node) before node_save ($node) in two cases: my personal module  and dev console 'Run PHP code'. The result is true in all cases.

The question for  is, why  the process do not shoot any exception, alert, or notify, The result is a don't response and 'blank page' in my web browser.

any suggestion?

When you are doing node_save() inside hook_node_presave, it will trigger hook_node_presave where you have node_save()...

You could move the node_save else where. Perhaps if your using form in creating the original node just add submit handler in case the node type matches? Or some other way to by pass the infinite loop.


Organizing common functions/classes Currently I have a common.module for storing common functions.  This file is getting way to long and I'd like to start breaking it up by similar functionality or by class:

common.inc
common.query.inc
common.taxonomy.inc
Node.php
etc...

I thought I could add files[] entries to my common.info file but this doesn't seem to source these files.

I need these files to be always sourced: on any page load, on full drupal bootstrap, and on update.php.

In your .module file add the following to the very top of the module (just after the opening <?php tag):

module_load_include('inc', 'common', 'common.query');
module_load_include('inc', 'common', 'common.taxonomy');

For your reference:

module_load_include();

EDIT

Seeing as how you're not going to be needing these on cached pages, then putting them in hook_init() is much better practice.

Like the following:

function common_init() {
  module_load_include('inc', 'common', 'common.query');
  module_load_include('inc', 'common', 'common.taxonomy');
}


"Questions that may already have your answer" Stackexhange Module For Drupal is there a module for drupal
when you write a title to a question it suggest the answer i.e

"Questions that may already have your answer" on Stackexhange

Many thanks for your help

If a 'Question' is a node, you could use the Similar Entries module as a starting point:

  Similar Entries provides lists of links to site content related to the current node being viewed. Links can be displayed in standard blocks or as part of custom views. Similar content is located and rated using MySQL's FULLTEXT indexing for MyISAM tables. FULLTEXT is a special query that helps find relevant content in other nodes using a natural language search that interprets the search string as a phrase in natural human language.

It will require some customisation to get a similar workflow to the one Stack Exchange uses (you'll need to make the blocks appear on the node add/edit pages somehow, and implement an AJAX solution for suggestions while writing the title).

I'd be surprised if there's a module which replicates the functionality here straight out of the box.


How can I pass an empty case subject from Webform CiviCRM integration to CiviCRM? I am using Drupal 7 and CiviCRM 4.4.2. I have created a form with Webform CiviCRM integration that creates a new case. However, the case subject should be generated in CiviCRM, based on a standard pattern. The code replaces {contactName}-{caseType}-{caseId} with the values in the civicrm_post hook.
How do I set the default value of the case subject in the Webform whilst not showing the field on the webform?

In the webform, give the field the default value that you want to use, and then change the field widget to 'Hidden' so that the field is not exposed to the user on the form. The default value will then be submitted, and subsequently modified/overridden by your hook.


How do I fix an uncaught TypeError? I am using Drupal 8.1.8. It is giving me many JavaScript errors.

Uncaught TypeError: Cannot read property 'permissionsHash' of undefined
Uncaught TypeError: Cannot set property 'StateModel' of undefined
Uncaught TypeError: Cannot set property 'AuralView' of undefined
Uncaught TypeError: Cannot set property 'KeyboardView' of undefined
Uncaught TypeError: Cannot set property 'RegionView' of undefined
Uncaught TypeError: Cannot set property 'VisualView' of undefined
Uncaught TypeError: Cannot read property 'uid' of undefined
Uncaught TypeError: Cannot read property 'currentPath' of undefined
Uncaught TypeError: Cannot read property 'currentPathIsAdmin' of undefined
Uncaught TypeError: Cannot read property 'url' of undefined
Uncaught TypeError: Cannot read property 'currentQuery' of undefined

There is no error in my local copy, but it happen when I uploaded in live hosting.

How can I fix this?

All the properties can be searched and found from the code in Drupal core. And they seems to be the properties of drupalSettings object in JS.

This object is initialised in core/misc/drupalSettingsLoader.js.

(function () {

  'use strict';

  // Use direct child elements to harden against XSS exploits when CSP is on.
  var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');

  ....

This code explained that the drupalSettings is contained in

<script type="application/json" data-drupal-selector="drupal-settings-json">

And it must be under <head> or <body>.

I suspect that your <script> tag is wrapped in other element. Please check your template files and remove the wrappers or check if there is a content with missing closing tag.


How to create file->node relations use relations modules? I have a little issue that How to create file->node relations use relations modules?

In my case:
   I need to create music(mp3) and album relations. After i check some information and said that music(mp3) and album is file->node relations.

But, i don't know that how to do this relations.

when i create a relation type, which bundles need to selected?

[Resolved]
1. Create relation between Node and file
2. Create a view for relation and only view out all related file
3. setting view to relation select values


How to get plugin configuration through plugin manager? I have defined plugin manager and I have installed two plugins, I am getting plugins name and id by $plugins = $this->pluginManager->getDefinitions(); but I need to access its configurations and display whether this property is enabled or not with an edit button. How to do it?

The plugin manager is not responsible for storing the configuration, that happens somewhere else.

Typically plugin configuration is then stored in a config entity, either in a 1:1 relation (e.g. blocks) or 1:n (e.g. views, view/form displays, filter formats).

I'd suggest that you look at those modules to see how they work, block is probably one of the simpler cases in core. You can also ask more specific questions if you're stuck on implementing that


Placing a menu based on a page’s taxonomy I created a Drupal menu and place the resultant block in the left sidebar. On the block configuration page I went to “Show block on specific pages” > “Show if the following PHP code returns TRUE (PHP-mode, experts only).” and added the following code:

$tid = 0;
$desired_tid = 12;  // Change to the tid you want
$node = menu_get_object();
if ( !empty($node) && !empty($node->taxonomy) ) {
  foreach ( $node->taxonomy as $term ) {
    if ( $term->tid == $desired_tid ) {
       $tid = $term->tid;
       break;
    }
  }
}
return $tid;

The menu still showed up on all pages and not just the page that had the taxonomic term that had ID=12.

I then tried using the code:

$desired_tid = 12;  // Change to the tid you want
$node = menu_get_object();
if ( !empty($node) && !empty($node->taxonomy) ) {
  foreach ( $node->taxonomy as $term ) {
    if ( $term->tid == $desired_tid ) {
      return TRUE;
    }
  }
}

Same effect, the menu still was on all pages. I have disabled caching, flushed the cache, and rebooted the server, all to no affect. Any idea what I might be doing wrong?

If you will put more blocks based on taxonomies or maybe for certain content type i would recommend the context module:

http://drupal.org/project/context

With context you can set conditions with a friendly UI  for display blocks in your drupal instalation.


Is there a Drupal 6 equivalent to template_preprocess_taxonomy_term()? Is there a Drupal 6 equivalent to the method template_preprocess_taxonomy_term()? I'm looking to add some code that will provide some additional links on my taxonomy term pages and want to keep the code in template.php (don't like code in my templates themselves).

Managed to eventually figure this out myself. I'm using the following in template.php to identify a taxonomy term page in D6:-

<?php
function THEME_preprocess_page(&$vars) {
  if (arg(0)=='taxonomy' && arg(1)=='term') {
    // do something
  }
}
?>


Different shipping $ for west coast Let me just preface this by saying I know nothing of Drupal. I am a wordpress developer but my company just inherited 2 drupal sites from a company we recently purchased. I am using Drupal 6.25.
I have 2 classes of products that I need to change shipping for. It's free for US east coast and $199 for US west coast.  There was a generic free shipping already set up and working but I need to change for the shipping increases. I tried using the flat rate and conditions but I kept getting "Invalid option selected. Recalculate shipping quotes to continue". I set up west coast fine. I did 2 groupings -  a main AND group with 2 OR groups in that - 'or' for the shipping states and 'or' for the 2 product classes. I disabled the previous free shipping and the west coast works fine. I set up a separate shipping for east coast just like the west coast but opposite states. It works fine if I disable the West Coast. So, obviously I am doing something that is conflicting when both are enabled.

Any and all advice is greatly appreciated!

This is not an answer, just advice: Drupal 6 has been unsupported since February of 2016 - close to 4 years now. I strongly suggest you spend your efforts upgrading to Drupal 7 right now, if nothing else because of all the security fixes (which are super important on an e-commerce site!).

The D6 -> D7 upgrade is relatively easy to do for most sites. I do not recommend going directly to Drupal 8 right now because that will be very long and painful process especially if you have little Drupal experience. If you want to move to D8, it would probably be easier to rebuild the site from scratch.


Add/Remove User Role on Node View I want to be able to add and remove a role to a user via a simple click of a button on almost any node. (Specifically the plan is to allow a user to give themselves a role that would give them extra editing powers, but so that they can remove it when generally browsing the site so all the editing options don't clog up the UI).

The best method I could think of for this is to have two nodes, and set up a rule so visiting these nodes added or removed the user role. I could then create simple menu links that linked to these nodes.

Essentially what I have set up is one rule which goes:

Event: Content is Viewed
Condition: Node is of alias - node url
Action: Add user role - Edit Powers

This rule works fine. When the node is visited the role is added to the user. However the reverse rule doesn't work despite being nearly identical to the other. It reads:

Event: Content is viewed
Conidtion: Node is of alias - node url
Action: Remove user role - Edit Powers

However visiting this URL doesn't remove the user role. The question here is two-fold.

a) Why would the rule not be working, and why can't it remove a role from the user?

b) Is this a really complex way of achieving something that might be quite simple? At the moment I assume this rule is effectively being checked when any user visits any page, which I'm sure isn't great from a resource point of view - but I couldn't think of an easier way to do it with flags etc. So please do advise if there is an easier way.

Thanks in advance for any help.

Try creating a condition that the user have the role, before trying to remove it.
Also, you could look into Rules Link - you may be able to add it to a custom Profile Page, allowing the user to access and change their settings via My Account - at least from a UI standpoint it might make more sense.


How do I hide a field after login? Could anyone tell me how I can hide a field after user login? For example, at the top of my front page I have:

  login | register

However, upon successful login, I would to hide this field.

The above 'login | register' field is just a 'div' block with 'href'.
One good example is the hiding of the default Drupal login block after login in.

I am using Drupal 7.

If you're outputting this directly in a template file it would be as simple as:

<?php if (user_is_anonymous()) : ?>

login | register

<?php endif; ?>

If you're using a block then you most likely won't want to put PHP code directly into it as that would involve using the evil eval() function. Instead you could add a new menu and use the block that's automatically created for that menu to output the links.

Since the menu system respects permissions, and the logged in users don't have access to the register or login page, the links simply won't show when a user is logged in.


Paragraphs: referenced entity error on save I recently updated to Drupal 8.6.2 and Paragraphs 8.x-1.3.

I have a content type with a Paragraphs field. When I try to update an existing node I get the following error message:

The referenced entity (user: 21) does not exist.

The existing paragraphs do not reference users directly.
User 21 does not exist.
User 21 is not the node author.
I can only update the node if delete all of the paragraphs, of every type.
There are no pending db updates or entity updates.

My feeling is that something didn't update correctly, but I'm not sure how to check / rerun the updates. (There were a number of updates to be run when I deployed the 8.6.2 update.)

UPDATE: I rolled back to the previous release and DB state, and I still get the error (which no one noticed), so it is not related to the update.

UPDATE 2: Ticket on drupal.org

User 21 was deleted, but 21 was still stored as the value in the uid column of the paragraphs tables. Changing the uid to that of an existing user (23) solved the problem:

UPDATE paragraphs_item_field_data SET uid = 23 WHERE uid = 21;
UPDATE paragraphs_item_revision SET revision_uid = 23 WHERE revision_uid = 21;
UPDATE paragraphs_item_revision_field_data SET uid = 23 WHERE uid = 21;

Run SQL, empty cache, reload edit page.

Note: other tables also contain the uid 21, but without a (noticeable) adverse effect.

UPDATE file_managed SET uid = 23 where uid = 21;
UPDATE node_field_data SET uid = 23 where uid = 21;
UPDATE node_field_revision SET uid = 23 where uid = 21;
UPDATE node_revision SET revision_uid = 23 where revision_uid = 21;

And two from contrib:

UPDATE crop_revision SET revision_uid = 23 where revision_uid = 21;
UPDATE redirect SET uid = 23 where uid = 21;


Views: Trying to filter content by two field values (either/or)? I'm trying to filter published content by the values set inside of two fields (one or the other). Right now, I'm successfully filtering my content by one field:

Contextual Filter

  If field_targetuser = logged in uid, than display content.

However, I also want to show content in which field_universal = YES , regardless of the logged in uid.

Naturally, implementing the first Contextual Filter and than a second only further filters the intial filter. What I'm trying to accomplish:

  Show all content of this type if targetuser matches logged in user id,
  but ALSO show all content where field_universal = YES, regardless of what appears in the targetuser id.

Views setup:

You can solve this without any additional modules or coding, just with pure Views + Entity Reference. Here is how:

You need to add 1 more relationship to your current View (looking at your screenshot):

Entity Reference: Targeted User => This is the Entity Reference field that points to a User, what you call "targetuser"

You need to add a "User: Current" filter to your view. Once you click on that, you should see the following:

This filter will allow you to select only the nodes where the targeteduser is the same as the logged-in (current) user.
You need to place the universalswap in an OR relationship to the new filter inside a FILTER GROUP. Then place that group in an AND relationship to the rest of your filters, i.e. Type = Messages.

That should do it without any additional modules.
Here is a screenshot of my final View configuration:

I am logged in as admin (uid:1) and you can see in the results that I am getting all messages that are either "Universal" or targeted at me.

Good luck!


How to build a user authentication workflow with AngularJS using RESTful module? I'm building a single page app with AngularJS and Drupal as the backend. I'm using the RESTful module. However, I do not have much to go on to build a user authentication workflow.

There are several techniques to authenticate users with a SPA. For example, storing session information in a cookie or in a token. In order to keep a persistent authentication with a token, AngularJS stores the token in local storage. I've been reading that this causes security risks because other scripts are able to access local storage.

Also, RESTful comes with a token authentication module which stores tokens on the server.

The first question is which form of persistent authentication to use? Do I have to completely make the SPA headless Drupal? If the app is headless, using token authentication, do I have to completely remove all the out of box user authentication workflow, for example, resetting a user's password, from the app? Is there a hybrid solution? If the information is being consumed and altered by mobile apps and other non standard means, is using cookie authentication out of the question? If that is the case, on a desktop app, how do I prevent users from accessing user URIs? Basically, I have no clue what is going on and there isn't much information about secure solutions.

Do headless means no layout and block display at all ?
i believe u can leave CAS drupal module do the job ( and a connection menu )


Why does menu items start disappearing In Drupal 7 some menu items, even though they exist in menu_links db table, do not appear in the menu. I wonder if it has something to do with cache, but I have disabled the cache and cleared it.

If I add a menu item that goes for instance to <front>, it appears in the menu, but if I add a menu item for a certain node, it does not appear. I can't find the logical reason for it.

The only reason I can think of is that the viewing user does not have access to the linked node. Internal menu links that point to unauthorised content do not appear in menu.

Make sure the node has been published and your user can view it.

Some people actually consider dolbydolby's work around a bug :-) http://drupal.org/node/483150


Drupal 6 site updates are not been applied I have a Drupal 6 site running fine, but when trying to apply updates to its modules by uploading the latest version of the module and visiting update.php the update process complete, but when I check the available updates report it still show me the old module versions marking them as outdate.

I can read and write in the DB, and I can upload files to the server so it is not a DB  or file permission.

Can you explain why the updates are not being applied/seen?

Did you clear the cache?

Are you sure you are updating the right modules? Drush for example will place modules in sites/all/modules, but if your modules are placed in profiles/profile/modules Drupal might still be reading the old modules.
Drupal won't complain if you are having duplicates, only on enabling.

Can you confirm the modules are read? Check the database, are the module path correct? Is the info file of you modules showing the correct version?


How to alter the parameters in the core.services.yml file programatically? I need to modify the filter_protocols parameter inside the core.services.yml file programmatically to add a new protocol. I know how to alter a service but I don't find any information about how to alter a parameter.
parameters:
  session.storage.options:
    gc_probability: 1
    gc_divisor: 100
    gc_maxlifetime: 200000
    cookie_lifetime: 2000000
  twig.config:
    debug: false
    auto_reload: null
    cache: true
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']
    auto_placeholder_conditions:
      max-age: 0
      contexts: ['session', 'user']
      tags: []
  factory.keyvalue:
    default: keyvalue.database
  http.response.debug_cacheability_headers: false
  factory.keyvalue.expirable:
    default: keyvalue.expirable.database
  filter_protocols:
    - http
    - https
    - ftp
    - news
    - nntp
    - tel
    - telnet
    - mailto
    - irc
    - ssh
    - sftp
    - webcal
    - rtsp

I know how to do this by copying the services.yml file inside the sites/default folder but at this time I need to do this programmatically.
Any idea about how to do it?

You need a compiler pass:

Compiler passes give you an opportunity to manipulate other service
definitions that have been registered with the service container.

There are some Drupal specifics. An example which calculates a container parameter depending on tagged services is RegisterSerializationClassesCompilerPass. This class is registered in SerializationServiceProvider.
For simple use cases, where you don't need control over compiler pass priorities, you can use the alter() method of ServiceModifierInterface. This will then be executed in a shared core compiler pass ModifyServiceDefinitionsPass.
Example for adding foo to the filter protocols:
src/MymoduleServiceProvider.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Defines a service provider for the Mymodule module.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $filter_protocols = $container->getParameter('filter_protocols');
    $filter_protocols[] = 'foo';
    $container->setParameter('filter_protocols', $filter_protocols);
  }

}


trouble with a checkbox on the user registration pages I created an extra checkbox field for the user registration form

This is the field setting page. (Standaardwaarde means "Default value.")

In the setting page, the field is unchecked, but it's checked in the registration page. I looked at some older questions regarding this subject, but it still a big questions mark for me.

How can I get the checkbox to be unchecked by default?

Found the answer. The problem was that I selected the wrong field type. I think because it is only one field you need to select a Boolean type. Now it's working!


Drupal 7 form alter required field is not working when i used field from "Add existing field" I have added two fields in to my custom content type using "Add existing field".

For specific URL, I need to set these two fields as Required.

So I have altered my form and set required condition. After setting it, I have printed the form using devel, these fields are having required settings.

$form['field_name']['und']['#required'] = TRUE;
$form['field_email']['und']['#required'] = 1;
dsm($form);

But required condition is not applied.

That is, I could not see red color required indication as well as its not working in the form submit.

Try

$form['field_email']['und']['0']['value']['#required'] = TRUE;

and if not work then try

$form['field_email']['und']['0']['#required'] = TRUE;


Fatal error when calling drupal_goto from hook_boot When I am trying to call drupal_goto from hook_boot I get an error:

  Fatal error: Call to undefined function drupal_goto()

What am I doing wrong and why is that happening?

My code:

function custom_mobile_redirect_boot() {
  include_once 'Mobile_Detect.php';
  $detect = new Mobile_Detect();
  if ($detect->isMobile() || $detect->isTablet()) {
    drupal_goto('http://testsite.local');
  }
}

In hook_boot() lot of APIs will not work as the required function definitions for them will not be loaded. In this case common.inc where drupal_goto() is defined is not yet included ergo you get that error. If its not possible to use hook_init() make use of Header. Check out mobile_tools module hook_boot() for more info.


Can drupal commerce products become cheaper to the customer when they order more? I would like to set up a shop to sell custom made products, all variations on the same base product.
The greater the number of tasks I have to do to get the product ready, the more expensive the product.

Some of these task do not require set up time for an order, but some tasks do.

Can drupal commerce take calculate the cost per item for a variation per product and the costs per order and turn those in to a sell price (the only price) the customer can see, based on the number of products they want to order?

Example:

Let's say, the products are cubes.

I can make a cube out of wood or plastic.
I can finish them by just sanding them, or paint them, or cover them in fabric.

Just sanding them is the quickest and thus the cheapest. Painting takes more time and is more expensive. Black is more difficult to get right then white, so again, is more expensive.

But also, painting not only takes time for the painting itself, it takes setup time for the whole order AND for every layer.

I would like to configure the products so that I can include most of these price factors in to the price the customer sees in the shop as they are changing the number they may want to order.

Because my typical order quantity is between 1 and 10, those diferences make a big difference in the price.

Can this kind of calculations be done with drupal commerce out of the box or with contributed modules, or would this require coding?

Assuming you're on Drupal 7 yes, I've done this with the Commerce Price Table module: https://www.drupal.org/project/commerce_price_table

"This is a contributed module for Drupal Commerce that allows you to use a secondary price field to supply an alternate price for a product based on the quantity of that product on the line item. It also provides a field formatter to display the price/quantity values as a table."


Second product attribute resets if first product attribute is changed I have a tshirt product on my Drupal Commerce webstore. The shirt has these options, in this order:

Size /
Color /
Sleeve Length

All shirts are available in all sizes/colors/sleeve lengths, so any combination of those three fields will yield a valid product.

If I choose a size, then a color, and then a sleeve length, there are no issues. However, if I choose a color first, and then choose a size, it resets my color to the original, default color. The same thing happens if I choose a sleeve length first and then change one of the other options.

Is there any way to fix this behavior so that the customer doesn't lose their selections? I'm afraid that they might not realize that their previously-selected options have been reverted to the defaults and I might end up with orders for the wrong size, color, or sleeve length.

Thanks!

This is addressed in a pending feature request that probably just needs a little more patch review before being committed to Drupal Commerce: https://www.drupal.org/node/1286244


How to print a variable set in my custom module's inc file in node-contenttype.tpl.php I am trying to grab all links under id="ctl00_ctl00_MainPlaceHolder_MainPlaceHolder_TaobaoLink".

Here is the function used in my custom module file:

function _taobao_add_tovar($url){
  $url = str_replace('&amp;','&',$url);
  $tovar_page = _taobao_get_page('http://rutaobao.com/pages/item_detail.aspx?ItemId='.urldecode($url));

  $linkz = _taobao_get_block($tovar_page, '"ctl00_ctl00_MainPlaceHolder_MainPlaceHolder_TaobaoLink" title="Открыть оригинальную страницу этого товара на taobao.com">');
  preg_match_all('%<a [^>]+href="(?P<url>[^"]+)"[^>*]*>(?P<text>[^< ]+)</a>%si', $tovar_page, $linkz);
}

I've set the $linkz variable. How can I print it in node-mycontenttype.tpl.php?

To get a variable to a custom node.tpl.php you need to do this in MODULE_preprocess_node(&$variables) usually this is done in your template.php file located inside your themes directory, however, because you are calling a private function _taobao_get_page(), I think you need it inside your module.

Something like

MODULE_preprocess_node(&$variables) {
   if ($node->type == 'mycontenttype') {
      $variables['linkz'] = X;
   }
}

Now you can call $linkz inside your tpl.php file


How to use CKEditor on the front-end? CKEditor do not work on one specific theme, it works fine in the back-end and also when I switch the theme.

When I look the sources, I get the JS & CSS, ckeditor class on textarea but not the injected code that CKE add under each textbox with id="cke_edit-body".

What can be the sources of the problem?

I know it's not jQuery, I found similar issues but they were provoked by a custom jQuery update, I use 1.3.2

On Input filter option (admin/settings/filters) you can check the user permission for each type of input filter you have on the site.

Then if you are using the WYSIWYG module, at admin/settings/wysiwyg you can check which type of editor is using each input filter.

If the WYSIWYG editor is working for anonymous user on one theme but not on the other, you could also check (with Firebug or Chrome DevTools) if there are Javascript errors. If that is the case, please, update this post with the error message.


How to integrate Lockr encryption key with Ubercart credit card payments We migrated a client to Pantheon hosting a couple months ago. The site’s ubercart payments worked consistently on the old hosting platform, but  have only worked sporadically on pantheon and I’m trying to resolve the issue. It seems that the only payments that go through are ones made immediately after Drupal’s caches have been flushed.

I believe the problem is due to the credit card encryption: while I can set a directory in ubercart’s “Encryption key directory” field and I can see that the key does get generated, most payment transactions fail.

Ubercart wants you to store this key outside your doc root or in sites/default/files/private. I think this probably works perfectly on a normal hosting platform, but on Pantheon, the structure is different with sites/default/files/private not within the site's doc root.

I have read both of these pantheon guides: https://pantheon.io/docs/guides/lockr/ and https://pantheon.io/docs/private-paths/. Based on this info, I have installed the Drupal Key, Encrypt and Lockr modules and have enabled them.

In the Key module admin UI, I was able to signup for a Lockr account and add an encryption key of type Lockr encryption.

But now I don’t know how to make ubercart use this Lockr key. In Ubercart’s payment settings, under “Encryption key directory” it expects/requires a path to the key: what would this be for a Lockr key?

In the README for the Key module under the section "Using Keys" it seems to indicate I will have to write a custom module to make the Lockr key appear as a selectable option in the ubercart key directory settings. But I worry this may be beyond my abilities or consume vast amounts of time to figure out.

Is there an easy way to make ubercart use a Lockr key? Or has anyone written a custom module for this they'd be willing to share?

A kindly developer wrote a patch for Ubercart that integrates Lockr key. It's working great for me.

You can find the patch here: https://www.drupal.org/node/2842813

Note: it's written for version 7.x-3.9 which isn't the latest, so it may have to be modified and rerolled for the current version.


limit access to private files uploaded by webform to specific role In my Drupal 7 site, I have a webform where anonymous users upload a file
(typically, their CV). The webform is configured to save it in the private file system. How can I achieve that the uploaded files are accessible only to authenticated users who belong to a specific role ?
(at this moment they are accessible only to the admin user)

thanks

By default, users with the 'access all webform results' permission can view all webform private files.

If, for some reason you need them to be able to access the files but not the webform results, you could implement hook_file_download() - you could base your implementation on webform_file_download() in webform.module


Programmatically specifying pathauto alias I am working on a custom module to specify the pathauto alias of a new node, based on taxonomy terms that a user sets when they create the node. For instance, for my blog post content type, the alias would be auto-generated as /blogs/this-is-a-new-blog-post. However, if the category taxonomy is set to be special-project, I want to change the alias to be /special-project/blog/this-is-a-new-blog-post.

I'm able to load the node using hook_entity_insert(). However, I haven't been able to figure out how to set the alias.

I've found examples of how to set the path when creating a new node, but I already have an existing node object in this hook. I've tried debugging the path from the entity using $entity->toUrl()->getInternalPath(), but that just gives me the default URL (/node/123), not the alias. Trying to debug $node->path, I get an enormous stdClass object that I can't really suss out. Trying to debug $node->path->alias using drupal_set_message("alias: " . $node->path->alias);, I get this: alias:.

How can I see and alter the path alias on an existing node?

Pathauto 8.x is already hooking into the hook_entity_$CRUD_OP() hooks of D8 to do its work. Thus, trying to do this via a hook_entity_insert() means your module hook might fire before/after pathauto has set its alias (depending on module weight).

Instead of doing this, you should use the API functions of pathauto to alter its behavior. For example, hook_pathauto_pattern_alter() or hook_pathauto_alias_alter() will let you alter the pattern/alias prior to generation/saving.

See pathauto.api.php for more info.


How can I do a multi-level sort in Views? I have a table format view with multiple columns/fields:

Date
Title
Room

And data that looks like this table (as an example):

|    Date       |    Title      |  Room  |

| 4 June 2016   | Yellow-Green  | Apple  |

| 4 June 2016   | Sky Blue      | Orange |

| 1 June 2016   | Magenta       | Apple  |

| 4 June 2016   | Yellow-Green  | Grape  |

I want to sort the data in the table at multiple levels:

First by Date in descending order
Second by Title in ascending order
Third by Room in ascending order

So from the data given, the table would sort in this order:

|    Date       |    Title      |  Room  |

| 4 June 2016   | Sky Blue      | Orange |

| 4 June 2016   | Yellow-Green  | Apple  |

| 4 June 2016   | Yellow-Green  | Grape  |

| 1 June 2016   | Magenta       | Apple  |

Please note that the data all still needs to be in a single table, rather than splitting into multiple tables, thank you.

The effect I'm trying to achieve in how it's like in Excel -- wherein you can sort the cells by levels -- for instance, first sort by Column B, then sort by Column D, etc.

How can I achieve this in Drupal 7 views without writing/editing any code?

Thanks very much in advance for any help.

(I've edited this question to hopefully clear things up.)

In Views, under the "Format" heading you format is already "Table", Click the Settings link, Scroll down until you see "Grouping field Nr.1" and choose date.  Then use "Grouping field Nr.2" for the next one.


hook for db insert function on custom table Is there any hook on db_insert function on a custom table?

db_insert('projects')
  ->fields(array(
    'title' => $title,
    'p_key' => $projectkey,
  ))->execute();

No, there's no hook invoked for db_insert.

If you have a custom table, though, you're probably controlling the insert code yourself, in which case you can invoke your own:

db_insert()->(...);
module_invoke_all('mymodule_foo_insert', $some_contextual_data);


Multistep module not works for User Edit form (Edit Profile) The Multistep module works well for nodes in content types, like Article, Page, etc.

But when I tried to use Multistep for Account fields, it failed. I cannot find anything about "User form" in Structure->Block (while other content types Multistep form will be shown here).

How could I make the "Edit Profile" form as multi-step?

Never used this module, but it seems that it could do what you need

https://drupal.org/project/step

It can be used both with deafult drupal registration system or with Profile2 module, however mind that it is still in dev version.

Cheers


Error when trying to edit and save a user field When trying to update the settings of an integer field in the user fields, there is an error on saving and the logs show the following error:

  PHP Fatal error:  Call to undefined function element_validate_number() in /var/www/vhosts/**/includes/form.inc on line 1361

element_validate_number() was added in Drupal 7.6 (or 7.8, I can't quite remember) so it may be that you have an older version of core that doesn't contain that function.

If you can't upgrade your version of core, try adding this into a module file, it should save you the headache:

if (!function_exists('element_validate_number')) {
  function element_validate_number($element, &$form_state) {
    $value = $element['#value'];
    if ($value != '' && !is_numeric($value)) {
      form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
    }
  }
}

In case you're interested element_validate_number() is the replacement for the deprecated _element_validate_number().


Get content type identifier on Views I am on Drupal 7 and configuring Views. I can easily add a field that displays thew node's content type. But it seems it will bring only the friendly content type name. Is there any way I can pull the content type's system name (like 'content_type_system_name')?

Thank you.

In your field settings at the end you've a "More" section, click there and then check the "Output machine name"'s option.


Full name field on node using Display Suite I am using Display Suite for layout and arrangement of nodes. I would like to display the full name of a node author (a field I have added to the user entity). Display Suite will only show the author username.

How do I display the full name field on a node, instead of the author username?

It sounds like you need a field formatter. You have a few options:

Use Drupal's mechanism and create one yourself.
Use the Custom Formatter module to create a custom formatter.
Use Display Suite to create a custom code field.

If you aren't comfortable with coding, options 2 and 3 are good choices. Option 1 is leaner since if you already have a custom module it wouldn't add the overhead to your site of enabling another module.


Calling entity reference field in page template We are working on Drupal 8 Blog Page template. We want to render entity reference fields in the page template.

I have tried {{ node.field_name.entity.name.value }} and {{ node.field_name.entity.uri.value }} but none of this is working. Do I need to update/change anything in Drupal backend for the content type?

The entity reference field normally contains just the entity ID as value.

Looking at Twig get value of field in entity reference and Drupal 8 loop entity reference fields.twig it seems a bit that

{{ node.field_name.entity }}

or

{{ node.field_name.0.entity }}

or

{{ node.field_name[0].entity }}

might work.

If it doesn't work, try Twig Tweak which gives you some handy functions to print Drupal entities in Twig.

{% set nid = node.field_name.target_id %}
{{ drupal_entity('node', nid) }}

Or even easier as recommended by @4k4 in the comments:

{{ drupal_field('field_name', 'node') }}

  Twig Tweak is a small module which provides a Twig extension with some
  useful functions and filters that can improve development experience.


Term translation in views i try to create a multilingual page with drupal.

http://alarabi.biz/category-listing

I created some categoreis and translated them with the Internationalization plugin and i18nviews.

So I can chouse the language in views settings

but all I get is language "und" I think it means undefined.

How to fix it? Terms are translated.

You need to use the Name (Translated) handler provided by i18nviews.


How to I get an extra field for a user profile when using EntityFieldQuery() I'm currently using something like this:

$users = new EntityFieldQuery();
        $users->entityCondition('entity_type', 'user')
        ->propertyCondition('status', 1);
$result = $users->execute();

Which is great, but it returns a list of 1000 ids. How do I get an extra field with this, without loading 100 user profiles (which would be quite time consuming). So for example I need to get the profile field - field_profile_company

I tried user user_load_multiple($result['user']);

Thanks.

The result that comes from EntityFieldQuery::execute contains an array of entity types, and within each of those is an array of the entities found in the query.

The caveat is that the entity ID is actually the array key of said array, so to use user_load_multiple() you would use syntax like this:

$users = user_load_multiple(array_keys($result['user']));


Can you save state in the $form_state variable that remains when the form is rebuilt? I have a form with a nested subform that has an ajax submit button in it. The subform is built inside a form_alter and attached to the form. The submit buttons #name is made unique by using a UUID generator.
When I press the ajax submit button, Drupal steps through its form builder steps rebuilding the form. Because of this, the same code in the form_alter is called rebuilding the same subform. The problem is that when it is rebuilt, the submit button gets a brand new #name via the UUID generator. As such, Drupal cannot match the _triggering_element to a #name, and the ajax fails.
One solution I thought to try was to attach the #name to $form_state storage when the form is first built hoping that it would be available when the form is rebuilt. For e.g. in the same form_alter I execute:
      $input = $form_state->getUserInput();
      if($input){
        //This only runs when the form is being rebuilt
      }

And I may be able to grab the correct #name out of $form_state storage and set it so Drupal can correctly match and find the right ajax callbacks.
Is something like this possible? Is there a better way to handle this?

You only need #name if the form array keys don't provide a unique path for form_state. I agree with @Jaypan, I too found setting #name never really necessary, it seems to be more reliable to define a unique key to the lowest level of the form element if you have issues with Ajax not finding the form element. In either case, #name or form key, it has to be predictable, derived from data which doesn't change between form builds, for example a field delta.
The form object and $form_state are not cached when a form is rendered, only after submitting the first Ajax request. So it doesn't help to store data in $form_state you want to use to rebuild $form.


Best practices to hide elements on a page So at the moment I can use:

CSS using display: none
function hide(attribute) using hook_preprocess_page()
remove title code from page.tpl.php

And I'm sure there are much more! I'm kinda new to drupal so wondering what you guys think is better practice. Ie...

If I want to hide the page title I would use...
If I want to hide the timezone configuration block on user profile I would use...

Thanks!

As Alex Gill mentioned in the comments this is an open ended question.

My guidelines though are as follows:

never hide something via CSS if you can hide it via application code, especially if you don't really want it inside the HTML. Hiding stuff with CSS is only acceptable if you want to have them "preloaded" in order to display them later on using javascript
hiding something via module (e.g code from your features module, if you have one) is good since it can work with any template

In regards to hiding form elements please note that:

hiding stuff with CSS still makes it possible for "smart" users to alter the hidden defaults, possibly via Firebug etc. So you should not assume that users will not be able to alter form elements that they cannot see.
removing form elements via code may have side effects down the line in case you've removed stuff that is expected in validate functions. E.g if you've removed a mandatory form element then it'll never get submitted.


Clickable Link to Header I'd like to have a header with PNG files, that are clickable.

I am using Drupal 7 and Omega Theme.

In the Omega default.css, I've added the following:

.branding-data {

    height: 250px;
    background-image: url('../images/slideheader1-object1441486291.png'),url('../images/slideheader1-object1068949429.png'),url('../images/slideheader1-object1159417376.png'),  url('../images/slideheader1.jpg');
        background-size: 100% 23.2%,49.55% 99.6%,39.51% 100%,  100%;
        background-position: 0px 192px,292px 4px,505px 0px,  0 0;
    background-repeat: no-repeat;}

It adds the images to my header. One of these should be a link to another page.

How can I do this?

answer found.

I've resolved this by adding new Blocks instead of background images:

Thereby adding Images, that are links to my header.

In the CSS files i then adjusted the position and opacity.

Greets,
Chris


Adding a validation step via hook_form_FORM_ID_alter() I am trying to add a custom validation function to an existing form. I am using hook_form_FORM_ID_alter() to edit the form. I am then adding a new function to the #validation array. When I use dpm()  and print out $form['#validation'] I can see that my function is there. However the validation step is not running. If I dpm() in the validation function it is not hit.

/**
 *  Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_mycustomdorm_form_alter(&$form, &$form_state, $form_id) {
    $form['#validate'][] = 'mymodule_test';
    dpm($form['#validate']);
}

function mymodule_test($form, &$form_state) {
  dpm($form_state);
}

Hi Bobby you can use custom validate submit handler to deal with this

$form['submit']['#validate'][] = 'custom_validate_function'

all you have to use is #validate in submit handler.

use the same callback function as above with replacing the callback name


Add a div at end of the form so that i can display data over there This is my code..

function mymodule_menu()
{
$items = array();

  $items['mymodules/page'] = array(
    'title' => t('my module settings'),
    'description' => t('change values here'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_page'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
   );
  return $items;
}

function mymodule_page()
{
$form = array();

$brandarray = array('nokia','siemes');
 $form['mymodule_brand'] = array(
    '#type' => 'select',
    '#title' => t('Brand'),
    '#default_value' => variable_get('mymodule_brand', 'nokia'),
    '#options' => $brandarray,
    '#description' => t('Change this.'),
  );
 $form['div_tag'] = array('#type' => 'markup', '#value' => '
content comes here
');
 return system_settings_form($form);

}

I just want to do like this. After the form is displayed i just want to add a div so that i can use it for my dynamic data which comes after select is changed. How do i do it?

Try this:

$form['my_markup'] = array(
  '#markup' => '
Lorem ipsum
'
);

Check the documentation at
http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html#markup


How to modify the fields of user registration form and user login form? I have user registration and user login form on same page and want to customize the field of both the forms?

Use hook_form_alter() or hook_form_FORM_ID_alter to update anything in the forms:
Example of updating the user login form using hook_form_alter():

function My_Module_form_alter(&$form, &$form_state, $form_id) {
  // Modify the user login form. ('replace the "-" with "_" in form id')
  if ($form_id === 'user_login_block') {
    // Modifying the label and the size of input of username and password.
    $form['name']['#title'] = 'User Name';
    $form['name']['#size'] = '20';
    $form['pass']['#title'] = 'Password';
    $form['pass']['#size'] = '20';

    // Adding extra class to the form.
    $form['#attributes']['class'][] = 'custom-class-name';

    // Adding additional validator to the form for some custom validations.
    $form['#validate'][] = 'My_Module_custom_form_validation';
  }
}


How to add new component type in webform? I want to add a reset component type to a webform. Is there any contributed module available? if not suggest me how can I achieve this through code.

I got answer for my question from this link, Hope this will help somebody who have same requirement.
follw this link.


Does Drush 8.x work with core 7.x? With the major changes to Drupal with version 8, it seems I would need Drush 7.x or earlier to work with Drupal 7.x. I tried to rebuild the cache and I got errors related to namespaces in PHP. It seemed to be looking for features that were not part of Drupal 7.x.

Are there different commands to clear the cache for a Drupal 7.x site?
I tried drush cr and it came back with errors indicating it was trying to find code using namespaces, but Drupal 7.x core doesn't use namespaces in the code.

I tried it on Ubuntu and on Windows.

Yes, Drush 8 works with Drupal 6, 7 and -8.3. I just tested Drush 8.1.17 against a Drupal 7.58 site: worked a charm to clear cache, generate a login URL and download a module.

This is the compatibility table from their site for reference:

  I mean are there different commands to clear the cache for a Drupal 7.x site?

Yes, it was cache-clear, or cc for short in Drupal 7, e.g.

drush cc all


How to limit users to a create only one instance of a node type? I know there is Node Limit module, but since it is in alpha stage since a rather long time, I am wondering if there is more elegant way to do so which does not need additional modules?

FWIW I've been using Node Limit on a dev site for a few weeks now, it's had thorough testing and seems to work perfectly. I'm using the 'Node Limit Type' and 'Node Limit User of Role' sub-modules.

If you want to implement it yourself, you can't really look anywhere better than inside the Node Limit module itself. It implements hook_node_prepare() to deny access to the node add form if the user has exceeded the maximum nodes, based on various rules.

A very simple custom implementation might look like this:

function MYMODULE_node_prepare($node) {
  if (empty($node->nid) && $node->type == 'the_content_type') {
    // Grab the number of nodes of this type the user has already created.
    $args = array(':type' => 'the_content_type', ':uid' => $GLOBALS['user']->uid);
    $node_count = db_query('SELECT COUNT(nid) FROM {node} WHERE type = :type AND uid = :uid', $args)->fetchField();

    // Get the max allowed number of nodes
    $limit = function_to_get_limit();

    // If the user is at/has exceeded the limit, set a message and send the user
    // off somewhere else.
    if ($limit >= $node_count) {
      drupal_set_message(t('Node limit exceeded'));

      drupal_goto('somewhere');
    }
  }
}

You could obviously add further checks in there to make sure the user has a certain role, etc. I'd advise having a flick through the code in the Node Limit module to see how the above could be improved upon.

The above is a 'friendly' way to perform the check (i.e. one that doesn't just throw out a 403 page). If you want to be more militant, you could put roughly the same code in a hook_node_access() implementation instead:

function MYMODULE_node_access($node, $op, $account) {
  if ($op == 'create' && $node->type == 'the_content_type') {
    // Grab the number of nodes of this type the user has already created.
    $args = array(':type' => 'the_content_type', ':uid' => $account->uid);
    $node_count = db_query('SELECT COUNT(nid) FROM {node} WHERE type = :type AND uid = :uid', $args)->fetchField();

    // Get the max allowed number of nodes
    $limit = function_to_get_limit();

    // If the user us at/has exceeded the limit, set a message and send the user
    // off somewhere else.
    if ($limit >= $node_count) {
      return NODE_ACCESS_DENY;
    }

    return NODE_ACCESS_ALLOW;
  }

  return NODE_ACCESS_IGNORE;
}


Using TableSort without doing a query Drupal core has the Drupal\Core\Utility\TableSort class which can be used to create tables with sortable columns. All examples in core however are based on Drupal\Core\Database\Query\TableSortExtender which providers table sorting for data coming from a database query.
I am looking to display data that is generated by custom code and is not originating from a query. How can I use the TableSort code directly in my controller?
This is the Drupal 8 version of the same question for Drupal 7. See the answers there for additional insights.

TableSort has methods to retrieve the sorting order and the field being sorted directly from the query arguments. You can use the values returned by ::getSort() and ::getOrder() to do a custom sorting of your data.
In your render array you can use some (undocumented) options in the #header declaration to control the way the table is initially sorted:

field: the name to use in the query arguments to indicate that the table should be sorted by this column.
sort: one (and only one) of the columns can be given this option (with value either asc or desc). This will be the column that is sorted by default.
initial_click_sort: this can be set to desc if the data should be sorted in descending order if the column header is initially clicked. This defaults to asc but for some data you want to show larger numbers at the top by default.

Here is an example of a controller using data from a custom array:
<?php

declare(strict_types = 1);

namespace Drupal\my_project\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Utility\TableSort;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Demo of a table with sortable columns using data from a custom source.
 */
class SortableTableDemoController extends ControllerBase {

  /**
   * The Symfony request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a new SortableTableDemoController.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   */
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new static(
      $container->get('request_stack')
    );
  }

  /**
   * Returns a render array containing data about Linux distributions.
   *
   * @return array
   *   The render array.
   */
  public function linuxDistributionsTable(): array {
    $headers = [
      // The distribution label has the 'sort' option, making it the default.
      [
        'data' => $this->t('Distribution'),
        'field' => 'label',
        'sort' => 'asc',
      ],
      [
        'data' => $this->t('Initial release'),
        'field' => 'year',
      ],
      // Sorted from highest to lowest on initial click.
      [
        'data' => $this->t('Packages'),
        'field' => 'packages',
        'initial_click_sort' => 'desc',
      ],
    ];

    $data = [
      ['label' => 'Arch Linux', 'year' => 2002, 'packages' => 77264],
      ['label' => 'Debian', 'year' => 1993, 'packages' => 118326],
      ['label' => 'Red Hat', 'year' => 2002, 'packages' => 12155],
      ['label' => 'Gentoo Linux', 'year' => 2002, 'packages' => 29092],
      ['label' => 'OpenSUSE', 'year' => 2006, 'packages' => 76236],
      ['label' => 'Ubuntu', 'year' => 2004, 'packages' => 89403],
    ];

    // Sort the table according to the options passed in the query arguments.
    $request = $this->requestStack->getCurrentRequest();
    $sort = TableSort::getSort($headers, $request);
    $order_by = TableSort::getOrder($headers, $request)['sql'];

    usort($data, function (array $a, array $b) use ($sort, $order_by): int {
      $result = $a[$order_by] <=> $b[$order_by];
      return $sort === 'asc' ? $result : -$result;
    });

    return [
      'table' => [
        '#type' => 'table',
        '#header' => $headers,
        '#rows' => $data,
      ],
    ];
  }

}


Is it possible to manage Drupal running on a Windows server using drush on linux via a Samba mount? I have been trying to set up drush on my linux desktop (hereafter called client) to control a remote Drupal site running on Windows using XAMPP (herafter called server).

The Drupal root on the remote server is mounted via Samba on the client at this location : /path/to/remote/server1/drupal

I am using the following drush alias:

$aliases['drupalserver1'] = array(
  'root' => '/path/to/remote/server1/drupal',
  #'remote-host' => 'drupalserver1.mydomain',
  #'remote-user' => 'myuser',
  'uri' => 'http://drupalserver1.mydomain',
  'os' => 'Windows',
);

Now, as I understand it, this tells drush that it is a local installation of Drupal, not a remote one since I left commented the remote-host and remote-user entries.

Drush then reads the settings.php file on the server (via the samba mount on my client), which specifies drupalserver1.mydomain (rather than localhost) and the necessary other configurations.

Database connection is successful as is bootstrapping:

 Site URI                        :  http://drupalserver1.mydomain
 Database driver                 :  mysql
 Database hostname               :  drupalserver1.mydomain
 Database username               :  root
 Database name                   :  drupal
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  acquia_marina
 Administration theme            :  seven
 PHP configuration               :  /etc/php5/cli/php.ini /home/myuser/.drush/php.ini
 Drush version                   :  5.9
 Drush configuration             :
 Drush alias files               :  /home/myuser/.drush/examples_example.aliases.drushrc.php /home/myuser/.drush/myorg.aliases.drushrc.php
 Drupal root                     :  /path/to/remote/server1/drupal
 Site path                       :  sites/default
 File directory path             :  sites/default/files
 Temporary file directory path   :  C:\xampp\tmp

Now, both the Drupal files (/path/to/remote/server1/drupal) and the mysql DB are hosted on a Windows machine, so using 'os' => 'Windows' in the alias makes sense.  I even wonder if this line is even taken into account since remote_host is not used.

Is there any hope that the configuration I am proposing works at all ?

Using Drupal 7.

In your case, 'os' => 'Linux'.  This variable tells Drush how to do things such as filesystem path escaping.  As you supposed, this variable is primarily used during remote calls, but I believe it may occasionally be referenced when building commands that are used locally.

I have never tried to set up Drush as you describe above; in theory, it should be possible, as long as you can connect to the database, but you might run into some problems.  Post issues in the Drush issue queue if you find bugs.  PRs with fixes would be particularly welcome.