Er, yes, I just succeeded in creating a Forum topic, after many trials. This was successful :

curl -i -X POST \
  -H Cookie:SESSe6a353351df0bfa8deadcafe=B0ZkiW3-U2x93yJU-deadbeef \
  -H X-CSRF-Token:PSCd5qIdddax0Mh5gfnOM872hdj893-eeeeffff \
  -H Accept:application/json \
  -H content-type:application/json \
  http://myserver/rest/node \
  -d '{
    "type": "forum",
    "title": "test post?",
    "language": "und",
    "taxonomy_forums": {
      "und": "1"
    },
    "body": {
      "und": [{
        "value" : "test post",
        "summary": "this is a test1",
        "format": "full_html"
      }]
    }
  }'

The key difference was, I think, adding this to the JSON:

    "taxonomy_forums": {
      "und": "1"
    },

I guessed this, based on a view of the Firefox firebug Net panel, when using the UI to post a new forum topic. This number specifies the forum to which the new topic should be associated. It is a different matter to get the list of forum topics!

Maybe this will help others.


Can I get the relationships of a node using node_load()?

As an option you can index the entire rendered HTML of your content.
Let's assume your index is called "default_node_index" and content type is "article".

Visit /admin/config/search/search_api/index/default_node_index/workflow
Enable "Complete entity view"

Visit /admin/config/search/search_api/index/default_node_index/fields
Enable "Entity HTML output".

Manage display of your content type /admin/structure/types/manage/article/display
Enable "Search Index" in "Custom display settings" fieldset.

Visit /admin/structure/types/manage/article/display/search_index
Add all the fields you want to render. You can extend this display using the regulat hooks, templates and preprocesses if needed.


I'm constantly getting logged out of my account

A lot of different things can cause that, so there are several things to check. One common issue is not having the site direct traffic to either www.[sitename].com or [sitename].com - this causes users to have separate sessions for each version of the site. Solution here: Website saves separate sessions for "www.domain.com" and "domain.com"

Another possible issue is a misconfigured sites/default/settings.php file - this can happen if you copy the site from another location. Check uncommented lines pointing to urls other than your test location. I believe cookie domain can cause session problems if misconfigured.

Finally, since you mentioned that this is a test server, you might check that Drupal's MYSQL user has the correct permissions for its database. I've had strange things happen when it has some but not all of the necessary access permissions to the database.


Attach a script to a particular node ID or view

Node ID:

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}

View:

function THEMENAME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(path_to_theme() . 'INSERT_SCRIPT');
  }
}


I would not create a content type just for adding a single image to the header in any case, but even more so in this case as it appears that is you website's logo (is that right?).

If it is your logo then the best way to achieve this is via the settings of your theme. Almost all themes have a setting for the logo image.

Go to admin/appearance then click the settings link for your theme.
You will see a "Logo image settings" section on the settings form, which usually by default has a check box "Use the default logo", which will be checked by default.

You can un-check that check box and then enter a path to your logo image file, however the easier and better way is to leave that check box checked and then in your theme directory replace the default logo with your own, by renaming your logo image to logo.png and copying it over the one that is already there.

On that theme settings page there is also a section for "Toggle display".
In this section make sure that "Logo" is checked.

Then the site will be using your logo, which normally by default will be in the header already.

Then you just have to use a little css to position it as you want it, or if it is not in the right place for you, edit the page.tpl.php of your theme and move the logo to where you want it, then tweak styles with css as needed.

If you only want the logo on the home page, make a copy of your page.tpl.php in your theme and call it page--front.tpl.php - This means it will only apply to your front page (see drupal 7 template suggestions for more info).

Then you can have the logo printing on the front page but you can remove it from your normal page.tpl.php so it doesn't appear on other pages.

If I was wrong about it being your site logo or it is the logo but for some other reason you don't want to use the site logo setting, you can do one of a few things.

If the image is purely decorative, it is generally considered a good idea to make it a css background image, in which case just add the image to your theme's images directory and add some css to your theme to set it as the background image of your text block in your header and use padding so that the contents don't overlap the image.

If the image is not purely decorative and it actually has meaning to the user, you want screen readers to read it as an image so disabled users can see it.

In this case you need to use an img tag.

So you can do one of these things:

Make the page--front.tpl.php and manually add an img tag in the place you want it, put the image in the images directory of your theme, then style with CSS.

The other option is to create a custom block via the block UI.

To do this go to admin/structure/block and click the "Add block" link.
In the block body field add the img tag you want.
The easiest way to do this is make sure you have a wysiwyg text editor (for example, ckeditor or wysiwyg module) and use it for block creation.
Then you can upload an image directly via the wysiwyg editor instead of messing around uploading files manually to your server, which is not ideal.

In this way you can either make a block for your image and a block for the text to the right of it, or if they directly relate to each other you can add them in the same block.

Then in the block visibility settings you can make it so that it only shows on the home page (or you can use some other block management system to do that if you prefer).


how to make node data available in the page.tpl.php

If you are on Drupal 7 you can edit your theme's template.php and add (or edit) the function

function <YOUR_THEME_NAME>_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

The same task in Drupal 6 is accomplished by adding/editing in template.php

function <YOUR_THEME_NAME>_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
    $variables['template_files'][] = "page-" . $variables['node']->type;
  }
}

Then you can add page--<YOUR_CONTENT_TYPE_MACHINE_NAME>.tpl.php (or page-<YOUR_CONTENT_TYPE_MACHINE_NAME>.tpl.php in Drupal 6)  to your theme. Remember to clear the theme cache.


How to add term programmatically in Paragraph field?

First load the node already created.
Second, create a paragraph like you did but for taxonomy term add "target_id" and for value choose a term id.
Set the paragraph value to your field of type paragraph from node. Also you need to save the node.

    $node = Node::load($nid);
     $paragraph = Paragraph::create([
            'type' => 'gallery_image',
            'field_type_createurs' => ['target_id' => $value],
          ]);
          $paragraph->save();

          $current[] = [
            'target_id' => $paragraph->id(),
            'target_revision_id' =>$paragraph->getRevisionId(),
          ];

   $node->set('your_field', $current);
   $node->save();

Varible $value is a term id.

Hope to help you.


Why is file_managed not updated correctly?

I changed file.settings config entry make_unused_managed_files_temporary to true and it seems to do the job.
Just hope there won't be any side effects...


Change order of markup for exposed views filter

You can create your own views-exposed-form.tpl.php file and move the submit button to the top, or add a class to it and use css to float left and right. This however would affect all exposed filter on your site.

If you want to alter the form you should use the function

function MODULENAME_form_views_exposed_form_alter(&$form, $form_state)

Your best option is however to try manipulating it with css.


Special thanks to Peacog Web Development for their great tutorial .Here is the tip:

  Rather than Drupal 7, Different Block types can be created by admin

so the solution is simple :

Create a new block type using : admin/structure/block/block-content/types
Add a Reference of type Webform to custom block type
remove body if it's inappropriate
modify custom block Manage Display so the form would be rendered as webform
your new Block type is ready

now to add any new webform as block you, you will need to add new block of type Custom Block and refer to your webform, and that's done.


How do you add a form to a content type?

If you are ok with custom code.

The form does not need to be inline to Content Type.
Consider this example
You have custom form. form builder of which takes an argument as nid.

function custom_form_builder($form, &$form_state, $nid) {
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $nid,
   );
  // form field goes here.
}
Now in your view add nid field along with other fields you need and an extra custom field.
In your views you can define custom template for custom field.
Implement template_preprocess_views_view() to call drupal_get_form('form_id',$nid) and make it available on the custom template.
Print the form on the template.
Now when the custom form gets submit you can get the nid to update in $form_state['values']['nid'].


Added a secondary link through code. Why is my href URL getting decoded?

Try using urlencode ...

$secondary_links['menu_custom_item'] = array(
                      'attributes' => array( 'title' => $label ),
                      'alter'   => 1,
                      'href'    => urlencode($uri),
                      'title'   => $label,
                      'language'  => 'en'
                );


If you're only concerned about taxonomy term fields, then I reckon that you should investigate the taxonomy_menu or similar family of modules. In fact, looking at your other post, I suggest that you go through the entire list of taxonomy modules on Drupal in general :)


You probably need to delete or remove the file from any nodes, or webform submissions that it references. There should be a usage tab on the actual media resource. I don't have a media site handy so I can't provide screenshots. Once that usage tab is empty, it should be possible to delete that file. Otherwise I'd check the recent log messages in admin/reports to see if there's a file permissions issue, like the only file owners can delete files.


Splitting field value inside field template not working?

In a field.html.twig template {{ item.content }} is a render array. You can't use it in functions which expect a scalar like boolean, integer or string.

If you want to use field values in TWIG code better use the field object #items:

{% for item in element['#items'] %}
  {% set tags = item.value|split(' ') %}
  {{ dump(tags) }}
{% endfor %}

In a single value field you can access the value directly without a loop element['#items'].value.


Styling views table - Toogle row class on click

First of all you need to add custom class to your VIEWS wrapper and also for TABLE ROW.
I have added my-view-wrapper for the VIEWS and row-wrapper for TABLE ROW

Add CLASS to your VIEWS

Add CLASS to your TABLE ROW

(function ($) {
  Drupal.behaviors.viewRowHighlight = {
    attach: function (context, settings) {
      $('.my-view-wrapper .row-wrapper').click(function(e){
        $(this).toggleClass('clicked');
      });
    }
  };
})(jQuery);


How to prevent the login block to be shown twice?

Follow the steps, Using which can solve your problem.

Go to Blocks under structure admin menu.
You will find user login block in Header section.
If you have added your custom login block then there is no need to have default login widget in header. So change it to null.
If you have default login then just check to put it in appropriate block.

This are the two cases according to your question description.Answer back if not solved.

Please do mention some more description if this solution won't work.


You can print the cck field like this.

// Load the node.
$node = node_load($nid);

// Print the fields.
print $node->title;
print $node->field_myfield[LANGUAGE_NONE][0]['value'];

or a more decent way like this...

$myfield = field_get_items('node', $node, 'field_myfield');

https://api.drupal.org/api/drupal/modules!field!field.module/function/field_get_items/7

See this also. https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_view_value/7


How to keep Views 2 RSS feed output from stripping out video, embeds, etc.?

Figured this out -- client request was to not eliminate any of the html markup (embeds, videos, emphasis tags, etc.) even though some of the RSS readers would continue to strip it out on their own. I worked through this by creating a views-view-row-rss.tpl.php for my specific view and then adding the following code in:

<?
 $index = $variables["view"]->row_index;
 $nid = $variables["view"]->result[$index]->nid;
 $node = node_load($nid);

 $teaser = check_markup($node->teaser);

 $description = "<![CDATA[".$teaser."]]>";

?>
  <item>
    <title><?php print $title; ?></title>
    <link><?php print $link; ?></link>
    <description><?php print $description; ?></description>
    <?php print $item_elements; ?>
  </item>

Hope this is helpful to someone else, welcome any suggestions on improving this.


7 - FAPI: form_set_error messages on bottom of page or dialog box

Perhaps the Inline Form Errors module is useful to you. It provides Inline Form Errors (as the name implies). More details from the module's project page:

IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.
IFE provides three behaviours for the configured forms

Leave the messages in place, this option will copy the error messages and place them inline. The original error messages set by Drupal will remain in place.
Show an alternative message, this option will replace the original messages with a generic error message such as 'Please correct all errors.'. This message can be set in the IFE configuration page. The original error messages are placed inline with the form elements
Remove all messages, this option will remove all error messages and place them inline with the form element

In all cases only the messages related to the form will be touched. All other messages will remain in tact.


Module to edit field data on multiple instances/nodes (in bulk)

For Drupal 7 you will need views bulk operations which packages this and other bulk operations.  For Drupal 8 you need Bulk Update Fields

Below the procedure is for Drupal 8 but very similar for Drupal 7

Install the module and modify the Admin content view found by going to admin/structure/views/view/content or perhaps you can use any view that you want.

add field and search for Node operations bulk form to add and make sure you enable

Selected actions: Bulk Update Fields to Another Value

With this when on the view page you can select 1 or more nodes and modify fields in bulk


How do I get the password from form API to use to log into external site?

I went with the
Encrypt Form API module.


How to expose Profile2 fields in Services?

I found that I had to use pid: /api/entity_profile2?parameters[pid]=1


Import content using the "Default Content for D8" module

This will be probably resolved by setting the _links type href domain as http://drupal.org (the default links domain used by default_content module) in yor .json files to import, instead of drupal-pro-8 that was set form the site you exported?.


This can be achieved with jQuery .trigger() event.

jQuery('#id-of-your-phrase').click(function (e) {
 e.preventDefault();
 jQuery('#id-or-class-of-first-image-YouCanAlsoUse-first-child').trigger('click');
});

This code will open the colorbox from First Image (the Big).


Taxonomy translation Localize option not working correctly. thoughts?

The answer to this is to change the taxonomy link preferences under 'Manage Display' in the content type - here is a link to a thread on the issue.

http://drupal.org/node/1070256


How to add phone number field to simplereservation/add page

I think if you don't want to edit module, you may use comment field for telephone number. It's much easier to customize comment label and change it to phone number, than to edit module's code for additional field to store in database and display in form. Anyway it will be your preference.

UPD: tried to do something. If you don't need user comment, you can change Comment label, make it required field, and change description. (better solution is to try alter form)

Result:

Where to replace code in sites/all/modules/simple_reservation/simplereservation.module:

You just can compare lines from original and my example.


How can I send mail containing rendered entity from referenced field?

You need to use target_id to get the node id, then load the node and get the fields values you want.
$avtal_id = $node->field_avtalsnummer[LANGUAGE_NONE][0]['target_id'];
$avtal_node = node_load($avtal_id);


How do I create a custom template for view?

Below give are the views template suggestion allowed in Drupal 8.

views-view--foobar--page.html.twig
views-view--page.html.twig
views-view--foobar.html.twig
views-view.html.twig
views-view-unformatted--foobar--page.html.twig
views-view-unformatted--page.html.twig
views-view-unformatted--foobar.html.twig
views-view-unformatted.html.twig
views-view-fields--foobar--page.html.twig
views-view-fields--page.html.twig
views-view-fields--foobar.html.twig
views-view-fields.html.twig

Refer Views template files for more information.


To resolve your issue: make sure when the view is created there is no other page or block.

It seems something setup in your MASTER page was causing it to not work. i.e localhost/extra/api/views/service.json?tag=11584


How can I get the invoicing and shipping profiles for a user?

I ended up doing this in a roundabout way:

Get the most recent order for the user
Get the shipping and billing profile for this order

If there are no orders, the user's unlikely to have shipping and billing info


How do I produce 2 lists with one display?

Under Advanced, Theming: Information, click on Information and you will see something like this:

For template file name you want to use the last suggested name, (which I underlined for you) that way it only affects this specific view and not others.

In the above example Row Style Output: you would use views-view--fields-shipping-cart--block.tpl.php

To print your fields, inside the template file you put

<?php print $fields["title"]->content; ?>

<?php print $fields["field_name"]->content; ?>

Title prints your node title, else if you want to print a field, you use field_name

Remember to flush the cache to see changes or you could click the Rescan template files button

If you're unsure of the name of a field, In view's click on your field, and go to re-write the output of the field, click on replacement patterns, whatever name replacement patterns uses is the one you need to use.

Alternatively, instead of working with template files, you could work with just replacement patterns if you like as my answer shows here

Else if you just want to add classes to your fields, you can do it with views like this:


How to display uploaded files as images in Views?

Ok I managed to work it out, it is quite simple really; you need to rewrite the output of the field using the html img tag and the replacement patterns available. This will convert any image files uploaded into the website from file names into actual images.


Termsatus module can help you.

This add a status "publis" or "unpublish" on terms like nodes, and is handled by permission (that can solve first three points), views, etc.

I think the optional point need a custom code using hook_node_validate check the status of term an send the custom error message attached to the field.


You need the Ultimate Cron module. It is an advanced system for managing scheduled tasks. You can set rules and custom schedules for every single task. Can be found here:

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


Keeping old site live while testing new site?

In short, yes you can, but this has a little to do with drupal.
To clone a Drupal site is nothing more than copying the drupal root directory (codebase) and taking a database dump. It's quite easy then to transfer all these on any other environment and with some settings.php tweaking you will have an up and running clone of your site. The hard part is to migrate from D6 to D7, but you have already done this as far as I understand.

I would propose you to setup a staging environment by using a clone created from your local environment and start adding/editing content there. It dosen't really matter under which hostname that (staging) will be, it may well be the test.dept.university.edu  because you can make the production's url (dept.university.edu) to point back (redirect) to the staging machine when all things are in place and the time to go live has come.

This is a rough idea but I guess that the meaning is quite clear.

Let the mods to decide if this question should be close or not.


D8 render a contact form from theme preprocess

Your code will work when this patch is implemented:

Add a view builder for contact_form


I have finally solved it, by using the following code which goes in a custom module.  The problem I had was that it was not rendering anything as there were nested divs. If you play with styles or add some HTML between divs, it will show the data.

The code is available at http://www.seanbuscay.com/ajax-reader-demo/


How to update path alias using MySQL command line

I don't think you will have much success using mysql, the quickest way is likely to write a script that bootstraps drupal, loads each node and then saves the node, I think this should update the aliases.


Variable storing payment method in ubercart order

The variable you're looking for is is $order->payment_method.


how to theme nodes in views results if logged in user equals node author

You'll need to check this in a preprocess hook.
You can load the global $user object and have views report the node author. In the preprocess hook you can check $user->uid against $node->uid and set a variable so you know in your tpl.php file which css class to set in your wrapper.


drush inheritance, site-ssh and site-list

The problem here is that Drush will always prefer the non-empty 'site-list' in @production over any empty value you provide in the specific site aliases.  This is regrettable, as it makes it Hard to delete values.

There are a couple of alternatives, though.  The most straightforward solution is to just take advantage of the fact that Drush alias files are executable php.  You can refactor your alias definitions like this:

<?php
$common = array (
  'root' => '/var/www/cust',
  'uri' => 'www.example.com',
  'databases' => array(
    'default' => array(
      'default' => array(
        'database' => '...',
        'username' => '...',
        'password' => '...',
        'host' => '...',
        'port' => '3306',
        'driver' => 'mysql',
      ),
    ),
  ),
);
$aliases['production'] = array (
  'site-list' => array(
    'production.1',
    'production.2',
    'production.3',
    'production.4',
  ),
);
$aliases['production.1'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.2'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.3'] = array (
  'remote-host' => '...',
) + $common;
$aliases['production.4'] = array (
  'remote-host' => '...',
) + $common;

Your second option is to take advantage of a Drush feature that automatically creates group aliases for all aliases that are defined in a single alias file.  Start with your alias file definition as you show it in the question above; then:

1) Delete 'site-list' from the 'production' alias.

2) Move the 'production' alias to a different file (I use servers.aliases.drushrc.php to store aliases to all of the servers that I have sites on).

3) Keep the individual site aliases as they are, with 'parent' => '@server.production'.

Once you have done that, you may use @cust as an alias list for all of the aliases defined in cust.aliases.drushrc.php.


IMCE browser just won't work (403 error)

ן needed to configure the IMCE profile as a saparate configuration from the CKeditor-IMCE configuration.

Go to Admin > Files > IMCE and configure it.


Print Webform reference in custom view display

At first glance it would seem you need to render this webform yourself in a preprocess function and then pass it to twig. You are trying to access the entity object using row._entity.field_reference_webform which is protected from outside access. However views should already be rendering this webform. I think maybe your template file is just setup wrong. All you have done is create a view, and put a template file for it in your theme correct?

For row level output, if your display is setup as unformatted list, your views twig file should be named:

views-view-unformatted--our-display-plugin.html.twig

and the basic code inside it should be:

{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{- row.content -}}
  </div>
{% endfor %}

Just use {{ row.content }} which should have the rendered webform in it already.

If that doesn't work perhaps we need more information on what exactly youre trying to create a template file for. The view container, the row level, or the field level.


how to exclude current node from a view inside a node commerce kickstart

Why don't you rather just pass the product display node id as a second parameter in your view field (you are allowed to use a comma separated list of arguments), and then don't bother with providing a default argument at all. The second argument to pass is [node:nid]


Your changes to $form here are lost because you are passing by value.  Pass by reference using &$form instead:

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


If you are customizing your theme and creating your own template files then this will help you.
This module can solve your problem for adding description for particular image.
https://www.drupal.org/project/image_field_caption
Just follow the installation guidelines and install it.
For title, just go to content type->edit link of image and then look for enable title field and enable that.
Yeah , you need to play a bit of with your codes, need to fetch data for title and description.
Thanks


Tab field formatter for Entity Reference field?

You can find this functionality in my sandbox.

https://www.drupal.org/sandbox/legolasbo/2383347

Please submit issues if you find any.


How can I make a node link to another node

Try to use drupal_set_breadcrumb() in template file if you want to do it programmatic.

Or configure Custom Breadcrumb module.


How to raise Notifications on new discussion posts?

You can use Flag module to create "subscribe button" on any content (forum category, post or comment) and then Rules to create rule:

what reacts to new content
then load parent entity (if new post, load it's category)
load all flaggings on it
send e-mails to authors of all flaggings OR create notification (so you can show them on some dashboard)

There are also modules specialized for subscribing to content and then send notifications, but they usually are not so flexible like solution based on Rules.


Views Dynamic Fields checkboxes to dropdown select

U can do it through hook_form_alter, just check the form_id, and change the type of form element to that of select, it will create select list from checkboxes.

However for making it working u have to write some jQuery.

$("#<form_element_id>").on('click', function(){
$(this).closest('form').trigger('submit');
});


Commerce free shipping for orders over €500

I at last managed to find out. I should have paid more attention to the video I've watched. What I needed to do was add the exact opposite condition to NL/BE rule, that is if the order's total amount is lower than €500.


How can I add a link to the main menu from a custom module?

You are missing the key menu_name that will permit the addition of your new menu item into your main menu.

my_module.list:
  title: 'List All Computers'
  description: 'Show all known computers'
  route_name: my_module.listAllComputers
  parent: main
  menu_name: main

The parent key is not mandatory, so if you want your link to be shown on the first level of your main_menu, you don't need it.


The file ID is stored in the  picture column of the users table

  Foreign key: {file_managed}.fid of user's picture.

So your payload to the update resource would look something like

{
  "uid": "123",
  "data": {
    "picture": "1078",
    # rest of user data
  }
}


Block-Placement in a Feature via Context

i think doing it in profile.install is clean enough :)
you only set the theme to default in there anyway, dont you ?


If you want  when user select a Car and then according to select car another select list showed with that car model I can suggest you use simple hierarchical select  module ( I know it hasn't stable version yet),

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

  This module has been inspired by Hierarchical select but is much
  simpler (hence the name ;) ).

Also conditional fields is very good module to achieve field show and hide based on another field but it is not suitable for your case.


Making an instantiated object in a module global

"Best" won't get you too far here; there are a bunch of different ways, none of them particular to Drupal, and all with advantages and disadvantages. Go with what you're comfortable maintaining.

That said, a simple singleton pattern would make most sense to me:

class MyClass {

  protected static $instance = NULL;

  protected function __construct() { }

  public static function getInstance() {
    if (!isset(static::$instance)) {
      static::$instance = new static();
    }
    return static::$instance;
  }

  // Remaining class implementation

}

// Use this as many times in a single page request to get access to the same instance of MyClass every time.
$instance = MyClass::getInstance();

I feel like I should add a bit about autoloading in Drupal 7, in case you haven't already come across the options...

Drupal 7 implements a simple autoloader; in the module's .info file you can specify the path to a file containing classes:

files[] = MyClass.php

and any class in that file will be automatically available to you anytime you want it, without having to explicitly include the file.

If you want to go one step further, check out the excellent X Autoload module. It provides a PSR-0 autoloader, which mirrors Drupal 8's autoloading.

I think PSR-4 is in the pipeline too, but that's another story...


Filter nodes by currently logged-in user

just add a view for all your nodes. Then add a "relationship" for "Content: Author".
Now add a "contextual filter" for the field "user: uid" with a default argument for "userid of logged in user" to filter the view.


Creating multiple nodes of different content type at once

The module you are looking for is Node Reference Create. Here is a quote about it (from the module's project page):

... is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.
When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.


Unless you known exactly what you are doing, don't try to integrate with Drupal at the database level.

Drupal database schema is dynamic. Tables to store nodes information are added and modified when you add fields or change theirs settings. So your database query will need to be checked for every changes. This could easily become a maintenance nightmare.

Any module can, an many do, add custom behaviors on node insertions and updates through Drupal hooks system. Inserting content in the database without using Drupal's API would bypass these added behavior and potentially create inconsistent data.

If you must really do it outside Drupal, you can either bootstrap Drupal in your PHP standalone script to be able to use its API or use the Services module to provides a REST API for node CRUD operations.

To bootstrap Drupal in your PHP script, use the following code. Note that most of Drupal's code expect the current dir to be Drupal's one. Drupal also register its own session handler that may conflicts with yours.

chdir("/path/to/drupal");
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


views_get_view() not accepting arguments?

View "commerce_wishlist_page" was created by module itself. There appeared to be some problem with the view configuration itself, because when I re-created the view with exactly same values the error is gone. I think this is the module problem and possible typo somewhere in hook_install()


Menus, drush uli link, and some images not working after moving site to localhost

I did recently a manual migration and had some problems, similarly to you. After this, I made a script to manually migrate the site and the database. You need to have a zip with the Drupal installation, not the folder of the installation, just the files inside it, the database and know if the database has some prefix. Change all the prefix in the database, you could use notepad++ or similar to change all in one command. Change the url i.e: mydomain.com/drupal to localhost/drupal. Then import the database, and unzip the files in your localhost server. Then go to sites/default/settings.php and at the bottom of the file edit the data of your database, prefix if you have one, pass, user, port if you changed it and, in same file, look for $settings['update_free_access'] = FALSE; and change it to true.
Now, in your browser visit localhost/yourinstallationfoldername/update.php and follow the instructions.
If you don't know the users you can see in the database for the table users and you can see there their ID (uid) and password (uuid) on md5. Just search on google for any md5 generator and copy paste it on uid 1 (admin user generated on installation) for know the name of the user you can go to the table users_field_data and look on name column.

If you have a virtual server working on your server, you must remember to point it to the new folder where is your Drupal installation. This is a good tutorial about how to do it: Installing virtual hosts for Drupal sites and subsites.


How do I set the fixed amount of values to 11?

The cardinality options are hard-coded into the field_ui_field_edit_form() function using these lines of code:

$form['field']['cardinality'] = array(
  '#type' => 'select',
  '#title' => t('Number of values'),
  '#options' => array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + drupal_map_assoc(range(1, 10)),
  '#default_value' => $field['cardinality'],
  '#description' => $description,
);

It's the drupal_map_assoc(range(1, 10)) line which is limiting the number to 10.

It doesn't seem that the maximum cardinality is validated (or further limited) anywhere else, though (at least not by core), so it would be pretty easy to offer more options for that value using a form alter hook:

function MYMODULE_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  // Increase the max cardinality to 20
  $range = drupal_map_assoc(range(1, 20));
  $new_options =  array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + $range;

  // Change the options
  $form['field']['cardinality']['#options'] = $new_options;
}

I've just tried this out and it seems to have no side-effects at all. The field system respects any cardinality you set that's higher than 10, and saves it without problem when you edit the field in the admin UI.


Hook to track commerce product category view

Well, since you're dealing with Drupal, there's no "product category page"s ... per say ... but there are taxonomy terms that are often used for catalogs and attributes. So, you could, in theory, use hook_entity_view() to tap into when a taxonomy term is being viewed.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_view/7

If you're building a module, I could see you building an interface that lets people assign urls and taxonomy terms that would potentially "make" the catalog pages trigger whatever it is you want to trigger.

Ultimately, though, there's no hard and fast rule on how to build a commerce store, so there's nothing for you to hook into.


How do I assign a region to programmatically created block?

That's expected. You can do it from code if needed. The following are the steps to follow.

Settings definition is done as in block.block.test_block.yml. Place that file, after editing it, in my_module/config/install and you're set. A quick hack is managing the block settings manually in a local environment and export them from /admin/config/development/configuration/single/export.

Import your settings, which can be done using code similar to the following one.
use Drupal\Core\Config\FileStorage;

$config_path = drupal_get_path('module', 'my_module') . '/config/install';
$source = new FileStorage($config_path);
$config_storage = \Drupal::service('config.storage');
$block_config = 'block.block.test_block';
$config_storage->write($block_config , $source->read($block_config));

Block settings are theme dependent.

For dynamic allocation of blocks, you can load and alter the block entity like this.
use Drupal\block\Entity\Block;

$block = Block::load('test_block');
$block->setRegion('my_region');
$block->save();


Relationship: Choose "Content: Taxonomy terms on node" & "Jobtypes"
Field: Add "term id"(Exclude from display) with relationship
Field: Add Jobtypes Field and "Rewrite the output of this field" with token

such as:

[field_jobtypes]

will get each term with unique css class with its term id.


Does Drupal 7 use a publicly-available function to concatenate text in the "text area with summary" widget?

The code used to render that field is contained in text_field_formatter_view():

case 'text_summary_or_trimmed':
  foreach ($items as $delta => $item) {
    if (!empty($item['summary'])) {
      $output = _text_sanitize($instance, $langcode, $item, 'summary');
    }
    else {
      $output = _text_sanitize($instance, $langcode, $item, 'value');
      $output = text_summary($output, $instance['settings']['text_processing'] ? $item['format'] : NULL, $display['settings']['trim_length']);
    }
    $element[$delta] = array('#markup' => $output);
  }
  break;

You are interested in how $output is set. _text_sanitize() is a function that you can use to write similar code more specific for your case, while text_summary() is a generic enough function you can use for your own code.

function _text_sanitize($instance, $langcode, $item, $column) {
  // If the value uses a cacheable text format, text_field_load() precomputes
  // the sanitized string.
  if (isset($item["safe_$column"])) {
    return $item["safe_$column"];
  }
  return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
}


How do I add a date format to custom block output

You should use date_format (Drupal function).


A workaround may be to add a class to the form which you could then use to style the fieldset:

$form['#attributes']['class'][] = 'my-fieldset-error';


How to override some admin theme CSS rules?

I did it just using:

function mymodule_preprocess_html(&$variables) {

  global $theme;

  if ($theme === variable_get('admin_theme', 'seven')) {

    // Reference your custom stylesheet.
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/mymodule.css', array('weight' => CSS_THEME));
  }
}

That's a bit more readable for me.


Get labels from fields ordered on block plugin - Drupal 8

I solved it loading the field definition using entityManager, I got the weight attribute, and then ordered the labels by weight.

$node = $this->requestStack->getCurrentRequest()->get('node');
$bundle = $node->getType();
$view_mode = 'full';

$fields = [];
foreach($this->entityManager->getFieldDefinitions('node', $bundle)  as $field_name => $field_definition) {
  if($field_definition->getType() == 'entity_reference_revisions') {
    $field_name = $field_definition->getName();
    $element = $node->$field_name->view($view_mode);
    $fields[] = [
      'name' => $field_name,
      'label' => $field_definition->getLabel(),
      'weight' => $element['#weight'],
    ];

  }
}

usort($fields, [$this, 'sortByWeight']);


How can I get my module to see the current language my user is using?

You could try the following:

$lang_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
Node::load(10)->getTranslation($lang_code)->toArray();

Good luck!


What is the correct way to programatically set node type options?

Looking at the code for node_type_form_submit you can see that the variables are set before the node_type_save() function is called. Thinking about it a bit, it doesn't really matter as the node type info is saved into a different table than variables. So as long as the variables are being set synchronously with the creation of the node type, it shouldn't matter. Even then, the worst case scenario would be you'll have some redundant variables in the variables table. Which is not a big issue.

So to answer the question, yes that's the proper way. However I'd do it in the same function call in the .install file, maybe implement it in hook_install or hook_enable depending on what you need.


I think the issue here is that Twig debug does not suggest all possible names.

Names containing the view display id or type are possible, but don't seem to be suggested by Twig debug.

The following are the possible template names sorted by precedence:

[base template name]--[view machine name]--[view display id].html.twig
[base template name]--[view machine name]--[view display type].html.twig
[base template name]--[view display type].html.twig
[base template name]--[view machine name].html.twig
[base template name].html.twig


How can I remove preview button from contact form?

A custom module can utilize hook_form_alter() to strip out the preview button form element in any form:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // Look for any form provided by the contact module.
  // If you want to target a specific form you'll use the whole form ID
  // (e.g. Website feedback = 'contact_message_feedback_form').
  if (strpos($form_id, 'contact_message_') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
  }
}


All images within my articles have a link of their own: why?

All entities in drupal have their own page, you can use the Rabbit hole module to control what should happen when an entity is being viewed at its own page.
Inside module there is a sub-modules for each entity type, you have to install rabbit_hole and rh_file.


How can I use an URL (being a field content) as a contextual filter in views?

I found a much simpler solution than what I was trying to do: I used node references. That's exactly what I needed but I wasn't aware of the existence of this functionality. So yes, the solution is simply to use a node reference to link the 'Article page' to the 'Author page'.


Modifying the default user registration page

I use this way to custom my user login page, I think u can also custom form and use same validate/submit function like user_register_form  did

$form['#validate'][] = 'user_register_validate';
$form['#submit'][] = 'user_register_submit';


Why is my site's homepage loading in static mode?

I was able to solved this problem by updating drupal core to latest version. If you were able to encounter problem like this and you have the latest version of drupal try to downgrade it to replace corrupted core files and update it again to latest version. I don't know what really caused the problem but this will solve the problem. Just run drush pm-update in your drush and it will update all modules and drupal core latest releases. If you only want to update drupal core run drush up drupal. If you want to downgrade drupal add the version drush up drupal-7.x.


Displaying taxonomy terms and its contents with views

Open a view you have create

1) set the path: /categories

2) add a CONTEXTUAL FILTERS as

3) OR add a RELATIONSHIPS as

after save a view


Extending the content administration pages

I would recommend you to have a look at the Views Bulk Operations module. With VBO you can create custom views with any exposed filters and criteria you need. VBO adds to every row a checkbox which can fire different operations which you also can define on the view itself.


Approach to create a custom search form for an apache solr search

I usually use Search API and Search API Solr. And for setting up the site layout I use Panels and Panels everywhere, so my answer will be using those modules. I'm not that familiar with Apache Solr Search but maybe it's doable with that module also. It would be interesting to hear other solutions :)

The fields you want to filter by could be built using Facet API. One thing that's pretty awesome is that the facets are shown depending on the search result. So the facet will only show filters that have results.

The tricky bit is that a facet can only be shown (as far as I know) by a query that has been run. To do this I would create a Search API view that uses you Search API index. Setup a views content pane that shows your search result. Then create a display of the type context in Views.

In your site template (setup using Panels everywhere)
Insert the view by adding a pane where you want the search result to be shown. Add your views context as a context to the panel under Contexts. Then add your facets to the region you want them to show.

Then you probably want some caching on the views context so that it doesn't fire off a query on each page load :)

Another approach as you mention would be building a custom form and redirect the user to the search page /search?q=filter or to the search page and "prefill" the facet on the search page with the filter value (ie /search?facet-argument=X).

The options in the filter list could be fetched with an entity field query so that you fetch all values for the field you want to filter by. Then cache the result of that for X min/hours so that it doesn't load your site.


Table with sqlsrv driver is not showing headers or pagination

theme_pager() only works in combination with pager_query() (Or the PagerDefault extender in Drupal 7). And that function is obviously not going to work with sqlsrv().

For Drupal 7, there is the http://drupal.org/project/sqlsrv project, which is properly integrated into the new database abstraction layer. I suggest you have a look at the following answer to see how you might be able to use that in Drupal 6: MSSql or SQL Server Wrapper for custom module? See also How do you make sortable tables with a pager with data from a custom table? for how to create paginated queries with Drupal 7/the DBTNG project.


Is there any alternate module of drupal core search form?

Drupal core search is not all that optimal, it is really only meant for small sites as the implemented architecture does not scale all that well.

Most sites with a larger number of content commonly tend to integrate Solr


Adding a "processed" flag to a Drupal Webform, that admins can use to indicate whether or not they've dealt with a particular submission?

We have a similar thing where two fields are marked as Private and these are only seen by admins.

We also only allow authenticated users to submit these type of forms.


Form custom with method GET remove form_build_id and op from GET variables

You need to alter the form after it has been built, for example

$build = [];
$build['filter'] = $this->formBuilder->getForm(LibrarySearch::class);
$build['filter']['form_id']['#access'] = FALSE;
$build['filter']['form_build_id']['#access'] = FALSE;
$build['filter']['form_token']['#access'] = FALSE;

Once the form has been turned into a render array, you can set the access to FALSE for those items. This is also documented in the core Search module.


Why does the eMail in my Rules Component use a theme that differs from page-theme?

You may want to check the result you get if you do NOT tell Mime Mail to use the site's stylesheet. And combine this with creating a file in your theme that is named mail.css. If you do that, then Mime Mail should automatically use that when sending emails. For more details on that, refer to its README.txt, i.e.:

  Email messages are formatted using the mimemail-message.tpl.php template.
  This includes a CSS style sheet and uses an HTML version of the text.
  The included CSS is either:

  the mail.css file found anywhere in your theme folder or
  the combined CSS style sheets of your theme if enabled.

Also make sure your theme is set as "Theme to render the emails" within admin/config/system/mailsystem. Without that, the stylesheets used by emails sent via cron (for example) may not look like you want them to look.


You should be able to just copy what that linkedin code is doing in it's own linkedin_user_settings_form_submit submit function:

$op = $form_state['values']['op'];
if ($op == $form['linkedin']['reset']['#value']) {
 drupal_set_message(t('LinkedIn preferences have been reset'));
} else {
  drupal_set_message(t('LinkedIn preferences have been saved'));
}


While theoretically now supported, that is not possible not like this.

You can not reliable load a node based on the node title, it is not guaranteed to be unique, and to become a practical URL, a number of replacements should be made, like replacing spaces, lowercasing it and so on.

Use the path alias system for this, just like in Drupal 7. We're maintaining an inofficial port of the pathauto module, that allows you to configure token patterns to automatically generate an alias for each node. You also need token.module, which you can get from here.


This is too vague to really answer well. A View may be slow for any number of reasons, but at a minimum, this View is loading 200 entities and potentially 400 if you're joining to products (or any other entity). You're going to need some pretty aggressive query caching, both at the database level and likely at the Views level, to perform at that scale of carts without having to change the way Drupal Commerce loads / manages cart orders.


Jquery in ajaxed loaded content referencing incorrect node id

Looks like Drupal.attachBehaviors should have fired on (target) instead of (context). It was refiring the script on the whole context instead of just the new ajaxed content. So I changed Drupal.attachBehaviors(context); to Drupal.attachBehaviors(target);

Now it works!


There are two ways to manage access to content with the User Relationships module.

The node access module allows you to open up access to nodes to friends but does not provide any way to remove that access, you'll need another module to do that.

The panels module allows you to show and hide panes based on whether or not a relationship exists.


The Drush extras project has commands for administering blocks.

Short instructions (following their README.txt):

Install this Drush add-on:

drush dl drush_extras

Determine desired module name and delta of block, and the desired region name and weight for adding the block:

drush block-show

Add the block to the region:

drush block-configure --module=block_module --delta=block_delta \
  --region=region_name --weight=-12

More instructions via:

drush help block-show
drush help block-configure
drush help block-disable


how to display a gallery of custom themes

The ThemeKey module would help you to achieve this.

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


Is there a nodecomment equivalent/replacement for D7?

@Chris You started me down the right path, thanks so much! I've tested and can implement it this way without writing any custom code:

Create 3 content types: Helpdesk Ticket, Ticket Internal Note, Ticket External Note.
Create a role called Helpdesk Volunteer.
Put a node reference field on Ticket Internal Note and Ticket External Note using the node reference URL widget.
Use the Content Access module (currently still in dev) to restrict view/edit/delete of the Ticket Internal Note content type to users in the Helpdesk Volunteer role.
Create a view with EVA that attaches to the Helpdesk Ticket content type, set to display both internal and external notes.

Afterwards, it's just a touch of prettification and theming as needed. Add a file attachment upload field and a ticket category. Maybe implement messaging/notifications to have email notifications and reply-by-email. Fully functional helpdesk on D7!


Custom block template PHP page, possible to make content editable in UI?

What you're describing is already in Drupal 7 core. It's called the Contextual Links module. When enabled, modules can define menu paths that enable a set of links that is contextually relevant to the content.

In your case, a user with Use contextual links & Administer block permissions will see a gear icon that produces a dropdown link from where they can configure & edit content of any custom block.


Easy PHP, Radioactivity module: Read out a node's current energy?

My guess is that it is something like

float($entity->field_energy['und'][0]['value']);

Also, you can do

print_r ($entity->field_energy);

to see what is contained in object.

also, it may be contained in node object so maybe it is

float($node->field_energy['und'][0]['value']);

My blind guess but it may help you :)


Is it possible to attach a single field collection to multiple nodes? (And so make updating easier)

You have to write custom module for this and use hook_node_presave($node) to save fieldcollection value of other node into this and save node.

Then check your DB, now single fc attached to other node(s).


Drupal 7 doesn't use %placeholder style query placeholders. Furthermore, there's an error passing a list of strings to db_query instead of an array.

Your query would be

db_query('UPDATE {users} SET name = :name, mail = :mail WHERE uid = :uid',
           array(':name' => $name, ':mail' => $mail, ':uid' => $account->uid));

However, you should probably use db_update for update queries, in which case it would indeed be:

db_update('users')
->fields(array(
    'name' => $name,
    'mail' => $mail
))
->condition('uid', $account->uid)
->execute();

You error is occurring because the initial db_query accepts an array of parameters in D7.

More info:
https://api.drupal.org/api/drupal/includes%21database%21database.inc/group/database/7


How to use views hooks - specifically hook_view_data()?

Views does have complete documentation for that hook, but it's not in the most obvious place.

If you install the Advanced Help module and go to http://mysite.com/help/views/api-tables you'll find the Describing tables to Views help page which contains extensive documentation and code samples.

You can also find the full Views' API docs at http://mysite.com/help/views/api with that module installed.

On top of that, the list of functions that implement hook_views_data() would also be worth a look. The aggregator, book and node module implementations look to be well commented at first glance.


Utilizing private methods/vars inside module

Yes - it's that simple. Remember; Drupal is only PHP.

Although your class should be called MyClass.php rather than MyClass.class.php to adhere to the Drupal Coding Standards for OO code (note - this isn't explicitly declared, but is hinted at when they describe the Interface file naming conventions).

Just to pad this out a bit; you could also use the X Autoload module to allow for PSR-4 style autoloading instead of adding your class in the files[] array. I do this for as much D7 code as possible now (where I'm not using Composer Manager), and would whole heartedly recommend it.

  xautoload is a comprehensive and yet highly efficient PHP class
  loading suite.

  Most importantly, it provides Drupal-8-style PSR-4 (and the old D8
  PSR-0-style in "lib") autoloading for Drupal 7. But it is also a great
  tool for 3rd party autoloading.


Reset a form element value through AjaxResponse

You can try the code below

$response->addCommand(new InvokeCommand('#field_id','val',['']));

The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given selector. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc.

This command is implemented by Drupal.AjaxCommands.prototype.invoke() defined in misc/ajax.js.

Please see InvokeCommand


How do I hook before the user is created in Behat tests?

Somewhat predictably, which I'm pretty sure is deliberate, it's @beforeUserCreate.

The Drupal Extension Hooks section of the docs has a bit of background in case you need it.


How can I remove a property from an entity in Drupal 7

You're looking for db_drop_field(). Although it's called a "field" here, it's essentially the remove-a-column-from-the-DB-table function.

Example from filter_update_7005():

// Drop the roles field from the {filter_format} table.
db_drop_field('filter_format', 'roles');


Content export and import / content deployment

The Default Content module uses cores REST/HAL/Serialisation API's to export content to JSON. You put the content into you_module/content/[entity_type]/anything.json and the content is automatically imported when you enable your module.


How to return a user's group access permissions?

The Group class has a userHasPermission() method you can use. So something like this:

if ($group->userHasPermission($user->uid, 'some permission')) {
  // do something.
}


How might I find a render array of a parent OG group?

I did the following to achieve this. I'm still not happy with the results but given time pressures, it'll have to do. I'm posting to see if anyone can suggests a better alternative.

I grab the nid of the parent group first and use it to do a query against menu_links. Once I have a result of a menu_id(s), we loop through, get the links, use theme(), and then drupal_add_region_content().

<?php
/**
 *
 *
 * This module creates a block that looks for any parent OG group and displays the menu of that
 * group.
 */

define('_OGPN_NODETYPE', 'user_posted_content');
define('_OGPARENTNAME_TITLE', 'OG Parent Menu');

/**
 * Implements hook_block_info().
 */
function ogparentmenu_block_info() {
    // This example comes from node.module.
    $blocks['_ogparentmenu'] = array(
        'info' => t(_OGPARENTNAME_TITLE),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function ogparentmenu_block_view($delta = '') {
        return [
            'subject' => t(_OGPARENTNAME_TITLE),
            'content' => __ogparentmenu(),
        ] ;
}

/**
 * @return string
 * @throws Exception
 */
function __ogparentmenu() {

    $node = menu_get_object();

    /* Set up menu on UserPosts  */
    if ($node->type == _OGPN_NODETYPE) {

        // get parent link of og
        $parent_og = filter_var($node->og_group_ref[LANGUAGE_NONE][0]['target_id'], FILTER_SANITIZE_NUMBER_INT);

        // Query menu_links based on node/$nid path
        $menu_query = db_select('menu_links', 'ml')
            ->fields('ml', ['menu_name', 'mlid'])
            ->condition('link_path', "node/$parent_og", '=')
            ->execute();

        // if single
        if ($menu_query->rowCount() == 1) {
            $menu_id = check_plain($menu_query->fetchAs()['menu_name']);
            $links = menu_navigation_links($menu_id);

            $themed_menu = theme('links__system_main_menu', [
                '#title' => t('title'),
                'links' => $links,
                'attributes' => [
                    'class' => ['user_post_menu_injected', 'section']
                ],

            ]);

            return $themed_menu;

        }
        // TO DO : handle multiple
        elseif ($menu_query->rowCount() > 1) {

            return 'null';
        }

    }
}


How do I access the variables posted in a page callback?

By default, Drupal looks for two functions on form submission (for forms generated with the Form API): {$form_name}_validate() and {$form_name}_submit();

For what you are trying to do, you need to implement the submit handler, do something with the form values (store to session, database, etc) and then go to page that will display the values of the form.  I've mocked up a quick and dirty module so you can see a couple different approaches:

function mymodule_menu(){

  $items = array();

  $items['sample_form'] = array(
     'title' => t('Sample Form'),
     'access arguments' => array('access content'),
     'page callback' => 'drupal_get_form',
     'page arguments' => array('mymodule_sample_form'),
  );

  $items['sample_form/success/%'] = array(
     'title' => t('Sample Form | Success'),
     'access arguments' => array('access content'),
     'page callback' => 'mymodules_sample_form_success',
     'page arguments' => array(2), //pass value of field_two to callback function
  );

  return $items;
}

function mymodule_sample_form($form, &$form_state){

    $form['field_one'] = array(
      '#type' => 'textfield',
      '#title' => t('Field One'),
    );

    $form['field_two'] = array(
      '#type' => 'textfield',
      '#title' => t('Field Two'),
    );

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

    return $form;
}

function mymodule_sample_form_submit($form, &$form_state){

  //This is where you process and store submitted values.
  //Lets use variable_set to store the value
  variable_set('mymodule_field_one', $form_state['values']['field_one']);

  //Ok, lets now redirect the user to the success page and pass field_two as an argument
  $form_state['redirect'] = url('sample_form/success/'.$form_state['values']['field_two'], array('absolute'=>true));
}

function mymodules_sample_form_success($field_two){

  $output = 'Value for field one: '. variable_get('mymodule_field_one').'
';
  $output .= 'Value for field two: '. $field_two.'
';

  //Lets display the form again, rebuilt.
  $output .= drupal_render(drupal_get_form('mymodule_sample_form'));

  return $output;
}


How do I get $form_state from hook_entity_update()?

$form_state is not available there.

You might want to consider using fields and widgets, then you get a lot for free.

If that's not an option then you can register a so called #entity_builder:

function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
  // ...
  $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
}

function menu_ui_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $type->setThirdPartySetting('menu_ui', 'available_menus', array_values(array_filter($form_state->getValue('menu_options'))));
  $type->setThirdPartySetting('menu_ui', 'parent', $form_state->getValue('menu_parent'));
}

The example is for the node type config entity, but it should work pretty much the same way for a content entity. book_form_node_form_alter() is an example for nodes.


How to Import content without affecting existing contents

Looking at the modules in question it states that the purpose is "...to export data from a site into datasets. These datasets are then imported into another site in such a way that the two sites end up with EXACTLY THE SAME DATA INCLUDING ID NUMBERS."

Looking at the drush commands the module provides there are not arguments to maintain any 'current' data. It will force the state of the dataset.


Unable to set #default_value for a date field

Set it like this

$form['filter_dates']['start_date'] = [
    '#type' => 'date',
    '#title' => $this->t('From'),
    '#description' => $this->t('Start event date'),
       '#default_value' => [
        '2015-05-09',
    ]
];


How can I use the administration theme for the user/%/edit page?

That path is already one that will use the admin theme if the current user has the correct permissions to access it.

Try going to http://mysite.com/admin/people/permissions and checking the "View the administration theme" permission for the roles you wish to be able to use the admin theme.

It'll definitely work as the User module implements hook_admin_paths() to define that path as an admin page:

function user_admin_paths() {
  $paths = array(
    'user/*/cancel' => TRUE,
    'user/*/edit' => TRUE,
    'user/*/edit/*' => TRUE,
  );
  return $paths;
}


Can a Panel be converted to a Mini-Panel?

Yes and no.  Panels is a module with a whack of facets.  Based upon the context of your question it sounds like you created a page via the panels interface.  So.  That's a page and that's why you can only really link to it ( or override another drupal generated page.

Mini panels are exposed as blocks and also as elements usable in other panel facets (like pages or other mini blocks).

You'll have to create a new mini panel from scratch but all the elements you used to create that custom page are available to you.  If you made custom elements just check the make reusable and then they'll be available to your mini panel.


Ok, I've thought of a solution that somewhat inelegant, but it works

On the Equipment content type, a hex/dec signifier field is added--some sort of a select box (maybe a taxonomy selection box) where the user will select if the serial number in hex or dec.

When the form is submitted, a custom rule will check for the presence of the select box, convert the value in the "title" to the other numbering format, and then append that value to the original value in the title field, so that the title field will contain both formats of the number. After everything is said and done, the Equipment titles will all look like "1234567, 12D687".

Now, when the user creates an order and searches for existing serial numbers using the Inline Entity Form, as long as you have it set to "autocomplete", it will find the correct piece of equipment and associate it with the order.

Still, it would be nice if Entity Reference auto-complete would work with fields from those entities and not just their titles.  And, I'm still in needs of some sort of module that will add a hex converter to Rules.

Let me know if anyone finds better solutions!


Find users who have not uploaded certain contents in last 30 days

SQL is evaluated backwards, from right to left. So the WHERE clause is parsed and evaluate prior to the SELECT clause. Because of this the aliasing of MAX(created) to max_created not yet occurred.

You can try this,

  SELECT uid, MAX(created) FROM node WHERE node.type IN ('page','story')
  HAVING MAX(created) < UNIX_TIMESTAMP()-2592000


Views Search Terms not working correctly for taxonomy terms with multiple words

This turned out to be a bug with the search score feature discussed here https://www.drupal.org/node/1615438.

This comment details that checking the "Remove search score" checkbox under the Search: Search Terms filter fixes that problem.


Get the title attribute into a lightbox frame

There are multiple issues for Lightbox about your problem. Atm your best chance is indeed to override the relevant tpl.php file. This would be in the form of views-view-field--viewid--fieldname.tpl.php. The variables exposed in there that are of interest are the following:

$output: The processed output that will normally be used.
$row: The raw SQL result that can be used.

The first one indeed contains a string in the form of:

The above should become something like this:

in order to have a caption in your lightbox.

You could of course use a replace function in order to achieve this, such as your attempted solution.

What I recommend is to use the $row variable to obtain the data itself and construct the output however you wish, for instance to add a title in  as well and why not solve the empty alt attribute value issue as well for the sake of SEO:

<?php
  //print $output;
  //dpm($output);
  //dpm($row);
  $caption = $row->taxonomy_term_data_name, // HERE use your field of choice
  print l(
    theme_image_style(array(
      'style_name' => 'thumbnail',
      'path' => $row->field_field_image[0]['raw']['uri'],
      'alt' => $caption,
      'attributes' => array('typeof' => 'foaf:Image'),
      'width' => NULL,
      'height' => NULL,
    )),
    image_style_url('large', $row->field_field_image[0]['raw']['uri']),
    array(
      'attributes' => array(
        'title' => $caption,
        'rel' =>
          'lightbox[field_image][
' . $caption . '
]',
      ),
      'html' => TRUE,
    )
  );
?>


Horizontal scrolling in Safari on one content type only when logged out?

Looking though the markup, the problem is on the H2 for your search form.

Search form

Can't say exactly what's up, but if you take off the width from .level1 h2, .related h2, .tabTog h2 then it seems to be fine.


My custom page.tpl.php file is not picked up

have you seen through your theme suggestions for the about page?

If not, then please refer to it and create a tpl file according to the suggestions and you will see that particular template running for "about" page.

As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments).

  To enable it, add this line to your settings.php:

$conf['theme_debug'] = TRUE;

  OR,
  You can enable it with drush using:

drush vset theme_debug 1

  And disable using

drush vset theme_debug 0

Note: You'll then see output like this when you inspect or view source:

<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.tpl.php
   * page--node.tpl.php
   x page.tpl.php
-->
<!-- BEGIN OUTPUT from 'modules/system/page.tpl.php' -->
…
<!-- END OUTPUT from 'modules/system/page.tpl.php' -->


How do I restrict view/edit access to a custom content type node to only the user it belongs to?

You can use the Node access user reference module.

  Gives content access permissions to users for content that references the users with User reference or Entity reference.


Seeking an approach to maintain a drupal site from a mobile platform

I don't know about the qualitiy of this app, but could

Drupad - Drupal on the go (iPhone/iPad App)

help you?

App description:

Features for webmaster

Manage any number of websites
Create and edit content (CCK, Fields API support)
Search and edit user accounts
Read, post, moderate comments
Moderate your content
Mollom™ support
Promote, sticky, publish, unpublish nodes
Manage your users, send them email etc.
Gravatar™ fallback for User's picture
Drag to refresh and to load more content
Built-in web browser
Optimized to be fast in 3G or Wifi


How can I understand when hook_form_alter() is called?

The lifetime cycle of a form and its stages depends on whether the form is rebuilding and using Ajax. Most times you react then on the form action you find in:
$form_state->getTriggeringElement()
The two different calls between page load and before the first submit is because the original form build is not cached and then has to be built the same way as the first one. Normally you don't care and alter the form build the same way for each call. If you need to make a distinction between both calls you find the raw submitted values in $form_state->getUserInput()


you need to specify the format value 'format' => 'filtered_html' to allow filtered html or '#format' => 'full_html'

$form['terms_format'][implode('~', array(MODULE_NAME, FIELD_TERMS))] = array(
    '#title'         => t('Terms and Conditions')
   ,'#type'          => 'textarea'
   ,'#description'   => t('Terms and conditiona')
   ,'#default_value' => variable_get(implode('~', array(MODULE_NAME, FIELD_TERMS)), "")
   ,'#required'      => TRUE
   'format' => 'filtered_html',
);

For drupal 6 try

if (!isset($edit['format'])) {
  $edit['format'] = FILTER_FORMAT_DEFAULT;
}
$form['terms_format']['format'] = filter_form($edit['format']);

Make sure your default filter format is filtered html or full html


Install a theme with its demo content -- via command line?

You can import the database using drush rather than phpMyAdmin.

Create a standard drupal 8 site, go to the /sites/default directory and run

drush sql-cli < databasefilename.sql

See the importing database section here http://tylerfrankenstein.com/code/use-drush-export-import-drupal-mysql-database-dump-file


How can I create an "allow anything" field on a node?

I would create a new text format for that:

Go to admin/config/content/formats/add
Select the filters you want to add (in your case probably no filters at all)
Add a textarea field on your content type and select this text format you just created.


Is 8.6.18 insecure? Will there be 8.6.19 etc.?

According to the Drupal core release cycle documentation, the last month for security coverage for 8.6 was November 2019. There is no more planned security coverage for 8.6.

Security releases only last through the next minor release cycle. I.e. 1.0 will receive patch and security releases until 1.1 is released. Then 1.0 will continue to receive security coverage until 1.2 is released. Once 1.2 is released (the second minor release since 1.0), 1.0 is considered unsupported.


How to let users subscribe and be notified (email) when certain type of content or taxonomy is created?

You could do the subscription by adding the taxonomie term to the user profile. If you don't have to many content types you could add it as a simple select list to the profile. This can be done at admin/config/people/accounts/fields.

As you sugested you can use Rules to get triggered about creates/updates of content or taxonomy terms. You might have to implement custom rules conditions or actions in PHP in a custom module to get exactly what you need. Check the differen hooks to define your own rules conditions or actions. hook_rules_action_info and hook_rules_condition_info are the most interesting for you.

To lear how to build your own rules code you find many examples in Drupal core and contributed modules.


To make sure nobody submit the form create a custom validate function that always set error on form ,(using form_set_error).

In that validate function you have to check for the circunstnaces that makes the form available to submission or not.


You can set

Find out more about [name]

(without the anchor tag) in Rewrite the output of this field, and then use the Output this field as a link option and set that to

taxonomy/term/[tid]

Views will rewrite the link according to Url Alias settings.


How to convert the drupal-entity tag into an img tag?

Basically you'll want to get the field's value and do a str_replace(), but where?

I haven't done this myself yet, but I believe you'll have to create a normalizer.

Serialization API overview (good read).

I think you can achieve it by doing the following Changing the way Serializer handles entities.

There is more indepth info here Using Normalizers to Alter REST JSON Structure in Drupal 8.


Order item with persistent custom field value

I couldn't find a more elegant way but this works for me.
First I rebuild the purchased entity link in the commerce cart form view to include the custom text field value as a parameter in the link URL for when I navigate back from the cart to the product variation:
/**
 * Implements hook_preprocess_views_view_field().
 */
function MYMODULE_preprocess_views_view_field(&$variables) {

  $view = $variables['view'];
  $field = $variables['field'];

  // Commerce cart form
  if (isset($view) && ($view->id() === 'commerce_cart_form')) {

    switch($field->field) {
      case 'purchased_entity':

        // Get purchased entity
        $purchased_entity = $variables['row']->_relationship_entities['order_items']->purchased_entity->getValue();
        $purchased_entity_id = $purchased_entity[0]['target_id'];

        // Load product variation
        $product_variation = $variation = ProductVariation::load($purchased_entity_id);

        // Get product variation URL
        $url = Url::fromUserInput($product_variation->toLink()->getUrl()->toString());

        // Get custom field value
        $custom_field = $variables['row']->_relationship_entities['order_items']->field_custom->getValue();

        // Rebuild url with variation & custom field value
        $url->setOption('query', [
          'v' => $purchased_entity_id,
          'custom' => $custom_field[0]['value'],
        ]);

        // Output
        $variables['output'] = Link::fromTextAndUrl(t($product_variation->label()), $url);

        break;
    }
  }
}

This will output a link like /product/1?v=2&custom=MYVALUE
And then on the product add to cart form, if the param is in the URL, I set the default value of the custom field:
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if (strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce_product_') !== false) {

    // Set custom text form field value from URL
    $form['field_custom']['widget'][0]['value']['#default_value'] = \Drupal::request()->query->get('custom');
  }
}


How are drush and jenkins used together for continuous integration?

For my projects, I use a build script made of Drush commands in a Jenkins job. I use my Phing Drush Task project to run Drush from a Phing build script. This allow me to leverage the existing Phing tasks (eg. files copy, phplint, etc.). With the help of Drush, this build script

Downloads all non-custom code (ie. Drupal core and contribs module and themes) with Drush Make to ./dist
Expands placeholders in a versioned settings.php (ie. replace ${db_host} with the actual DB hostname) while copying it to the freshly downloaded ./dist/sites/default folder.
Copy custom modules and themes to ./dist/sites/all/modules/custom and ./dist/sites/all/themes/custom
Run phplint for all files from my custom modules and themes.
Copy everything under ./dist to a pre-configured webroot.
Run drush site-install testing and drush pm-enable simpletest to install a fresh site using the build code base and able to run SimpleTest.
Run drush test-run to run my custom module test suites.
Run drush coder-review.

Here is a commented build.xml template for Drush usage in Jenkins.


Try to run drush command : drush vset clean_url 0 --yes

or

Include a line in settings.php : $conf['clean_url'] = 0;

Updated :

Check this LINK. There are many ways to disable the clean url.


Multiple forms one page always submit with the values of the first

To use multiple instances of the same form on a page you need to implement hook_forms(), which allows you to essentially use 'aliases' for your forms.

function hook_forms($form_id, $args)
{
  $forms = array();

  // Check if the form id is of the pattern add_to_collection_form-[NUMBER]
  if(preg_match('/^add_to_collection_form-\d+$/', $form_id)
  {
    $forms[$form_id]['callback'] = 'add_to_collection_form';
  }

  return $forms;
}

The above code tells Drupal that if a form ID has the pattern add_to_collection_form-[NUMBER], to use the add_to_collection_form form callback.

Now you can call the forms on your page like this:

drupal_get_form('add_to_collection_form-1', $node->nid);
drupal_get_form('add_to_collection_form-2', $node->nid);
drupal_get_form('add_to_collection_form-3', $node->nid);


Drupal 7 views add one field as a URL to another

for the Title, set it 'Exclude from display'
for the File attachments, 'Rewrite the output of this field' using the token for Title

Make sure the Title field appears above the file attachment, or the file attachment won't recognize it as a valid token when rewriting the output


Returning alternate HTTP codes for unpublished content

I haven't tried this myself, but I think the main problem is that in your cases, the "unpublished status" means two things.

I think your best bet is to use something like Workbench Moderation, and defined a "retired" state.  Then, in a hoot_init(), check the status, and generate the 410.

Something like:

function mymodule_init ()
{
   $node = menu_get_object();
   if (isset($node->nid) && this_is_a_retired_node($node)) {
     drupal_add_http_header('Status', '410 Gone');
     drupal_exit(); // may want exit instead; not sure of other hook_inits()s should run
   }
}

I think you have to take the sledgehammer approach so that you don't get too far into the request where you may have a race condition with other modules.


Drupal combine nodes and comments in view

Add 'Comment' as a node type to display in the view but keep your 'Note' content type filter. You should get both the nodes and the comments associated with any of those nodes, which you can then add an exposed filter to for date.


Multiple relationships in Views Contextual Filters

Use this module:  https://www.drupal.org/project/views_contextual_filters_or
it gives you posibility to achive your needs


How do I change the default value of a field with AJAX?

Method 1 setting #value does indeed make it impossible for the user to input data.

So the method 2 setting #default_value is I think still the best approach. As the old trick from D7, unsetting the value in $form_state, doesn't work anymore, you can try this one:

Create the field in a subkey, which is incremented for each request. Set the property #tree on the first level of the field, so you get back the field value as array [$key => $value]:

$form['wrapper']['options']['field1']['#tree'] = TRUE;

if ($form_state->hasValue('field1')) {
  $key = key($form_state->getValue('field1'));
  $value_field1 = current($form_state->getValue('field1'));
  $key++;
}
else {
  $key = '0';
  $value_field1 = NULL;
}

// insert logic to determine new field value
// but check, if there is user input in $value_field1, that you don't want to overwrite

$form['wrapper']['options']['field1'][$key] = [
  '#type' => 'textfield',
  '#title' => 'Text 1',
  '#default_value' => $value_field1,
];


How do I have points and polygons in the same Leaflet map?

Nigel Waters has it correct. Here are the details. I did this for cities and states. I used points for cities and polygons for states. Here are the steps.

Requirements:

Geofield module
Leaflet module
Leaflet Views module (a submodule of Leaflet)

Steps:

Create the two content types: City and State.
Create a field of type Geofield, call it "Location"
Choose GeoJSON as the field widget
Add the Location field to both content types
Create a city. For location enter GeoJSON Point data
Create a state. For location enter a GeoJSON Polygon data
Create a view with a Page display
Add the Location field to the view
Filter the view by State and City content types
Set the Format of the view to Leaflet Map
Your view should now look like pic 1
Click on View Page
You should see a map like pic 2


Drush up error - unable to untar - Destination already exsists

I've had a similar problem in the past.  It looks like there's already a /home/sites/lg/public_html/drupal-7.26 (at least based on your post).  Make sure you have read / write access to it.  Better yet, run drush as root or under sudo.


How to represent media as individual entities?

There is a module called Media entity. Some more details about it, from its project page:

Media entity provides a 'base' entity for media. This is a very basic entity which can reference to all kinds of media-objects (local files, YouTube videos, Tweets, Instagram photos, ...). Media entity provides a relation between Drupal and the media resource. You can reference to/use this entity within any other Drupal entity.
This module attempts to provide the base storage component for the Drupal 8 media ecosystem.

I think that it will do what you want.


Individual CCK Imagefield promote-to-front

Here is another option, that will work for sure.  May need to do a bit of reconfiguring with your current imagefields.

Download latest version of CCK 3.x.
Install multigroups module (currently this module is stable)

On the selected content type:

Add on/off checkbox featured field (set limit to 1)
Add Image field (set limit to 1)
Encapsulate theses 2 fields in a multigroup (set limit to unlimited)
Create view that will filter on featured field


This is indeed very simple. You can add fields to the comment entity.
Have a look at these explanations of how o achieve this:

http://kps3.com/thots/adding-new-fields-to-comments-in-drupal-7

https://www.ostraining.com/blog/drupal/entities/


How to get a list of entities programmatically?

From the very beginning, I went the wrong way. The problem is solved with the vievs_rules module. I made a view of simplenews subscribers, with relations with subscriber:email and subscription:category, then added filters by term (subscription category), by user (active or not) and subscription status. I used a user entity as resulting variable. Then I just imported the view into views loop (Rules UI) and voila!

Very thanks to @Pierre.Vriens for pointing me to views_rules


how to set Default time zone and date format

You can set default timezone and whether user should be able to edit default timezone settings or not.

Go to Regional and language settings:

http://yousite.com/admin/config/regional/settings

And uncheck : Users may set their own time zone.

On same page other settings also available. See :

To add any new format you can add from here :

http://yousite.com/admin/config/regional/date-time


How to display a specific field instead of Title with Entity Reference

If you edit your entity reference field you'll see an "Entity Selection" fieldset section. There is a "Mode" field in there that defaults to "Simple" which just lists the entity titles.  You can change that to "Views" which lets you use a custom View to display the selection.

You'll want to create a View first. Just create the View to display the fields you want.  That could be the Cours Title and CoursRefNumber if you want.


Stopping a submit is best done in a validation function. You need to have this code in a custom validation handler that you add to the form, and then you set a validation error on it.

Learn how to add custom validation to an existing Drupal form

Redirecting on form validation fail seems to be a problem. Look here for workaround:

Redirect form in validation fail

As to hook_node_submit, the docs have this to say:

  Act on a node after validated form values have been copied to it.

  This hook is invoked when a node form is submitted with either the
  "Save" or "Preview" button, after form values have been copied to the
  form state's node object, but before the node is saved or previewed.
  It is a chance for modules to adjust the node's properties from what
  they are simply after a copy from $form_state['values']. This hook is
  intended for adjusting non-field-related properties. See
  hook_field_attach_submit() for customizing field-related properties.

This hook is not a good place to try and stop submission, as form validation has already passed. It is therefore assumed that the node should be saved to the db.


Adding accept attribute to managed_file field to specify file types client-side

Still not sure if this is a bona fide bug; the file_managed element has several elements inside it, so there's no real way to specify which of those you're targeting with the #attributes property.

So in one respect it does make sense that they'd be ignored, because of the ambiguity. But it works for classes, so it makes less sense. Would need a bit more digging to find out why I suspect.

Either way, you can work around it by adding your own process callback to the element:

$form['image_upload'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image upload'),
  '#description' => t('Upload png images'),
  '#upload_location' => 'public://',
  '#process' => array('file_managed_file_process', 'MYMODULE_file_managed_file_process'),
);

function MYMODULE_file_managed_file_process($element) {
  $element['upload']['#attributes']['accept'] = '.jpg';
  return $element;
}


Create secondary links in admin/menus/secondary links.

Once completed, go to blocks/list/, look for your secondary links, and place them in the footer block region.


How to disable auto create customer profile after edit order?

This is happening because the inline customer profile form has the country selected, which is all that's required for a field value to be present. I believe we should add a fix to Drupal Commerce core to prevent this, but I don't know off the top of my head if there's already an issue in the queue for it. Feel free to search at https://www.drupal.org/project/issues/commerce and file an issue if you don't see it already. Thanks!


create online "diagnostic" questionnaire with results based on choices

Maybe this helps: Module for decision tree / guided entry. There is nothing which appears do the job out of the box. So you need to evaluate the modules if they full fill your needs. I am going to check following modules to build a so called decision tree:

Decision Tree
D.A.I.L.
Core Book
Outline Designer
Choose Your Own Adventure
Hierarchical Select
Conditional Fields
... to be continued ;)


Drupal 7 ajax button added via ajax callback

I found the answer here.

I was because of the id of my button.


add and remove preassign role to user on completion of user profile

I never did something similar before, but I guess, rules module suits you like nothing else.

First of all you need 2 roles: users who just created and users who filled some profile fields. When admin creates a new user he set first (just created) role.

Then you create a new page view event (in rules core):

Create action load entity by id using site:current-user token (so you can access user profile fields in condition section);
In condition section, Check user role (only for just created);
In condition section, create condition for each profile field you wanna check (not empty or something similar);
Create action to redirect user to edit profile page.

So, each time when new user will load any site page, he will be redirected to edit profile page until he doesn't fill profile fields.

The second event is after profile save, assign new role "Fills some profile fields".
There is no difficult conditions, so I'm sure you can handle this event yourself.

If you need more complex solution, redirect on profile if only user load specific page you can try rules page. If you would like to redirect only once per session, you have to write your own rules condition through rules API or try out this one (never use this before).

I hope this could be helpfull for you, anyway wish you luck to find what you are really looking for.


How to redirect user after form submit in overlay mode?

This seems to be the working solution:

Inside your form:

$form['somebutton']['#submit'] = array('your_custom_callback');

Add a custom callback

function your_custom_callback($form, &$form_state) {
  //redirect users to Drupal.org
  $url = "http://drupal.org";

  if (module_exists('overlay') && overlay_get_mode() == 'child') {
    unset($_GET['destination']);
    overlay_close_dialog($url, array('external' => TRUE));
    $form_state['redirect'] = FALSE;
  } else {
    $form_state['redirect'] = $url;
  }
}


How to prevent login if a condition is not met

You can use sess_destroy_uid($account->uid).

You might also consider blocking users during the import process; this is done by setting the "status" column to 0.


How can I get pragmatically all certain actions from Rules and Components?

This function should do the trick:

/**
 * Find all rules with action name matching a string pattern
 *
 * @param $pattern
 *  String pattern to check action names
 *
 * @param $active
 *  Boolean whether to limit the search to active rules only
 *
 * @return
 *  Array with rule names with actions matching the pattern as keys and arrays of rule
 *  action names as values
 */
function search_rules_for_action($pattern, $active_only = TRUE) {
  $active_only = ($active_only) ? array('active' => 1) : array();
  $rules = rules_config_load_multiple(FALSE, $active_only);
  $matching_rules = array();
  foreach ($rules AS $rule_name => $rule) {
    if (method_exists($rule, 'actions') === TRUE) {
      foreach ($rule->actions() as $action) {
        if (method_exists($action, 'getElementName') == TRUE) {
          $action_name = $action->getElementName();
          if (stripos($action_name, $pattern) !== FALSE) {
            $matching_rules[$rule_name][] = $action_name;
          }
        }
      }
    }
  }
  return $matching_rules;
}


Multiple File Uploads fail when webform is placed in a block

Turns out that I had, due to custom markup added to the webform, nested <form> tags. Per the spec, this is a big no-no. What happens in the older browsers appeared to have been that the form AJAX submission tried to use the form ID of the most recent <form> tag, which, in my case, was empty. It triggered this in file.module:

if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
  // Invalid request.
  drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.',
    array('@size' => format_size(file_upload_max_size()))), 'error');
  ...
  ...

Removing the unneeded <form> tags resolved the issue.


Order total field, transactions and balance

There is no way via the user interface that I'm aware of to add lines to the order total display that lists out price components like this. However, via code you have the ability to alter the array of formatted price components however you want at the point of display.

Drupal Commerce 1.x includes hook_commerce_price_formatted_components_alter() for this, letting you alter existing rows in the components list or add some to it that wouldn't otherwise be included. You can add lines that check the payment transactions associated with an order to see how much has been paid and that use commerce_payment_order_balance() to show the balance.


Page cache not rebuilding after page cache maximum age is reached

The Internal Page Cache for anonymous users doesn't use any configuration option. If you want a quick solution in UI your only chance is to de-install this module.

Better for performance is to set an expiration time for the cached pages, but for this you need custom code, see this answer Anonymous user cache control.

In both cases the setting on the performance page is still necessary to set the correct headers for external caches.


Images not appearing into sites/default/files

I fixed this problem. Apparently it was a permissions issue with the default directory. I set it recursively to 777 and the client was able to post images without a problem. I just had to make sure to reset the permissions on the settings.php file.


Thanks for your input @JPMC. In the end I just used Simple Hierarchical Select and did what I wanted to do.


Permissions to see all users products, not just the orders on UberCart

The permission manage products must be turned off. The permission for to create a product, edit and delete own product must be turned on.


Adding a call to drupal_add_js() directly in hook_menu() doesn't work; the call to drupal_add_js() should be added on the code that is executed when Drupal is outputting a page. This means:

in the implementation of hook_init()
in an implementation of hook_form_alter(), hook_form_FORM_ID_alter(), or hook_form_BASE_FORM_ID_alter()
in the menu callback for the menu defined from the module

Within a form, Drupal 7 modules can use something similar to the following code, to add a JavaScript file to the currently output page.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'my2form') . '/abc.js',
);

As alternative, if you write the following line in the .info file of a module, the JavaScript file will be added to any page.

scripts[] = abc.js

The path needs to be relative to the directory containing the module; if the file is contained in a sub-directory of that directory, e.g. javascript, the line should be the following one.

scripts[] = javascript/abc.js


How to add two fieldConditons in Entity field Query?

You can chain multiple field conditions, however I'd probably try something like this (haven't tested it):

->fieldCondition('field_town_city', 'value', $search_title, 'CONTAINS')

The EntityFieldQuery::fieldCondition() invokes the addFieldCondition() method, see the possible $op values on api.drupal.org:

https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AaddFieldCondition/7


Services 3.x json cache for anonymous user

Even in my experience, the boost module doesn't seem to cache responses from the Services module end points the last time I tried. But here's a discussion on this topic in the module's issue tracker. There's a patch for this requirement http://drupal.org/node/1219484