Your custom_upload migration is trying to create nodes; the custom_upload migration is taking a d6_upload source plugin:

source:
  plugin: d6_upload

...and mapping it to a node:entity destination plugin:

destination:
  plugin: 'entity:node'

Since the d6_upload source doesn't have a title field to map to the node:entity field in the process definition of your migration, the migration fails as it tries to insert a titleless node.

You need update your node migration. If your node/file migrations are working, the node migration should have a
process.field_attachments yml property to map field_attachments.target_id to the fid property from your custom_file migration.


You can find an example in the Examples for Developers module. Here are two excellent guides:

Simpletest Testing tutorial
Unit Testing with SimpleTest


Just define the  variable already before using it

$profile ="";
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
$checkbox1 = isseet($profile->field_checkbox_admin1['und'][0]['value']) ?      $profile->field_checkbox_admin1['und'][0]['value'] : "";

That is nature the profile 2 module, it doesn't create any entry for any field in the database untill it is not assigned any value actually. So it returns nothing if it is empty.

Hope it will help


Show total count of items on page created by views

You could add an element on Header, from the interface.
CLick "Add" in header section and then add a "Global: Result summary" field.

If you have to do it by code, the right variable should be:

$view->total_rows


How to add css files based on breakpoint in library?

Here is the solution I found.

mytheme.libraries.yml

mylibrary:
  version: 1.0
  css:
    theme:
      css/some/path/desktop-small.min.css: { media: all and (min-width: 756px) }
      css/some/path/mobile.min.css: { media: all and (max-width: 755px) }


Form api custom validation function doesn't work

I think that if you use drupal_get_form() you can't alter the form because the form will be already built, cached and all the processing done.

Try this instead.

$form_init = array();
$userLogin = user_login_block($form_init);

array_unshift($userLogin['#validate'], 'MY_UBERLEAD_FUNC_validate');
$form['selfservice_ad_tabs']['tab_3']['login'] = $userLogin;


How to use term edit page instead of view page?

There are a few ways we could achieve this:

Option 1: Introduce a route subscriber in a custom module with below code:

    $route = $collection->get('entity.taxonomy_term.edit_form');
    $collection->add('entity.taxonomy_term.canonical', $route);

This code would replace the edit_form to the canonical route.

Note: Might need to update the local task to remove the view tab as it is confusing to see the edit form in the view tab (as below).

Option 2: Extend Drupal\taxonomy\Form\OverviewTerms form and overwrite buildForm method and use $term->toUrl('edit-form') as below:

      $form['terms'][$key]['term'] = [
        '#prefix' => !empty($indentation) ? $this->renderer->render($indentation) : '',
        '#type' => 'link',
        '#title' => $term->getName(),
        '#url' => $term->toUrl('edit-form'),
      ];

However, it might not be a good idea considering how complex buildForm method is and the effort to keep up with any core changes.


All visited urls ending with _900 in cache_page tables

This issue was caused by module http://drupal.org/project/resp_img after installing the latest version, everything is ok.


I´ve solved it by using a token, and placed that token (from a view) in a hidden field in that form - thus saving that value.

The same token generated from views - I used to alter the label for that question with "hook_alter_form".

A kind of non programmatically way of solving the problem.


Where are you doing the call to workbench? Have you tried doing the call in the postprocess of the node creation. Maybe you don't have the proper database object yet when you do it?


You need to replace 'my_view_machine_name' with your actual view machine name.

To get view machine name, you can edit your view, and in the URL you will see it: admin/structure/views/view/machine_name/edit


What causes EntityMetadataWrapperException: Unknown data property?

Please login to admin and go to following page. You need to add field for your bundle. It will resolve above error.

Home » Administration » Configuration » Group
Organic groups field settings

For more details please visit following link.
https://www.drupal.org/node/2023721


Populate fields when a checkbox is clicked on a form

You could do this with hook_form_alter and add a state to the field that needs to be hidden.

$form["first_name"] = array(
    "#states" => array(
        "invisible" => array(
            ":input[name='bring_parter']" => array(
                "checked" => FALSE,
            )
        )
    ),
);

What this does is hides the "first_name" unless "bring_partner" is checked. More info here


Why does user column name has UNIQUE Constraint?

It's a bad idea, your are modifying a core feature of Drupal that others module (and the core itself) may relay on. That's the reason why that column has 'UNIQUE' option, because Drupal requires unique username. Think on user login: how you can login with different users if the have the same username?

Check this answer where you may find more info:
Is it possible to allow duplicate usernames ?


Where is the template for the promoted to front page items?

This is tipically done in node.tpl.php in your theme. Just keep in mind that this template works for any node, so you should introduce some logic to check if the node is promoted, e.g.

<?php if ($node->promoted) { ?>

Maybe some other stuff

<?php } ?>


How can I alter the contents of a form before they are submitted?

You may be interested in form_set_value().  You would use this within the form validation function.  There are examples of its use posted below the API documentation in the comments if you need further clarification.

For help creating a validation function, see the Form API Quickstart Guide (D6) or How to use the Form API (D7).


Use multiple choices of CSS class in Insert

I would suggest you to create two presets. Each preset can then be styled and positioned with CSS and the .imagepresetname class. You just have to activate the presets you like on the field in the "Insert" settings.


How can I put the feed import page on a different page and not have it on the node add page?

There is an option on the Feeds importer edit page that lets you toggle off the form on the node add page. Just select the Use standalone form option on the Attach to content type setting.


You can create the node without saving it.  You wouldn't really need a try catch if you know what types of data you're saving.

    $node = \Drupal::EntityTypeManager()->getStorage('node')->create([
      'type' => 'news',
      'title' => "hello world",
      'field_some_textfield' => "Here's some text",
    ]);

    $node->set('status', 1);
    $node->set('field_site_section', [['target_id' => 6]]);
    $node->set('field_first_name', $data->firstName);
    if (!empty($data->middleName)) {
      $node->set('field_middle_name', $data->middleName);
    }
    $node->set('field_last_name', $data->lastName);

When you're satisfied that your node is set up properly, then you can call:

$node->save();

At this point, you can get the node id this way:

$nid = $node->id();


You'll need a Taxonomy Term view with a Taxonomy vocabulary: Vocabulary ID contextual filter.

The problem here is there isn't a core-provided argument plugin for a default value. The closest thing is the Taxonomy term ID from URL provider, but it supplies the Term ID, not the Vocab ID. So you can:

Use the PHP Code plugin provided by Views to retrieve the term ID and return the vocab ID. (Not recommended, as it could cause various problems & won't be compatible with D8).
Implement a custom module with views integration via hook_views_plugins() and a handler that extends the views_plugin_argument_default class. (You can use the Views module's
views_plugin_argument_default_taxonomy_tid provider as an example).


How to check with the Rules module if a user has a custom picture?

Here's what I did, using a quick custom module to define and evaluate the condition that a user has uploaded a custom image to the core-provided Picture in the user account.

Module name: mymodule

This goes in mymodule.rules.inc:

/**
 * Implements hook_rules_condition_info()
 */
function mymodule_rules_condition_info() {
  return array(
    'mymodule_condition_user_has_picture' => array(
      'label' => t('User has picture'),
      'parameter' => array(
        'account' => array(
          'type' => 'user',
          'label' => t('User account')
        ),
      ),
      'group' => 'User',
    ),
  );
}

/**
 * Evaluates condition user_has_picture
 */
function mymodule_condition_user_has_picture($account) {
  if ($account->picture == NULL) {
    return false;
  } else {
    return true;
  }
}

Note that I've chosen to make the condition positive (returns TRUE if picture is found). If you want the condition to return true when the picture is NOT found, use the Negate option found in Rules.


How to import nodes with entity reference field through feeds?

Take a look at this answer:

https://drupal.stackexchange.com/a/22043/4134

At the moment there is a very active thread on d.o about adding this functionality.


How can we change the default URL what we get through the view blocks on a basic page?

You can use the Clean Pagination module to get reasonably close:

  Clean Pagination is a very simple module that allows you to enable clean URL pagination for specified pages. The way Drupal typically works, if you had a view with the URL 'my-view', subsequent pages would normally use a query to pass the page number, as in 'my-view?page=2'. When Clean Pagination is being used for a page, it will create a url like 'my-view/2'.

If that doesn't do the trick that module should at least serve as a good starting point to convert the pager to exactly what you're looking for.


Change Product type's referenced Variation type

It's safe as long as you don't have any products. We need to change the logic in Commerce so that it checks for existence of product entities, instead of just checking whether the product type is new. Continued in your issue: https://www.drupal.org/project/commerce/issues/3014686


View filter to include title and body text

This module will help to do you job Views filters populate

  This is an utility module. Its sole purpose is to fill in one blank
  that seems not easy to be done using normal views, which is to use one
  exposed string filter to search on multiple fields.

  Bear in mind, that, for now, only populates STRING exposed filters, so
  those filters that take an array (options) or special types won't
  work, although it may not be difficult to extend it.

You need to make use of Global: Populate filters or Global: Combine fields filter its explained in steps  here


The problem was that I didn't notice that Drupal 7 has compatibility problems while running on IIS and requires a complex (at least for me) configuration procedure to run correctly.
I've reached that conclusion when I tried to install Drupal 6 on the same server, and it ran instantly.


There is an option to change the text. Follow the steps

In you 'view' you can find PAGER settings

Click on Settings to change the text

Enter the text whatever you want to see at Output


How do I include data from the order item type fields in the order receipt email?

Figured it out! Took a few steps:

I created a View of type: Order Item. Added my custom fields to that view (Job Title, etc).
Added a Contextual Filter "Order item: ID".
Provide Default Value: Content ID from URL.
I created a Viewfield on
each of my Order Item Types, using the View I created in the
previous step.
I went to
/admin/commerce/config/order-item-types/default/edit/display and hid
all the fields except for the Viewfield. Repeat for the other Order
Item Types. In commerce-order-receipt.html.twig, add this code
(which was found in commerce-checkout-order-summary.html.twig):

{{ order_item|commerce_entity_render('summary') }}

Style the output as you like in the receipt twig. Here is the
pertinent portion of mine in case anyone finds it helpful:

            {% block order_items %}

              {% for order_item in order_entity.getItems %}

            {{ order_item.getQuantity|number_format }} x
            {{ order_item.label }}
            {{ order_item.getTotalPrice|commerce_price_format }}

          {{ order_item|commerce_entity_render('summary') }}

              {% endfor %}

            {% endblock %}

Clear cache, and that's it!


referencing/linking to an entityform and passing nid/other field information through the URL

I finally figured out how to get everything I wanted to happen, and figured I would post it here in case anyone had similar difficulties.  Entity reference prepopulate + a views block that links to my event registration entityform.  This blog was extremely helpful: https://wunder.io/blog/simple-contact-form-per-content-item-with-entityform/2012-10-24 .

One tricky thing for me was getting my taxonomy terms to be recognized by an entity reference field.  The only field option I had was "Content: All taxonomy terms," and entity reference taxonomy term fields will only recognize the taxonomy id in the url.  So, I used views to rewrite the output of the  content: all taxonomy terms field as [term_node_tid-tid].

Really effing love tokens, views, and entity reference prepopulate right now!


How to display the View according to the logged user?

Add a relationships based on user who is assigned in the request (if he/she is assigned using a reference field , select that field) , then create a filter based on user (the user who is currently logged in and is viewing the table) , use relation to relate user to nodes which he/she is assigned to.


How do I include a custom JavaScript file in a module?

This is the right & simple way to include any JS file in Drupal 7.

Create a folder named i.e. js, inside your module folder.
Inside that folder place (modulename).js file.

Note: Drupal JS code has a specific format as follows:

(function ($) {
  $(document).ready(function(){
    alert("Hello world!");  //here we can add our JS code
  });
})(jQuery);

Open (modulename).info file & add:

scripts[] = js/(modulename).js
Clear Cache & Run.


When you define title arguments as an array, each array element will be passed as arguments in that sequence.

Now you have title arguments defined as array(1), which means the actual call would mimic t('something') if the URL path was custom_gmap_neo/something/something_else/something_else_1.

If you want to call t() function as t('Get directions to @hotel', array('@hotel' => 'something')), you need to define your own title callback, because automatic integer to path argument translations only happen in the root level array elements.

<?php
function custom_gmap_neo_menu(){
    $item = array();

    $item['custom_gmap_neo/%/%/%'] = array( // hotel/origin/destination
        'title arguments' => array(1),
        'title callback' => 'custom_gmap_neo_get_map_title'
        'page callback' => 'custom_gmap_neo_show',
        'page arguments' => array(1,2,3),
        'access callback' => TRUE,
    );

    return $item;
}

function custom_gmap_neo_show($hotel, $origin, $destination){
    dpm($hotel);
    dpm($origin);
    dpm($destination);

    return '';
}

function custom_gmap_neo_get_map_title($hotel) {
  return t('Get directions to @hotel', array(
      '@hotel' => $hotel
    ));
}
?>

However, if your first URL argument (hotel) is a node, consider using %node as the path wildcard, because it can load the node for you, and handles page not found errors automatically if node_load returns an empty result. Otherwise you will have to call node_load twice. node_load caches results, but there are many loader functions that do not cache results.


Make content type available for anonymous to edit and use front end theme

Just make sure your anonymous user role (and any other relevant roles) don't have the 'View the administration theme' permission...then they'll get the default front-end theme when accessing any page that's deemed to be an 'admin' page.


The answer is simple enough, though a little counter-intuitive coming from a Drupal 7 install where everything but the kitchen sink is included.

All I had to do was to inlcude the library in my theme's .libraries.yml file;

dependencies:
  - core/drupal
  - core/jquery
  - core/jquery.once
  - core/drupal.dialog.ajax

This will be more performent than including the entire core javascript system on every page. It was a little confusing since that is the behavior for the admin user.


Preserve Current Paths before rolling out new Pathauto Alias

To preserve AND redirect existing aliases when you implement a change like that:

install the Path Redirect module
open the 'Automated Alias Settings' in URL Aliases (admin/build/path/pathauto)
open the 'General' fieldset
change the radio button for 'Update action' to 'Create a new alias. Redirect from old alias' (see screenshot below).

http://img705.imageshack.us/img705/2738/redirectaliasleaveintac.png


How to send email in every 7 days to in-active users that is not logged in since 7 days?

In order to send an email to the user with 7 days of inactivity. Do the following:

A. Install Rules and Scheduler where Scheduler depends upon Tokens and Entity API

B. Once you have installed and enabled all the above modules, then you can start configuring your rule. To achieve what you want, do the following steps:

Add new rule (Configuration -> Workflow -> Rules)
Give it a name (i.e. user_login ) and select the event as "User has logged in", leave the tags field out and Save the rule
After saving the Rule, go back to Rules using the breadcrumb (i.e. URL), when you are back in the Rules window, you should see your recently created rule (i.e. user_login)
Select Component from top-right-hand-side-of-the-page (There should also be a tab named Scheduler, if not there then enable the module)
Inside component, select Add new component
Choose Action set as Component plugin and press Continue
Give it a name (i.e. send_email_to_inactive_user)
Skips Tag
From Variables section, Choose DATA TYPE as User, give it a LABEL (i.e. inactive_user), give it a MACHINE name (i.e. inactive_user), ignore USAGE and press continue and the page should refersh.
Now under Actions add an Action
Select Send email
TO, click on switch to Data Selector then reference the label of variable created in previous screen (i.e. inactive-user:mail) colon mail
Provide a subject to your email
Provide a message to your email
Provide a from to your email
Then save, now you should see the send_email action which is attached to the component.
Go to the Rules and create an Action for your rule with event (User has log in)
Select the value of action as Schedule component evaluation and it should open a window with combo box containing your recently created component (i.e. send_email_to_inactive_user), choose it
for * Schedule Evaluation Date * provide a value (i.e. +10 minutes or +7 days or +15 weeks)
for Identifier provide a value that will help you identify the scheduled task among other tasks (i.e. 7 days inactive reminder for [account:uid], where the [account:id] is replaced by the logged-in-users-id)
Last option, select account for INACTIVE_USER's data selector
Save and you should see the schedule component evaluation under Actions

You are done. If you pay close attention, the Rules evaluates The component when a User log in, the component then schedules an email to be send to the user +7 days (or override the existing one, updating the schedule time duration) and the scheduler sends the email when the time come. So Rule is used to evaluate the component and component is used to setup/update scheduler and scheduler is used to send the email.

In case you have not followed me, or can't figure out then here are my working sample exports for Rule & Component, just import them and change the values accordingly and save. Test it by logging in and then go to Configuration -> Workflow -> Rules -> Schedule and you should see a scheduled event for exactly (i.e. +7 days or +10 minutes from the time you login).

Important component first:

{ "rules_send_email_to_inactive_user" : {
    "LABEL" : "send_email_to_inactive_user",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "inactive_user" : { "label" : "inactive_user", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "inactive-user:mail" ],
          "subject" : "test inactive user",
          "message" : "test inactive user message",
          "from" : "raf",
          "language" : [ "" ]
        }
      }
    ]
  }
}

then import the Rule:

{ "rules_user_login" : {
    "LABEL" : "user_login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "schedule" : {
          "component" : "rules_send_email_to_inactive_user",
          "date" : "+7 days",
          "identifier" : "7 days inactive reminder for [account:uid].",
          "param_inactive_user" : [ "account" ]
        }
      }
    ]
  }
}

To test whether it is working you can execute it right away and you should get the email in your inbox.

Good luck man, if you needed further help, then Google is your best friend.


It looks like you can use the Serial Field module to accomplish this.

From the Serial Field page on Drupal.org:

  Usage

  You can add a serial field to any type at admin/content/types ->
  manage fields. In the New Field form select Serial as the type of data
  and label and field name as your choice, and Save. No other settings.


Create an advanced search that searches only on a field with search_api in drupal 7

You don't need separated indexes. In you callback handler, you need to build a new SearchApiQueryInterface instance and set conditions on the field using its condition method.

$index = search_api_index_load('custom_index_machine_name');
$query = $index->query(array(
  'language' => $GLOBALS['language']->language,
  'search id' => 'custom-search',
));
foreach($form_state['values']['filters'] as $field => $value) {
  if (!empty($value)) {
    $query->condition($field, $value);
  }
}
$result = $query->execute();


download a file from a link using DrupalWebTestCase?

The class DrupalWebTestCase has the method DrupalWebTestCase::curlExec(), which accepts an array containing the same values used by curl_setopt().


Commerce 2 Add to cart with quantity field and Product Picture

Please check your order item type e.g. admin/commerce/config/order-item-types/default/edit/form-display/variation_cart_form (default type)

Needed view mode is variation cart form. There is quantity field.

Also check this default view mode for your product variation type /admin/commerce/config/product-variation-types/default/edit/display

There is add to cart button.


How to transfer field location inside a div?

I was able to achieve this using javascript:

<script>
$("#edit-field-date").appendTo("#detail-wrap");
</script>

But I am still looking for a way to do it under form_alter.


You can store it in session

During Add to cart.

$_SESSION['my_module_name']['product_id']['field_name'] = $filter_value

Then set form option value from session

function my_module_name_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'your_form_id') {
    $get_default_value = isset($_SESSION['my_module_name']['product_id']['field_name'])?$_SESSION['my_module_name']['product_id']['field_name']:'';
    $form['field_name']['#default_value'] = $get_default_value;
  }
}


There is a Field Collection issue with a Field Collection Migrate destination (in the patch in comment #222). The added field_collection.migrate.inc file contain a bit of documentation on how to use it.

In you case, I guess you have a speaking engagements migration class which load your CSV file and create Speaking engagement nodes. You will then need a speaker migration class to load the same CSV file and create Speaker field collections. This second migration class depends on the first one, so when a Speaker is created, it will be linked to its Speaking engagement.

Something like

class SpeakerMigration extends Migration {

  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->dependencies = array('SpeakingEngagementMigration');
    $this->source = new MigrateSourceCSV('path/to/speaking/engagement.csv', array(), array());
    $this->destination = new MigrateDestinationFieldCollection('field_speakers',array('host_entity_type' => 'node'));
    $this->map = new MigrateSQLMap($this->machineName, array(
      'id' => array(
        'type' => 'char',
        'length' => 40,
        'not null' => TRUE,
        'description' => t("Speaking Engagement's identifier"),
      )), MigrateDestinationFieldCollection::getKeySchema());
    $this->addFieldMapping('host_entity_id', 'id')
      ->sourceMigration('SpeakingEngagementMigration');

    // ... Add field mapping here.
  }
}


How can I securely expose data through Drupal (via REST or something else)

Services has a pluggable architecture for authentication, so if there's nothing that supports certificate authentication, all you need to write yourself is such a plugin.

That is basically responsible for mapping that certificate to a Drupal user and then everything after that will check that this user has permissions to access whatever entity/content it requested.

Drupal Module as web service with SSL looks like a related question but doesn't have any answers.


Where in the MySQL database schema is the URL alias for a group relation?

As Clive stated in the comment, all aliases are in the url_alias table.

You should join it with the og_membership table, to take the url alias of the node's group.

So, for a node with id 100, the script should look like:

select u.alias
from og_membership og, url_alias u
where concat('node/', og.gid) = u.source
and og.etid = 100 and og.group_type like 'node'


How to hide tabs, depending on the role of editing using menu_alter

Using hook_menu_alter you put restriction by passing role in access argument like "tutor" or "student".

function MYMODULE_menu_alter(&$items) {
  $items['menu_item']['access callback'] = 'user_has_role',
  $items['menu_item']['access arguments'] = array('tutor'),
}

function user_has_role($roles) {
  if (user_is_logged_in()) {
    global $user;
    if (in_array('administrator', $user->roles)) {
      return TRUE;
    }
    foreach ($roles as $role) {
      if (in_array($role, $user->roles)) {
        return TRUE;
      }
    }
  }else {
    return FALSE;
  }
}


How does Drupal check write permissions for a folder?

You're probably looking for the file_prepare_directory() function:

  Checks that the directory exists and is writable.


A newly developed module, Media View Addons, provides just that.


Display the Group Title after the content in Views Grouped By

You should override the views-view-grid.tpl.php for your views. Otherwise, it will be effect all grid layout into your site.

The correct template suggestions for views be views-view-grid--[views_name].tpl.php or views-view-grid--[views_name]--[display_id].tpl.php.

To know more template suggestions for views, you can follow below step.

Go to Administration » Structure » Views
Edit your views
Open the correct display of the views.
Click on  information link for theme under Advanced tab.
A popup be display for all template suggestions for a particular
views.


I can't render default values on form element in theme_table()

In FAPI (and renderable arrays in general), keys starting with a # are considered properties - so not renderable elements. This means their children aren't processed for content properly.

There are several methods to do what you want, but the easiest is probably references. In your specific example, it would look like this (I've trimmed out some stuff to make my changes more clear):

function _ss_menu_zone_test($form, &$form_state) {

  $tablesort_headers =array(
    array('data' => t('Price'), 'field' => 'price'),
  );

  // render the tablesort of menu items.
  $form['category_' . $tid]['items'] = array(
    '#theme' => 'table',
    '#header' => $tablesort_headers,
    '#rows' => array(),
    '#sticky' => TRUE,
    '#attributes' => array('id' => 'zone-items-' . $tid)
  );

  $formfield = array(
    '#type' => 'textfield',
    '#default_value' => '10' // default value set
  );

  //We need to include the field in the form so it's rendered. This wont display because we're using #theme => table.
  $form['category_' . $tid]['items'][] = array('formfield' => &$formfield);

  //These are your rows, note the byreference on the formfield.
  $tablesort_rows = array(
    array('price' => 'test row format 1'), // example of basic string row
    array('price' => array('data' => 'test row format 2')), // example of simple string but using data
    array('price' => array('data' => &$formfield)),
  );

  //Add your rows to the table.
  $form['category_' . $tid]['items']['#rows'] = $tablesort_rows;

  //Since we used references we want to unset the variables we created.
  unset($formfield);

  return $form;
}


How to rewrite this theme call to drupal_render

Something like this...

$build = array(
  '#theme' => 'image_style',
  '#path' => $news_image['uri'],
  '#style_name' => 'thumbnail',
  '#alt' => $news_image['alt'],
  '#title' => $news_image['title'],
);

$rendered = drupal_render($build);

Where every named variable you would normally pass to the theme() function as the second parameter becomes a #-prefixed key in the render array.


This is native browser functionality, you are going to need to use JavaScript to circumvent and add your own behavior


Text formatting in the "Help Text" section

The Advanced Help module will let you create help texts that can be tied to a help icon on any page, form or form item. Clicking the icon will pop-up a Ajax window with the text.


How do I implement a clickable JavaScript map?

You can use drupal_add_js() and drupal_add_css() in the menu call back function to add js and css files on the specific page.

Adding in the .info file would add js and css on all the pages.

You can also use hook_library() to define the library of js files and its dependancy with jquery or core js files.


Same website but different logo for large screen and small device?

There are multiple ways to do this through CSS media queries. See example below.

.classname {
   @media all and (min-width: 768px) {
     background-image:url('image2.png');
   }
   @media all and (min-width: 320px) {
     background-image:url('image1.png');
   }
}

Helpful links

Responsive Images
Working with breakpoints

If you use the module and breakpoints from your theme you can probably just wrap the logo in a div class so you can control the padding or other CSS attributes. Just make sure to find the correct image styles per breakpoints and multipliers.


Preprocess hooks are named MY_MODULE_preprocess_TEMPLATE_NAME, in your case:

function my_module_preprocess_node__myfile(&$variables) {}

Notice how I replace the template's dashes with underscores in the function name.

Now you can get the display variable from $variables['node']->field_display->value.


How to get a field third party settings for every content entity forms

Implement hook_field_widget_form_alter() to alter form elements of any content entity form.

For example how to add a validate callback when you have third party settings stored in the field configuration:

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition instanceof \Drupal\field\FieldConfigInterface) {
    $mymodule_settings = $field_definition->getThirdPartySettings('mymodule');
    if (!empty($mymodule_settings)) {
      $element['#mymodule_settings'] = $mymodule_settings;
      $element['#element_validate'][] = 'mymodule_element_validate';
    }
  }

}


How do I render a custom form on a view page?

It's only possible to display one "page" on a url, so you can't both display a view and a form or any other "page" for that matter.

You have a few options:

Insert the form into the view (can be done with a global views handler)
Insert the form on the view page by exposing it as a block.
Insert the view on the form page by exposing it as a block.

Probably the easiest solution for you is to convert the view page to a view block and insert it on the form page. Views already has support for this, so you only need a few clicks in the interface to achieve this.


How to create field collection item fields programmatically?

This works for me (my field collection is called field_fc_test). I imagine the problem is with the way you are calling field_create_instance.

$new_field = array(
  'field' => array(
    'field_name' => 'name_of_my_field',
    'type' => 'text',
    ),
  'instance' => array(
    'field_name' => 'name_of_my_field',
    'entity_type' => 'field_collection_item',
    'bundle' => 'field_fc_test',
    'widget' => array('type' => 'text_textfield'),
  ),
);
field_create_field($new_field['field']);
field_create_instance($new_field['instance']);


consider you have called like this $content = node_load(1);

then you can get the values like below

$content['field_orgs_number_details']['und'][0]['value']

Similarly you can do the same for getting the telephone numbers


If you go your modules admin screen (/admin/modules), you'll see there's a module called Statistics that actually comes with core Drupal.  Make sure you enable it on this screen if it isn't enabled already.

This will print out page views at the bottom of your pages, but you have to make sure you visit the permissions screen to give anonymous users (if that's what you're trying to do) the ability to see that.  After the module has been enabled, you'll see the following set of permissions for your site(/admin/people/permissions):

Administer statistics
View content access statistics
View content hits

You'd just need to check the last one for whomever you want to be able to see the page views!

You can find additional information about this module on your own site's help pages: /admin/help/statistics


How to call module function in template file?

Please try bellow code and use module_load_include() function.

function non_login_preprocess_page(&$vars) {

  module_load_include('module', 'module', 'test');   // **add this line**

  if(module_exists('test') && function_exists('test_get_rnd_data')){
    $vars['rnd_data'] = test_get_rnd_data();
    print_r("callled"); exit;
  }
}


How to exclude all blocks on a specific page?

You could use the Rules block visibility module for this. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

  Need to show a block only for users registered more than a month ago?

  Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

  What about displaying or hiding a block based on current weather conditions?

  All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is not shown on that page on which you want to hide that block).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

{ "rules_block_visibility_exclude_a_page" : {
    "LABEL" : "Hide block for a specific page",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "NOT text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "my-page-to-exclude-all-blocks"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

Adapt the value of my-page-to-exclude-all-blocks to fit your needs. Obviously, you can reuse the same Rules Component for all blocks you want to hide on that specific page.

Should you want to further enhance the above Rules Component (to make it more generic), just replace the Rules condition in it with something using an appropriate regular expression (related to the current path also).

Note: yes this requires (at least) 1 more module (Rules block visibility, and Rules which it depends on). I also always try to avoid modulitis (= way too much modules) in any Drupal site. However adding Rules to any site seems to me like a no-brainer, because you can avoid/eliminate dozens of other modules that do only 1 thing. And by using the (tiny) Rules block visibility module, you can potentially replace modules such as the Context module and/or reduce the need for custom modules and/or using the (dangerous) PHP filter.


Apply a product discount if orders are picked up

Aren't the shipping methods themselves using rules? I would try to edit the rule for the Pickup shipping method and see if I could add the discount from the Actions of that Rule.

If you know how to use Rules Components, you could further encapsulate this so all the discount-related stuff was in a separate Rule Component.


Move images from a image field to another field

Welcome to SO, MineDoodler!
A little bit ago I found the same problem, so I developed this piece of code. (Note that I started a little bit ago with developing, it is possible to achieve this easier).
Read the comments to understand the code.

use \Drupal\node\Entity\Node;
use \Drupal\paragraphs\Entity\Paragraph;
use \Drupal\file\Entity\File;

function migrateImages() {
  // Get all products
  $query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'productos');
  $nids = $query->execute();

  $allNids = [];

  // In my case, i had a keyed array (First element was [213] => "157") so I turned into ([0] => "157")
  foreach ($nids as $nid) {
    $allNids[] = $nid;
  }

  // Go through every node
  for ($i = 0; $i < count($nids); $i++) {
    $nodeID = $allNids[$i];

    // Load node.
    $node = Node::load($nodeID);

    // Get current paragraphs (if already has any).
    $current = $node->get('field_prod_media')->getValue();

    // Go through every image this node has.
    foreach ($node->field_prod_img as $item) {
      // Create new paragraph
      $paragraph = Paragraph::create(['type' => 'YOUR_PARAGRAPH_TYPE']);

      // Load image
      $file = File::load($item->target_id);

      // Save image
      $paragraph->set('IMAGE_FIELD_IN_PARAGRAPH', $file);

      // Force the new "alt". I've done this because it wasn't saving the alt.
      $paragraph->field_img->alt = $item->alt;

      // Check if it's new and save it.
      $paragraph->isNew();
      $paragraph->save();

      // Add to the current paragraphs the new one.
      $current[] = array(
        'target_id' => $paragraph->id(),
        'target_revision_id' => $paragraph->getRevisionId(),
      );
    }

    // Set again all paragraphs, with the new ones.
    $node->set('field_prod_media', $current);
    $node->save();
    dpm("node ".$node->label()." has been saved!");
  }
}

Took the idea from #7 in this post and developed by my knowledge.
I forgot to mention that this code was executed in the Devel PHP, in the Devel module.


Why is my custom webform submit handler not submitting?

I found the problem.

One of the features of webform is the ability of have multi-page forms, and the way how webform determine if it is in the "final" page is checking if the submit button has the value "Submit" and if that is not the case then it thinks to there is another page to evaluate before to submit the last function.

You can see this in the file webform.module in the line 3174:

 // Check for a multi-page form that is not yet complete.
 $submit_op = !empty($form['actions']['submit']['#value']) ?
 $form['actions']['submit']['#value'] : t('Submit');
 $draft_op = !empty($form['actions']['draft']['#value']) ?
 $form['actions']['draft']['#value'] : t('Save Draft');
if (!in_array($form_state['values']['op'], array($submit_op,
$draft_op, '__AUTOSAVE__'))) {

In the case of your example $form_state['values']['op'] doesn't exists and even if it exists it wouldn't has the value 'Submit'  so it  will try to handle your form as a multipage form and It will not execute the last part of the function.

What I did to make your example work was only add the this in your submit function $form_state['values']['op'] = 'Submit'; and that's it.

It feels like a hack but that is the way how webform work :(

Below the example if you want to compare it with your code:

<?php

/**
 * Implements hook_form_alter().
 */
function test1_form_alter(&$form, &$form_state, $form_id)
{
    switch ($form_id) {
        case 'webform_client_form_5':
            $form['64_bit_btn'] = array(
                '#name' => 'op',
                '#type' => 'submit',
                '#value' => t('DOWNLOAD 64-BIT TRIAL'),
            );
            $form['#validate'][] = 'create_vector_user_free_trial_form_validate';
            array_unshift($form['#submit'], 'create_vector_user_free_trial_form_submit');
            break;
    }
}

function create_vector_user_free_trial_form_validate($form, &$form_state) {
    // this function runs correctly
}

function create_vector_user_free_trial_form_submit($form_id, &$form_state) {
     // add your code here
    $form_state['values']['op'] = 'Submit';
}

(please note to my module is called test1 you need change this with the name of your module)


Just enter the Endpoint of your AWS Elastic-search Cluster.

Use port : "80".

the Complete url will be something like:

XXX-XXX-XXX-XXXXXX.ap-southeast-1.es.amazonaws.com:80

First check are you able to access the Elastic-search , Try to telnet on the server:

telnet XXX-XXX-XXX-XXXXXX.ap-southeast-1.es.amazonaws.com 80

If it's not accessible make it available for your IP by changing the access policy .


Order receipt e-mail language for guest checkout

This is a known problem. Orders need a language field.

That will be added as a part of https://www.drupal.org/project/commerce/issues/2603482


I am looking for a responsive slider that can take text instead of images

There is a smaller group out there Theme Boutique who built a really remarkable slideshow tool called the Revolution Slider.  It's currently out ther and available on their Dawn Responsive theme (I have used their BigWig theme in the past with the same slideshow).  It worked really well and didn't require alot of the gymnastics that I've seen with other solutions.

Here's a demo video of it in action.  https://www.youtube.com/watch?v=zZL2renvh5o


Create a field instance programmatically on a taxonomy vocabulary

If you look in taxonomy_entity_info() you'll see this code that defines the taxonomy_vocabulary entity type:

$return['taxonomy_vocabulary'] = array(
  'label' => t('Taxonomy vocabulary'),
  'controller class' => 'TaxonomyVocabularyController',
  'base table' => 'taxonomy_vocabulary',
  'entity keys' => array(
    'id' => 'vid',
    'label' => 'name',
  ),
  'fieldable' => FALSE,
);

The important bit to note is 'fieldable' => FALSE...that's why it's 'forbidden' to add fields to that type.

The taxonomy_term entity type is fieldable so you won't have any problem adding field instances to one of those.

If you really want to add a field to the vocabulary, you'll need to implement hook_entity_info_alter() to change the vocabulary entity to 'fieldable' => TRUE (I've done it before, it's perfectly safe):

function MYMODULE_entity_info_alter(&$info) {
  $info['taxonomy_vocabulary']['fieldable'] = TRUE;
}


EntityFieldQueryException when saving node

I would check and see if the field (field_event) exists. Go to Fields list under reports (admin/reports/fields). You can also check the "field_config" table directly and see if the field exists.


How to complement eMail notifications with a notification bar?

You may be looking for Heartbeat module:

Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.
(...)
Heartbeat has global configuration for display, message template configuration and stream configuration.


Upgrade Backup and Migrate from 2.x to 3.x

It is possible to do that upgrade without losing any data.


using same addressfield for profile2 and commerce module

Profile2 and Commerce Customer Profiles are different entities.

Even if the address field is the same, the data will need to be copied over somehow.

One way to do it would be with

hook_field_attach_load

and load in the relevant address field data there, when the field is loaded.

Keep in mind:

That hook can be passed multiple entities
Ensure the user id for both entities is identical prior to merging the data.

More info on the Field Attach API


Stuck with Drush on OS X with AMPPS and Homebrew

Even though I did export the Drush PHP path, I had not added the link to AMPPS' mysql bin in .bash_profile. That solved my issue.

nano ~/.bash_profile
export PATH=$PATH:/Applications/AMPPS/mysql/bin
source ~/.bash_profile


You can use Drupal::entityQuery() & Node::loadMultiple() to load all the nodes of your given type:

$nids = \Drupal::entityQuery('node')->condition('type','my_custom_type')->execute();
$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);


Node reference field options supplied by Views 3 work in preview, not in content

I faced this problem. After some hours of googling, I found the solution in these issue reports.

http://drupal.org/node/1306106
http://drupal.org/node/1356006

What you basically need to do is to install the development snapshot (7.x-1.x-dev, 25 Dec 2011) of Drupal Commerce. The patch has already been committed there.


I can think of two approaches.

The quick(er) dirty way:

Hide it with CSS!

Problems:

I assume you're using seven or some other admin theme that you can't edit so all this will need to go in a module with drupal_add_js() or some other method for inserting JS.
After we determine if the visitor is on a touch device, we can't hide the element with simple jQuery because the element is dynamically inserted.

First, we'll need a way for JS to add CSS to the page. This function will let us do that:

function addCss(cssCode) {
  var styleElement = document.createElement("style");
  styleElement.type = "text/css";
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = cssCode;
  } else {
    styleElement.appendChild(document.createTextNode(cssCode));
  }
  document.getElementsByTagName("head")[0].appendChild(styleElement);
}

Then determine if the current visitor is on a touch device:

var is_touch_device = 'ontouchstart' in document.documentElement;

If so, add some CSS to page that hides the "Crop" button.

if (is_touch_device) {
  addCss('.manualcrop-style-button-holder {display: none;}');
}

The harder way:
Somehow determine if the current visitor is on a touch device via PHP. I don't have a foolproof method for this, but you can look into something like php-mobile-detect.

If you can determine that the visitor is on a touch device in PHP, you can return the manualcrop_croptool_process() function early. (Line 151 of manualcrop.helpers.inc). Of course, that will require filing an issue with module maintainer and providing a patch of those changes.


How to change the language of inserted or updated paths to LANGUAGE_NONE using a module?

If someone needs to have a multi language site, but have all URL aliases language independent (i.e. the same for all nodes and languages), the solution is to create a function:

mymodule_node_validate($node, $form, &$form_state) {
   $form_state['values']['language'] = LANGUAGE_NONE;
}

As a side effect, it also makes all nodes language independent. One possible scenario where this would be useful is:

all nodes are created in a custom language which is also the site default language
the administration interface is in English (this so far requires multi-language)
the administrator users are able to use the same URL aliases as the rest of site visitors, despite the fact that they have English set while the content is in a different language (this requires the trick)

In a real multi-language scenario, URL aliases may need to be different for different languages.


How to pass a db_query as an array instead of a string?

There are three errors in that query:

The database tables are not field_config_instance(), and field_config(), but field_config_instance, and field_config. Parentheses have a particular meaning in SQL, and putting them after a table name causes an error message.
The field_config_instance table doesn't contain any "label" field. See the schema definition given in field_schema().

$schema['field_config_instance'] = array(
  'fields' => array(
    'id' => array(
      'type' => 'serial',
      'not null' => TRUE,
      'description' => 'The primary identifier for a field instance',
    ),
    'field_id' => array(
      'type' => 'int',
      'not null' => TRUE,
      'description' => 'The identifier of the field attached by this instance',
    ),
    'field_name' => array(
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
      'default' => '',
    ),
    'entity_type' => array(
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
      'default' => '',
    ),
    'bundle' => array(
      'type' => 'varchar',
      'length' => 128,
      'not null' => TRUE,
      'default' => '',
    ),
    'data' => array(
      'type' => 'blob',
      'size' => 'big',
      'not null' => TRUE,
      'serialize' => TRUE,
    ),
    'deleted' => array(
      'type' => 'int',
      'size' => 'tiny',
      'not null' => TRUE,
      'default' => 0,
    ),
  ),
  'primary key' => array('id'),
  'indexes' => array(
    // Used by field_delete_instance().
    'field_name_bundle' => array('field_name', 'entity_type', 'bundle'),
    // Used by field_read_instances().
    'deleted' => array('deleted'),
  ),
);

Drupal 7 placeholders aren't wrapped between quotes, when they are for strings.

The following query should not return any error.

SELECT nfi.field_name FROM {field_config_instance} nfi
  INNER JOIN {field_config} nf ON nfi.field_name = nf.field_name
  WHERE nfi.type_name = :type_name  AND nf.active = 1 AND nf.locked = 0


SMTP Authentication Support address/from name overwritten by Site Information

You can use the Mail System module to configure how to send different emails.


Here there is a piece of code I wrote for the same problem. It checks if the field is an array and start a for loop to print the field. I've used this in an external page who gets json through a json view from drupal.
I hope this can help you. If you rewrite it in a simple way, please let me know.
I'm using drupal 6, with NO "Display all values in the same row".

This Check if the field has got more than one img:

var image =  your_img_field;
    function isArray(image) {
   if (image.constructor == Object)
      return true;
   else
      return false;
}

If the field has got more than one img, it counts the array and return the size:

if (isArray(image) == true) {
Object.size = function(image) {
    var size = 0, key;
    for (key in image) {
        if (image.hasOwnProperty(key)) size++;
    }
    return size;
};
var size = Object.size(image);

Here the for loop to print (in my views the array starts from 1)

for (i=1; i<size+1;i++){
$("ul").append("

");
}
}

If the field img has not more than 1 img it prints the single img.

else {
$("ul").append("

");
}

PLEASE, CHECK QUOTES AND DOUBLE QUOTES IN THE IMG TAG


How to display image preview right away for managed_file form element?

This is my solution:

<?php

namespace Drupal\foo\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Element\ManagedFile;

/**
 * @FormElement("managed_image")
 */
class ManagedImage extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $info = parent::getInfo();
    // @see \Drupal\image\Plugin\Field\FieldWidget\ImageWidget::formElement()
    $info['#accept'] = 'image/*';
    $info['#image_style'] = 'thumbnail';

    return $info;
  }

  /**
   * {@inheritdoc}
   */
  public static function processManagedFile(&$element, FormStateInterface $form_state, &$complete_form) {
    /** @var \Drupal\Core\Image\ImageFactory $image_factory */
    $image_factory = \Drupal::service('image.factory');
    $element['#upload_validators'] += [
      'file_validate_is_image' => [],
      'file_validate_extensions' => [implode(' ', $image_factory->getSupportedExtensions())]
    ];

    $element['#description'] = [
      '#theme' => 'file_upload_help',
      '#description' => isset($element['#description']) ? $element['#description'] : NULL,
      '#upload_validators' => $element['#upload_validators']
    ];

    return parent::processManagedFile($element, $form_state, $complete_form);
  }

  /**
   * {@inheritdoc}
   */
  public static function preRenderManagedFile($element) {
    $element = parent::preRenderManagedFile($element);

    if (!empty($element['#files'])) {
      foreach ($element['#files'] AS $delta => $file) {
        /** @var \Drupal\file\Entity\File $file */
        $element['file_' . $delta] = [
          'preview' => [
            '#type' => 'container',
            '#weight' => -10,
            '#attributes' => [
              'class' => [
                'image-preview'
              ]
            ],
            'image' => [
              '#theme' => 'image_style',
              '#style_name' => $element['#image_style'],
              '#uri' => $file->getFileUri()
            ]
          ]
        ] + $element['file_' . $delta];
      }
    }

    return $element;
  }

}


View of users having same taxonomy terms?

The right way to solve this is by writing a default argument handler.  A patch to do this was started here: https://www.drupal.org/node/721390

A "shortcut" to doing this would be to use the PHP Code default argument handler and plug it in directly.  This is not generally recommended; it would be much better to put the code in a custom default argument handler so you should Google around for how to set one of those up as that's a bit beyond the scope of this question.  But here are the steps for using the PHP Code approach and you can use the same logic for a default argument handler:

Create a view listing users
Add a contextual filter to filter on the user skills field
In the contextual filter option, for "When the filter is not in the
URL" choose "Provide a default value" and select "PHP Code" from the
list.
Assuming your field is named "field_skills", enter the following:

PHP code:

global $user;
$account = user_load($user->uid);
$terms = array();
if (!empty($account->field_skills['und'])) {
  foreach ($account->field_skills['und'] as $value) {
    $terms[] = $value['tid'];
  }
}
return implode('+', $terms);

Down towards the bottom of that form there's a "more" link.  Be sure
to open that section of the form and select "Allow multiple values".

At this point, you should have the list that you want with one caveat: the currently logged-in user will show up in this list.  You probably don't want this.  To prevent that from happening add another contextual filter that excludes the current user from the list:

Add a contextual filter on the User:Uid value
Choose "Provide default value" for "When the filter is not in the
URL" and, out of that list, choose "User ID from logged in user".
Under the "more" link at the bottom, choose the "Exclude" option.


you can create a custom token , another helper link

or use
Custom Token module
then get views url  with

$view = views_get_view('viewname');
$view->set_display('display_name');
view->get_url(); // if not work try this  $view->get_path()

Learn how to create custom token according to below example

 /**
 * Implements hook_token_info().
 */
function my_module_token_info() {

  // Add tokens.
  $site['city_name'] = array(
    'name' => t('Token Name'),
    'description' => t('Token Description'),
  );

  return array(
    'tokens' => array(
      'site' => $site,
    ),
  );
}

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

 if ($type == 'site') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'city_name':
          $city_name = variable_get('city_name');
          $replacements[$original] = $sanitize ? check_plain($city_name) : $city_name;
          break;
      }
    }
  }

  // Return the replacements.
  return $replacements;
}


Download count module does not work for me

Try setting your file field to use private file system instead of public.


how to drupal_set_title for add node form D7 (form alter doesnt work)

finally...

in general code below works great...

function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'yourcontenttype') {
drupal_set_title(t('my title'));
}
}

BUT sometimes other modules do altering the form and title AFTER your module... that was my case :(
it took me couple days to find the solution...
solution:

function yourmodulename_preprocess_page(&$variables) {
if (!empty($variables['page']['content']['system_main']['#form_id']) && $variables['page']['content']['system_main']['#form_id'] == 'yourcontenttype_node_form'){
drupal_set_title(t('my title'));
}
}

to find out your form's id use this in form_alter

drupal_set_message(print_r($form_id, true));

I hope someone will find it useful...


Help outputting Drupal View JSON data using getJSON function

$.ajax({
  url:'views/ajax',
  dataType: 'json',
  data:{
    view_name: 'my view name',
    view_display_id: 'default',
    view_args: 'view argument goes here',
  },
  success: function(data, textStatus, jqXHR){
    if(data[1].data !== undefined){
      // the view results will be in data[1].data
    }
  }
})


clone a display for the "filtered (must have picture)" view.
Add a relationship on the picture field and make it required. This will limit the display of content to that which has a picture field populated.

Now you can use a link in the headers to jump back and forth or provide another means.


How do I use and show a vocabulary with multiple fields?

What you're looking for is Entity Reference.  This will let you create a taxonomy term field on your content type and give you the option to render the entire term using the display of your choice (teaser, full etc).

Setting it up would be very similar to what you've already tried with term reference:

Create an entity reference field in your content type
Target type = taxonomy term
Set target bundle if preferred, then save
Under manage display, set the field format to rendered entity
Set the view mode to your preferred option (you would configure these options under your vocabulary manage display screen)


What's the difference between web service (API) implementation with REST and routing?

actually to create a wbesrvice endpoitns  in Drupal 8 we need to activate  one of or both of this 2 modules :

JSON:API module (best one):

after the activation of this module you can
       access to all Drupal entities (user , node , taxonomy ) throw a dynamic endpoints that have this structure http://{host}/json_api/{entity_type}/{bundle}?Parameters, with the ability to fitter the result + built in pagination + sorting ex of endpoints :

/jsonapi/node/article : get a json contains all node article.
/jsonapi/node/article,sort=-created : get a json contains all node article and order them with e created field in DESC
order.article.
/jsonapi/taxojomy_term/article : get a json contains all taxnomy term category.

  understand the Drupal entity type first will be better :
  https://www.youtube.com/watch?v=FrSjwe8bh7I

  then use the  JSON:api using this videos :
  https://www.youtube.com/watch?v=--ZL3EAhnwc&list=PLZOQ_ZMpYrZsyO-3IstImK1okrpfAjuMZ

RESTful Web Services

Exposing Views using the RESTful Web Services module( Do you need an easy configuration from backoffice to set up and endpoint ?) https://www.youtube.com/watch?v=TMvNwRVJSEQ.
Creating a Custom REST Resources to expose data that can’t be exposed by the previous solution - when to use  this solution when none of the previous solution can expose this data (Does JSON:API  and View exposing can't expose this type of data ?)

note : the methos in this url https://www.chapterthree.com/blog/custom-restful-api-drupal-8 never use it because we get out of the context of drupal, and you waon't be able to use a hiddne power of Rest module ex  :l by default any custom rest endpoint will display i if rest ui (https://www.drupal.org/project/restui) module installed .


How do I override LoginTobbogan so that it redirects to Front Page on 403?

Option 1: Use the CustomerError module

As per the "... is there another login module ..." part of your question, you may want to look at the CustomError module. Here is a quote about it (from its project page):

  ... allows the site admin to create custom error pages for HTTP status codes 403 (access denied) and 404 (not found), without the need to create nodes for each of them.

  Main features:

  Configurable page title and descriptions.
  There are no author and date/time headers as with normal nodes.
  Any HTML formatted text can be be put in the page body.
  The error pages are themable.
  Users who are not logged in and try to access an area that requires login will be redirected to the page they were trying to access after they login.
  Allows custom redirects for 404s.

More specific, related to the LoginToboggan module, this is how the CustomError module integrates with it (quote from its README.txt, bold markup added here):

  If this module is enabled, it can enhance CustomError's handling of
  access-denied messages, but you have to be careful to set them up to
  work together correctly.

  These two modules both attempt to take over handling of system 403
  ("access denied") messages, and can conflict. CustomError does it by
  asking you to go to "admin/config/system/site-information" and
  manually setting the "Default 403 (access denied) page" to
  "customerror/403", whereas LoginToboggan sets that same field to
  "toboggan/denied" automatically (overwriting any other value that
  was there), when you enable its "Present login form on access denied
  (403)".

  If you are using CustomError with LoginToboggan, you should allow
  LoginToboggan to perform this take-over (in other words, don't set
  the "Default 403 (access denied) page" to "customerror/403"). This
  way, if someone attempts to access a page that they don't have
  access to, LoginToboggan will first give them a chance to log in if
  they haven't yet. If they still don't have access to the page,
  CustomError then takes over from LoginToboggan (by overriding one of
  its theme functions), displaying its customisable messages for
  access-denied errors.

So using what is described in this last (bold) sentence, you may get it to work the way you'd want to (or at least come closer to the solution you're looking for).

Option 2: Retry with the Rules module

Your (failed) attempt to use the Rules module, might be because you have NOT used event "Drupal is initializing". You may want to retry, using this "Drupal is initializing" event. That might help to ensure that the rule gets trigger 'BEFORE Logintoboggan has a chance to take precedence' (so that you are NOT too late).

For a sample of a Rule (in export format) using this "Drupal is initializing", refer to my answer to the question "How to redirect user using Rules when user visits a link with view?".


How to display a views block on pages with a specific combination of URL patterns?

Using the Block Visibility Groups module, perform these steps:

Define a new Block Visibility Group, say you name it "Group pages".
For this newly created *Block Visibility Group" (named Group pages"), add 2 conditions by selecting a condition related to the "Request path", which look like so:

Return true on the following pages: group/*.
Do not return true on the following pages: group/*/node/create/article (not sure if you want the /article suffix to be added, pick what fits your content types).

If you also want to show the Global Blocks, then mark the Show Global Blocks as checked.
Use the Place block button to place the Views block in the theme region of your choice.

Notes:

if you're not familiar yet with this module, then have a look at the video about Block Visibility Groups - Drupal 8 Blocks but Better.
if this question was about D7, I'd use the Rules block visibility module and specify similar Rules Conditions (based on the same current paths).
don't get confused with all the Group-stuff (the Group module, versus the Block Visibility Groups module ...)


Create user after node created and assign node entity reference to it

Download the Rules module
Enable Rules and Rules UI

Add a new rule

React on event: After Saving New Content (it's listed under NODE)
Restrict by type: Hotel

Under Action

Add Action of Create New Entity >> ENTITY TYPE: USER >> For your EMAIL field, Ex: If you called your field "Email" then it's node:field-email. For user name, I guess you will also need to create a field in the node for that too. Then do same steps as e-mail

Note: You can always click on "DATA SELECTORS" to see all the tokens you can use.

Add Action of Set data value >> select your entity ref field (Ex: If you called your field "Test" then it's node:field-test) >> for Value use entity-created:uid
Add action of Send Account Email (listed under USER) >> Account: entity-created

  You can modify the e-mail templates here
  /admin/config/people/accounts use tokens for your needs.

  Let me know how this goes, no time to test this Rule.


How to avoid CKeditor to change the HTML code?

I know that this is not the answer to your problem (which is annoying) but personally I would avoid putting a
 inside a  tag. It is normally not allowed to put a "block" type of tag inside an "inline" type of tag.

So you could do the following:

Your stuff

and then add a CSS rule:

a.block,
a.block > span {
  display: block;
}

This way you are HTML valid and CKEditor should not try to correct it.


No, running Drupal core test suite is wrong. You can assume that your code won't messed up drupal core and if you so - you'll get exception for that and then the fun will start :).

If you came from the ruby world then you probably familiar with the Behat solution and if not you should check this - very easy to use QA platform and a lot of posts were written in order to test your site with behat. But there is also selenium that can help you.

And i'll give a you a tip on how to start the testing suite for your site: For now you probably have a running site. You need to take a pen and paper or a google doc and start what features you create for your site: what happens when the use login, what happens when he create node. After you wrote your tests you can start to write them in test - behat, selenium simple test... what ever! As long as those tests testing your features.

Another tip is: when ever you have a bug and you fixed this, you write a test that verity that the bug can't be reproduced. This the way all of the big projects i know works: OG, Message stack, Open scholar,


How can i include views page in search results

Building a page via the views interface implements this page with the hook_menu. An entirely different approach from the nodes wich are saved in the database.

Views is essentially a query engine wich basically searches those database tables (and only one base table per view).

There is no real way to make a hook_menu implementation appear a node view.
Ollies advice to put your view into a block and add it to a node is probably the best viable option.


Why can't I comment on a module' project page on drupal.org?

The project page of the module you've mentioned or any other module/theme/distribution is meant only have a brief description, and releases of that particular project.

If you need to contact any of the maintainer of the project, you should use the issue queue of the project which could be found at : https://drupal.org/project/issues/{project_name} just replace {project_name} with the project name, in your case awssdk.

Detailed reading here : Use the issue queue.

And if you feel that the project is not being updated / supported for quite some time and the bugs aren't being fixed, and you intend to fix them you have an option to take over the maintainership of the project.

More reading here : Dealing with unsupported (abandoned) projects.


Rendered node display for anonymous users?

If it is working for admins, but not for non admins, you problem is most likely permission. Do the users have permission to see the node? Maybe they need a special permission to see nodes via relationships?

To fix this, you need to tweak your permissions.

If you want to change the way a field is rendered, either on an entity or in a view, you need to create what's called a field formatter, which essentially is a theming function for fields.


Drupal UberCart how can users see thier own orders

If the users are not anonymous users, they should have a tab in their user profile that shows their orders.


Commerce Discount Module : Free Products : n+x

Buy X Get Y offers (or "Per quantity" offers) are supported out of the box in the Commerce Discount Extra module, which we'd like to merge into Commerce Discount eventually:

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


I'm trying to retrieve a custom content type onto the user profile page

Have a look at the Profile 2 module. It replaces the Content Profile module from Drupal 6 and the profile module that is build into Drupal Core.


Will memcache work in this configuration?

Short answer is yes, that's a fairly common configuration.
You might also want to consider using Nginx instead of Apache.

For user session support, it's possible to use Memcache.
However, memcache data is more transient and you may prefer the more persistent storage, for longer and more durable user sessions, that the database engine provides.

For cache_form you should use a more persistent cache, such as the database, to avoid form cache validation errors.

e.g: $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

It's recommended to use Memcache for the lock API layer as it's quick read/write and short cache lifetime is suitable.

e.g: $conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';

For Memcache integration with Drupal, you can use https://www.drupal.org/project/memcache or https://www.drupal.org/project/memcache_storage


How to remove colon in a label which is not in a form - D6

Drupal 6 or Drupal 7? The Drupal way to do this would be to modify the content field template in your theme to remove the colon OR create a custom node template to render the fields without the colon. For the content-field option, in Drupal 6 this file is in your cck folder under:

./modules/cck/theme/content-field.tpl.php

Copy this file to your themes folder and modify it to remove the colon at line 18:

<?php print t($label) ?>:&nbsp;

For a node template, check out the handbook on node templates, theming, etc:

http://drupal.org/node/190815#node-suggestion

There's also this module

http://drupal.org/project/no_colons

if you want another alternative.


I found that one of my colleges had written an invalid file in the drush folder.  I was writing mine in my ~/.drush folder.

The result was it would run his code, then my code, leaving a big mess that drush could only partially understand

I fixed the incorrect file and the code I posted in the question started working.  I can now run drush commands against a site-list.


How to print url arguments in headers view

<?php print arg(1); ?>

See: arg

Arg can be used to get the url arguments. It's 0 indexed, so 0 will give the first url argument.

Notice, when using url aliases that arg will bring the internal url arguments (the original path).


If you are under apache, you can use mod_rewrite to deliver others robots.txt :

  RewriteCond %{HTTP_HOST} ^domain1.com$
  RewriteRule ^robots.txt$ robots.domain1.com.txt [L]
  RewriteCond %{HTTP_HOST} ^domain2.com$
  RewriteRule ^robots.txt$ robots.domain2.com.txt [L]

Note you may also generate your robots.txt in some controller for each site depends on config and fallback to default if not defined.


You found the answer already. The contextual links you're looking for are just not provided by the views module when using fields (except when you add them explicitly). If you use the node row style in views they're provided through the node system of drupal. For convenience and many more options there's a module for it: Custom Contextual Links


Given a node or node id is there a way to generate an admin edit link to its edit form?

Absolutely, the Url class has a fromRoute method:

$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
$link = Link::fromTextAndUrl('edit', $url);
$build = [
  ...
  'link' => $link->toRenderable(),
];


Rule to create an identical entity to the node created then delete node

Wonders never cease, managed to figure this out. For anyone else:

Created a Rule

EVENTS:

After saving new content of type Article

CONDITIONS:

Entity has a field:

Data selector: node

Field: added ONE field from my source node (one seems to be enough) This was called "discipline" in my case. node:field:discipline

Entity is of bundle:

Data selector: node

ENTITY BUNDLE: Article

(so this is my source node again, my original node I am copying from)

ACTIONS: (this is where we create the entity using the information from the node)

Create a new entity:

ENTITY TYPE:

Article CLONE (this is my entity "content type" name, to make it simple)

Set a data value:

Selected data: entity-created:field-discipline (this is the identical field on my newly created entity that I want to add data to.

Data selector: node:field:discipline (this is the field from the node I want to copy to my entity identical field)

Delete entity:node

3rd step deletes the original node that was created. You can add more "set data values" as you'll need one for each field you are copying over.

This works fine. There could be better ways to do this, of course. Hope this helps someone else.


Is it possible to POST more than one article at once?

As far as I know there is now way to create multiple nodes in one request. You can send multiple requests instead.

The JSON format need not to to be that much complex(as you mentioned in your POST).

You can use the following JSON format to create a node.

  URL : http://www.example.com/d8/entity/node

  Method: POST

  Headers:

  Name: X-CSRF-Token

  Value: TPlhcaO_KESksKPye805T86j0-ja9rhyfaaqi6zpA8

You can get user session token by requesting the following URL

URL: http://www.exmaple.com/rest/session/token

JSON format to create a node  (Article) for D8

{
  "type":[{"target_id":"article"}],
  "title":[{"value":"Hi World"}],
}

I've tested this on my D8 instance. It's working fine. Hope it helps


Here is the way:

  hook_menu_alter()

/**
 *Implemantation of hook_menu_alter()
 */
function your_module_menu_alter(&$items) {
  $items['myuserpoints']['page callback'] = 'userpoints_list_my_userpoints_custom';
}

By using menu alter write your custom function and change the table structure as per your need. And it's done :)


Drupal Commerce order total amount not update after I programmatically changed line item's price

I'v found the way. Put answer here:

function mymodule_commerce_cart_line_item_refresh($line_item, $order_wrapper){
    $line_item->commerce_unit_price['und']['0']['amount']=110;
    $line_item->commerce_unit_price['und']['0']['data']['components']['0']['price']        ['amount']=110;
}

Because the commerce_order_calculate_total() is based on components, so if you only changed the commerce_unit_price amount is not enough. Must change data also.


There are a lot of different methods for doing this.

The basic idea is to detect the content type using one of a few methods and calling drupal_not_found().  When doing this, I typically set the pathauto for these to no-view/[nid], and then detect the request_uri in a hook.  There are some variations, but the all do something really similar.

However, there is a newish module called Rabbit Hole that eliminates the need for custom modules and provides a lot of flexability to how you hide the content.  I had been working on a general use module that did something similar, and abandoned developing it when I found this.  From the project page:

  [It] works by providing multiple options to control what should happen when the node is being viewed at its own page. You have the
  ability to

  Deliver an access denied page.
  Deliver a page not found page.
  Issue a page redirect to any Drupal path.
  Or simply display the content (regular behavior).

  This is configurable per content type and per node. There is also a permission that lets certain roles override Rabbit Hole completely.


Send "Views PDF Display" generated PDF by mail as attachment

I tried a couple of things with views directly, but I had no luck, so I turned to curl. You can create your pdf display and give it a path. Hit that path with curl to download the file that will be generated by your view. My example below is pretty simple, but you can pass arguments with the url just like you would normally.

 $pdf_page = "http://yourplace.net/pdf";
  $pdf_file = fopen('/tmp/my.pdf', 'w');
  $ch = curl_init($pdf_page);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_FILE, $pdf_file);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_exec($ch);
  curl_close($ch);
  fclose($pdf_file);

I tested this with a pdf display built on Views PDF and it worked well. Maybe someone has an answer that utilizes views directly instead of using curl.


Users who just registered can login & change profile information, but cannot create certain contents until admin lets them

As Sandesh suggested, give registered users permission to change their profile information, and remove the permission to create content. When an admin sees that a user is qualified to post content, they will give the user the permission. The permissions will be on an individual basis, so we use the User Permissions module.


Set exposed filter date programmatically

Use the below after set_display line.

function mymodule_views_pre_view(&$view) {
  if ($view->name == 'myview_user'){
    $view->get_exposed_input();
    dsm($view->exposed_input['created']['min']);
    $view->exposed_input['created']['min'] = "2015-01-01";
    $view->exposed_input['created']['max'] = "2016-01-01";

    //$view->set_exposed_input($exposed_filters);
    $view->execute();
  }
}

Please refer the example


How to update a field on menu_link_content (added using menu_item_extras module) entity from node form

There are couple of problems here:

The node form has the menu fields hardcoded. See menu_ui_form_node_form_alter() and menu_ui_form_node_form_submit() for more details.
Turns out the root cause of the field issue is that the Menu Item Extras module updates the bundle value to menu name which happens on pre_save hook of menu_link_content entity. Without menu_name as bundle, the entity wouldn't have any fields associated.

One way to solve this issue is to implement a hook_form_node_form_alter() hook and update the bundle details before trying to update the custom field. Here is the code:

1. mymodule/mymodule.module

/**
 * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = [
        \Drupal::service('mymodule.menu_link_content_helper'),
        'nodeSubmit',
      ];
    }
  }
}

2. mymodule/src/MenuLinkContentService.php

<?php

namespace Drupal\mymodule\Services;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;

/**
 * Class MenuLinkContentService
 *
 * @package Drupal\mymodule\Service
 */
class MenuLinkContentService  {

  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * MenuLinkContentHelper constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * Form submission handler for menu item field on the node form.
   *
   * @param array $form
   *   Form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function nodeSubmit(array $form, FormStateInterface $form_state) {
    if (!$form_state->isValueEmpty('menu')) {
      $values = $form_state->getValue('menu');
      if (!empty($values['entity_id'])) {
        // There is no bundle by default for menu_link_content entity.
        $menu_name = 'menu_link_content';
        if (!empty($values['menu_parent'])) {
          list($menu_name) = explode(':', $values['menu_parent'], 2);
        }
        $entity = $this->nodeSaveMenuLinkContent($values['entity_id'], $menu_name);
        // If no  menu item with given bundle, load and update bundle.
        if (!$entity) {
          $entity = MenuLinkContent::load($values['entity_id']);
          $entity->set('bundle', $menu_name)->save();
          $this->nodeSaveMenuLinkContent($entity->id(), $menu_name);
        }
      }
    }
  }

  /**
   * Updates additional field on menu link content entity.
   *
   * @param int $entity_id
   *   Entity ID.
   * @param string $menu_name
   *   Menu name.
   *
   * @return \Drupal\Core\Entity\EntityInterface|mixed|null
   *   An Entity. NULL, if no entity with given ID and bundle found.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function nodeSaveMenuLinkContent($entity_id, $menu_name) {
    $storage = $this->entityTypeManager->getStorage('menu_link_content');
    // Using loadByProperties() as loading without bundle wouldn't bring the
    // custom field.
    $entities = $storage->loadByProperties([
      'bundle' => $menu_name,
      'id' => $entity_id,
    ]);
    $entity = reset($entities);
    if ($entity) {
      $entity->set('field_searchable', TRUE);
      $entity->save();
      return $entity;
    }
    else {
      return NULL;
    }
  }

}

Note: my checkbox field is field_searchable.


display the multiple value in single field in drupal 7 view

You can do this by "Rewrite results" follow the following steps.

1) Edit the first field and exclude it from display.

2) Edit the second field and click on the "Rewrite results"

3) check "Rewrite the output of this field" checkbox.

4) find your fields in the "replacement Patterns" and put it in the textarea like this [field1],[field2]


The Themekey module has that functionality built in:

  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


Why can't I edit Views in Drupal 6 since moving the site?

I think something went wrong with SQL queries when importing the DB. Can you check if views_display and views_object_cache tables are consistent?

I would try to export each view using the Export function from the old site and then import those in the new site.


In a general sense, what is the purpose of the Drupal DB Semaphore Table

The semaphore table is used from the locking mechanism implemented by default from Drupal. It is not different from the usual mechanism of locking seen in programming: A value is used to verify an operation is already in progress, to avoid conflicts or race conditions. The difference is that, normally, the lock is a file, while Drupal uses the row in a database.

In fact, the locking mechanism has functions to acquire a lock (lock_acquire()), or wait a lock is released (lock_wait()). In both the cases, the semaphore database is used.

// lock_acquire()
// Optimistically try to acquire the lock, then retry once if it fails.
// The first time through the loop cannot be a retry.
$retry = FALSE;
// We always want to do this code at least once.
do {
  try {
    db_insert('semaphore')
      ->fields(array(
        'name' => $name,
        'value' => _lock_id(),
        'expire' => $expire,
      ))
      ->execute();
    // We track all acquired locks in the global variable.
    $locks[$name] = TRUE;
    // We never need to try again.
    $retry = FALSE;
  }
  catch (PDOException $e) {
    // Suppress the error. If this is our first pass through the loop,
    // then $retry is FALSE. In this case, the insert must have failed
    // meaning some other request acquired the lock but did not release it.
    // We decide whether to retry by checking lock_may_be_available()
    // Since this will break the lock in case it is expired.
    $retry = $retry ? FALSE : lock_may_be_available($name);
  }

  //lock_may_be_available()
  $lock = db_query('SELECT expire, value FROM {semaphore} WHERE name = :name', array(':name' => $name))->fetchAssoc();
  if (!$lock) {
    return TRUE;
  }
  $expire = (float) $lock['expire'];
  $now = microtime(TRUE);
  if ($now > $expire) {
    // We check two conditions to prevent a race condition where another
    // request acquired the lock and set a new expire time. We add a small
    // number to $expire to avoid errors with float to string conversion.
    return (bool) db_delete('semaphore')
      ->condition('name', $name)
      ->condition('value', $lock['value'])
      ->condition('expire', 0.0001 + $expire, '<=')
      ->execute();
  }
  return FALSE;

In Drupal, different users can requests the same page, which means different threads or processes could execute the same code at the same time. This could cause problems when the code is, for example, updating a database table. Using locks is a way to avoid this could cause problems.

The reason a database table is used is simply that Drupal requires a database engine to work; using a database table also for the locking mechanism is a way to reduce the requirements. The locking mechanism could be implemented using the APCu extension too, and if I recall correctly, there is a module doing that.


Issue a Conditional Redirect in Drupal 7

You should not use hook_init, but hook_boot as you want to perform the check when caching is turned on. That would also be the best explanation as to why your exit doesn't work. That or you forgot to clear cache after implementing the hook. (All hooks are cached in D7)


Set the "from" header in the email to be in the format "Full Name"

You can use hook_mail_alter() to change the "from" email address of any email sent out from your site. The email address used needs to conform to the RFC standard, which it does is your question's title. But user names can be tricky and might contain illegal characters. There's a comment on the D6 docs that provides a code sample for properly formatting the email address. Your code would look something like...

function yourmodule_mail_alter(&$message) {
  $message['from'] = $message['headers']['From'] = '"Full Name" <email@address.com>';
}

Also, keep in mind that just setting the "from" address may not have the desired results in all email clients (see the discussion on the Drupal issue queue). You might also need to set "sender", "errors-to" and "reply-to" based on your requirements. Those values are in the "header" of the $message variable from the code sample above.


If you look at the code that the Forum module executes in forum_uninstall(), you will notice that it just deletes the field it defines, but it doesn't delete the content type it defines.

function forum_uninstall() {
  // Load the dependent Taxonomy module, in case it has been disabled.
  drupal_load('module', 'taxonomy');

  variable_del('forum_containers');
  variable_del('forum_hot_topic');
  variable_del('forum_per_page');
  variable_del('forum_order');
  variable_del('forum_block_num_active');
  variable_del('forum_block_num_new');
  variable_del('node_options_forum');

  field_delete_field('taxonomy_forums');
  // Purge field data now to allow taxonomy module to be uninstalled
  // if this is the only field remaining.
  field_purge_batch(10);
}

Your module should do the same, and avoid deleting the fields defined for the content type (if they are not defined from the module), or the content type itself.


Allow user to fill out node form, then force registration

There are many ways to achieve this. Two suggestions:

Check out the Rules module. There's a tutorial for your use case described here.
Or use one of the modules already available, e.g. Inline Registration.


How do I turn off full html in comments only in drupal 7

I've always got on well with the Better Formats module, which allows complete control of input formats per type (comment/block/node), role and content type.

Others have answered this too, have a look at these:

Limiting allowed HTML tags in comments only
Disabling CKEditor in comments
Related: Removing the Text Format selection


Select nodes based on entity reference value

You need to JOIN on nid and vid (entity fields are stored per nid/vid), add a JOIN to your email field table, set the fields to select the email value, and set your WHERE clause to entity reference target.

$query = db_select('node', 'n');
$query->join("field_data_field_offline_course_reference", "t", "t.entity_id = n.nid AND t.revision_id = n.vid");
$query->join("field_data_field_offline_course_student_ema", "e", "e.entity_id = n.nid AND e.revision_id = n.vid");
$query->fields("e", array("field_offline_course_student_ema_value"))
    ->condition('n.type', 'students')
    ->condition('t.field_offline_course_reference_target_id', $courseinfo);


Use this module http://drupal.org/project/formblock

Download and install the module. Navigate to admin/structure/block You can see Registration form as a block and choose the region to appear.

User Registration to appear in a block taken from this source.


How to store your own key-value pairs in Redis using PhpRedis with D7 Redis module

Once configured/initialized, the module has a wrapper class/interface Redis_Client
 that contains the library object. It can be retrieved with the getClient() method:

$redis = Redis_Client::getClient()


How to let a user choose a role after their very first login?

I am not sure, but you can try somthing lke this: create form with Form API, on submission change value of Role array in user object.
Example:

function MENUCALLBACKNAME($form, &$form_state, $user) {
 $form = array();
 $form['role'] = array(
  '#title' => t('select role'),
  '#type' => 'select',
  '#options' => //Array of your roles like array(id_of_role => t('Name of Role'), ...)
 );

 $form['uid'] = array(
  '#type' => 'value',
  '#value' => $user->uid,
 );

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

 return $form;
}

function MENUCALLBACKNAME_submit($form, &$form_state) {
 $uid = $form_state['values']['uid'];
 $role = $form_state['values']['role'];

 $account = user_load($uid);

 $account->roles = $role;
 user_save($account);
 $form_state['redirect'] = 'SOME PATH';
}


Display database query results in custom module

To be able to exploit your result, you should fetch your result with one of the function of the Statement class.

If you use the function fetchAll() for example, you will have an array of objects with all your result.

$results = $query->execute()->fetchAll();

You can do a function to create your markup with that array.

You can also not use a function from Statement and do a foreach directly on the result generate by the execute() function to create your markup

$results = $query->execute();

foreach($results as $res) {
    $markup .= "
$res->field_1	$res->field_2
";
}

If you want see how is design your array, you can install the module kint (from the devel module) and display your result with

ksm($results);

Additionnally, to work, your query should have the list of fields it should select.

$query->fields('m', ['field_1', 'field_2']);


How to pass variables into link path within l() function?

Some Examples

Example 1: Link to front page

<?php
// example 1:  front page
print l(t('Home'), '<front>');
?>

Example 2: Link to front page and open in new window

<?php
print l(t('Home'), '<front>',array('attributes'=>array('target'=>'blank')));
?>

Example 3: How to use html

<?php
print l('Home', '<front>',array('html' => TRUE));
?>

Example 4: How to use image instead of text link

Lets create my picture path

<?php
global $base_url;
$path = "$base_url/sites/default/files/ceo5.png";
print l('', 'sites/default/files/ceo5.png', array('html' => TRUE));
?>

Example 5: Add class, ids, etc

<?php
// add a new class to my php ini configuration path
print l(  t('PHP ini configuration'),  'node/3',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf') ));
?>

Example 6: Adding query string to links

Adding a query string to example 5

<?php
// adding query string on example:5
print l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf'), 'query'=>array('id'=>'5','status'=>'ok') ));
?>

The output will be:

http://webemania.com/blog/php-ini-configuration?id=5&status=ok

Example 7: Adding destination to query link

<?php
print l(  t('edit'),  'node/'.$nid.'/edit',  array('query' => drupal_get_destination() ));
?>

Example 8: Create a hash-only link (to #)

<?php
print l('linktext', '', array('fragment' => ' ', 'external' => TRUE));
?>

Example 9: Specific portions of a page

Use fragment attributes Go to php ini configurations short open tag portion: PHP Short open tag

<?php
l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'fragment' => "php-tag")));
?>

References:

How and why to use l() function to create links in Drupal


Firstly I'd say menu titles should be text, for accessibility, maintainability and SEO reasons.

If you must, you could consider using CSS background images by checking the classes or IDs on those menu elements and adding CSS rules target them.


set #empty_option of billing address select list

The problem is that your t() function looks like this:

(t -'- Add a new billing address -');

And it is supposed to look like this:

t('- Add a new billing address -');


How to filter a view relating node and user data?

You can add the same filter programmatically to your view.

/**
 * Implements hook_views_pre_view().
 */
function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_view_machine_name') {
    $info = array(
      'table' => 'field_data_field_points', // name of your “Points” field table.
      'field' => 'field_points_value', // name of value field in that table.
      'value' => array('value' => userpoints_get_current_points()), // dynamic part.
      'operator' => '<',
      'id' => 'field_data_field_points_YOURMODULE', // unique id.
      'group' => 100, // new group.
    );
    $handler = views_get_handler($info['table'], $info['field'], 'filter');

    $handler->init($view, $info);
    $view->display_handler->handlers['filter'][$info['id']] = &$handler;

    unset($handler);
  }
}

It will automatically join the table and add condition to query.


Create 3 Views blocks that display 1st, 2nd, and 3rd most recently created nodes

Create the 3 views blocks with your filters and order by created. Then change the Pager to Display a specified number of items.

For 1st block update the settings (it should say displaying X items) then update the Items to display to 1 and the offset to 0.

For the 2nd block do the same but change the offset to 1 and then for the third block set the offset to 2.

Untested but on a quick check of the options, this should give you what you are after.

Paul


How to allow users to create groups with Organic Groups

Groups are just a special kind of nodes, so you just need to go to Permissions and grant users the right to create nodes of that bundle. Users can create groups by going to yourwebsite.com/node/add/nameofyourgroupnode. There is also a menu link by default.


Is it possible or/and how to restrict access to the block on th certain page using route name?

There is no UI for it, but you can either write your own condition plugin to do that or implement hook_block_access() like this:

function yourmodule_user_block_access(BlockInterface $block, $operation, AccountInterface $account) {

  $hidden_blocks = ['yourtheme_block_id'];
  $hidden_routes = ['entity.user.canonical'];

  if ($operation == 'view' && in_array($block->id(), $hidden_blocks) && in_array(\Drupal::routeMatch()->getRouteName(), $hidden_routes)) {
    return AccessResult::forbidden();
  }
}


Rule to send an e-mail with the URL of an uploaded attachment after node change

You can use these to get file name and file url respectively (Drupal 7.67 Entity API 1.9):

[node:field-document:0:file]
[node:field-document:0:file:url]