Filter entities in a view by referenced entity

Phase1:
You would need to construct a view using contextual filters, relationships and dynamic path (url) to display team members for a department.

First create a view with Content type of Department. Also enable Create a page and add path like for example, /department/%. Here % is used to make your path dynamic (to pass arguments such as nid using contextual filters). Then click continue & edit.
Now in your view under the advanced section, add a reverse relationship to your team member content type. You should select something like A bridge to the content entity that is referencing content via field_teammember. The field_teammember is an entity reference field from team member content type.
Next under fields, add all the required fields you need. If you add any of your team member content type fields, do not  forget to add relationship in those fields settings.
Again under the advanced section, add contextual filters. Select Content:Nid and in the settings do not add relationship because this Nid will be of the department content type (base table of your view).
In the same contextual filter configuration, under When the filter value is NOT available section, select provide default value and then select type as Raw value from URL. The path component value will be the position of % in your url. In the path you specified /department/%, its in the second position. Select 2 for your path component value and click apply.

This should have already generated a view as you required.
Now to preview your view, find an Nid of any department node and paste it in the Preview with contextual filters and click update preview. This will display the team members of that department.

Phase2:
Now create a view of departments list for menu items.

Create a view and select Content type of Department. You do not require a page for this view. Click Continue & edit.
Under fields, if you already have a Title field as your department name then add only an Nid field. And in the Nid field settings enable Exclude from display.
Note: If you don't have title field as your department name, then remove the title field and add a department name field.
Now if you are using title field, disable Link this field to the original piece of content option. Then expand Rewrite results section and enable Output this field as a link. In the link path, add your dynamic url created for previous view like www.xyz.com/department/[nid].
Note: In the link, Nid is replaced with %. This could be some other value in your view, so you need to get this from Replacement Patterns in the field settings.

This will create another view for your departments list.
Now install and enable Menu views module if you don't have it. Next in the Administrator/Structure/Menus, create a menu and in the settings select departments list view to display the list as menu items.
Hope this helps.


Catchable fatal error: Object of class stdClass could not be converted to string includes/theme.inc on line 2742

Clearing your cache goes through all of your code looking for hooks, so something you have installed or updated or written since the last time you cleared cache has this error.

The error technically means that you are trying to use the wrong type of variable in a particular function.  In my limited experience, this usually means you have passed the wrong type of variable to the function before it.

In your case, it looks like you are trying to add a stdClass object $region_content to a string, which is why it is trying to convert it.  You will likely need to dig into $region_content to find the markup you are looking for before adding it to your string.


Question about AuthorizeNet ARB functionality with UC Recurring Module

I enabled the "Log reported ARB payments in watchdog" setting and added the url to the Silent POST URL setting in AuthorizeNet. It is now working fine and recording the recurring transactions in my Ubercart Orders screen.


The Context API allow to pass a variable from view.tpl to template.php file

Example:

In view.tpl file :

context_set('slider_settings', 'slider_class', 'fixed_position');

In theme template file :

function MYTHEME_preprocess_html(&$variables) {

$slider_class = context_get('slider_settings', 'slider_class');
if ($slider_class == 'fixed_position'){
    $variables['classes_array'][] = 'slider_fixed';
}

}

It is an aswer for my own question, because I found a solution by myself, and it might be useful for someone I think..


Make sure your theme contains a zeropint.info file. This makes Drupal see it at admin/appearance
Clear the Drupal cache

Now your theme should be listed


Ajax submission leads to => An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports

So after a throughout debugging i finally found the solution. the first thing i did is that i searched for the error and it was outputed from core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php :: wihtin we find a condition that interests us:

if ($exception instanceof BrokenPostRequestException && $request->query->has(FormBuilderInterface::AJAX_FORM_REQUEST)) {
  $this->drupalSetMessage($this->t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', ['@size' => $this->formatSize($exception->getSize())]), 'error');
  $response = new AjaxResponse();
  $status_messages = ['#type' => 'status_messages'];
  $response->addCommand(new ReplaceCommand(NULL, $status_messages));
  $response->headers->set('X-Status-Code', 200);
  $event->setResponse($response);
  return;
}

So the error is triggered if an exception instanciated of the BrokenPostRequestException class has occurred.

and now if we got to Core/lib/Drupal/Core/Form/FormBuilder.php we find that this exception is thrown if the post request is bigger than what is allowed by the server and also if the request doesn't carry the form id.

if ($ajax_form_request && !$request->request->has('form_id')) {
  throw new BrokenPostRequestException($this->getFileUploadMaxSize());
}

  It would have been better if there was another exception for this case
  rather than getting the same error for when the post request exceeds
  the configured allowed size (post_max_size)

well in my case it was not a matter of post size request but rather when I themed the form in my twig file, I did not include the form id.

So what i did is i added the lines highlited bellow:

Filtres

        <form> //Added this one
            {{ McRefund_build_data.filterform.form_build_id }} //Added this one
            {{ McRefund_build_data.filterform.form_id }} //Added this one
            {{ McRefund_build_data.filterform.RelevesMensuels }}
            {{ McRefund_build_data.filterform.from }}
            {{ McRefund_build_data.filterform.to }}
            {{ McRefund_build_data.filterform.example_select }}
            {{ McRefund_build_data.filterform.actions.submit }}
        </form> //Added this one

        {% for Num_refund,refund in McRefund_build_data.filterform.RefundsContainer['Refunds']['#Refunds_data'] %}
                   ............
                   ............
                   ............
        {% endfor %}


How to ONLY display an image in the teaser for Drupal 7

The display suite module will give you this feature. It will give you advanced teaser-templates where you will be able to display one or multiple fields (and the option to display title or not) + you will get along quite easily!


@kiamlaluno is right, you have to use the form builder directly. But for this question in the comments there is a solution:

  ... its a custom class extending FormBase. But I still don't get how
  to change the submit handler. In my controller ...

you can put additional parameters in formBuilder()->getForm('Drupal\custom_module\Form\CustomForm', $param), which you then can use in the form class to build the form differently, for example add different submit handlers:

  public function buildForm(array $form, FormStateInterface $form_state, $param = NULL) {

    if ($param == 1) {
      $form['actions']['submit']['#submit'][] = 'custom_module_form_submit';
    }

  }


Relationship between node_access gid, roles and workflow

Looking at the source (the function workflow_access_node_access_records()), it looks to be the rid, which is the role id. Additionally, it is also defined in workflow_access_node_grants(), which returns the gid's for a given user. And that is the role id's for 'workflow_access' and the user id for 'workflow_access_owner'.

There is also a {workflow_access} table, that contains information about which role has which permissions for each workflow state. Based on that, the access grants for each node are then built.


To show or hide some form elements you can use #states attribute.

$form['fm_first_in_firm'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show form.')
);

$form['firm_registration_container'] = array(
  '#type' => 'item',
  '#attributes' => array('id' => array('firm-reg-container-div')),
  // make this form item visible only if "fm_first_in_firm" is checked
  '#states' => array(
    'visible' => array(
      ':input[name="fm_first_in_firm"]' => array('checked' => TRUE)
    )
  )
);


If I were you, I'd rather do this in my module code to access the links data:

function mymodule_block_view_alter(&$data, $block) {
  if($block->title == 'myblocktitle') {
    $data['content']['#content'][idofthenodelink]['#access'] = false;
  }
}

And your link will no longer be accessible.

Here is the dpm($data['content']['#content']) after the operation:


How to theme table row to link particular column data?

You can try using the render element syntax for a Link element, like this:

$rows[] = array(
  'name' => array(
    '#title' => $row->name,
    '#type' => 'link',
    '#url' => $profile_url
  ),
  'mail' => array(
    '#title' => $row->mail,
    '#type' => 'link',
    '#url' => 'mailto:' .  $row->mail,
  ),
);

That way you can stick to a more consistent coding style, i.e. render arrays for presentation.


Scoping an admin link to only show for certain node bundles

I solved this. I mentioned that I had tried hook_local_tasks_alter when I should have been using hook_menu_local_tasks_alter

/**
 * Implements hook_menu_local_tasks_alter().
 * @param $local_tasks
 * @param $route_name
 * @param RefinableCacheableDependencyInterface $cacheability
 */
function mymodule_menu_local_tasks_alter(&$local_tasks, $route_name, RefinableCacheableDependencyInterface &$cacheability)
{
  if ($route_name == 'entity.node.edit_form') {
    $route_match = \Drupal::routeMatch();
    $node = $route_match->getParameter('node');

    if ('A' != $node->bundle()) {
      unset($local_tasks['tabs'][0]['my_module.related_B']);
    }
  }
}


What are the database tables related to comments in Drupal 7?

I know following tables.
1. comment
2. field_data_comment_body
3. field_revision_comment_body
4. node_comment_statistics

Beside that, I think, comments are also stored in any other tables installed by modules, and linked to comment modules.


Before saving a node how to get the file path

Check out hook_file_presave() function.

You might have to additionally rename/move the file after it has been uploaded.

See also this thread and check the File (Field) Paths module as it might have already the functionality you need.


You can use features module to export your panel page in form of a module.


how to automatically select entity reference field value from url when adding a node

I think the easiest way would be to use hook_form_alter() and set a default value for the field. You can use arg() to get the course ID


Is there a module for using Google Analytics to display popular content?

Google Analytics Statistics has integration with views...

Project page says

  This module provides views integration for the Google Analytics Data
  Export API.

  This allows you to use Google Analytics directly through views to do
  things like Most Popular, Most Read ect. You can combine the
  statistics to create interesting results.


It could help.

add php function:

use Drupal\Core\Ajax\AjaxResponse;

Class AnyClass extends FormBase {

public function buildForm(array $form, FormStateInterface $form_state) {

/**
 * Running the library drupal core ajax
 */
$form['#attached']['library'][] = 'core/drupal.dialog.ajax';

}

}


How to redirect an exposed filter query to a views results page that lives in another panel page?

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id=='views_exposed_form') {
    global $base_url;
    $form['#action'] = $base_url.'/path_that_you_want';
  }
}


How to create a content type to embed video in drupal 6?

You are looking for Embedded Media Field module. After enabling just paste the URL of the video, it will render the video on the page. It supports almost all the videos like youtube, vimeo, etc..

  This extensible module will create fields for content types that can
  be used to display video, image, and audio files from various third
  party providers. When entering the content, the user will simply paste
  the URL or embed code from the third party, and the module will
  automatically determine which content provider is being used. When
  displaying the content, the proper embedding format will be used.


I can recommend taking a look at Sarnia

  Sarnia allows a Drupal site to interact with and display data from Solr cores with arbitrary schemas, mainly by building views. This is useful for Solr cores that index large, external (ie, non-Drupal) datasets that either aren't practical to store in Drupal or that are already indexed in Solr.

I am using to search a solr index with emails imported with the dih


Migrating Users with Migrate D2D when/if they already exist

If Migrate and Migrate D2d modules are installed with the UIs, go to Content > Migrate tab. Once you get the migration set up, there is an option under "options". Check "update" and it will just update the existing users with any information that is new or not matched, keeping the UIDs, etc. It will also update with any new users. It's a long process if you have a lot of users, but so far so good.


Copy the schema.xml from the Search API Solr module into Open Solr. Also be warned that compatibility with 4.x is not stable, so consider using solr 3.x configuration instead.


Why does Drupal not register Menus Nor Links?

It would be interesting to see if your problems could be related to the "memory limit", which might not be high enough (anymore), especially since in the OP it says "I have many modules enabled".

I'm assuming that this is NOT a multi site. So therefor consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

ini_set('memory_limit', '100M');

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Curious to hear if that helps somehow ...

Here are a few other thoughts that might ring a bell in the right direction (if you haven't tried them yet):

temporary turn of all caching, to see what the impact is of doing so. Of course that cannot be the real solution in most cases, but at least it might give some indication like "it seems to be caching related".
what about compression of JavaScripts and/or CSS? If you have turned them on, what happens if you (temporary) disable them?


@Ivan Jaros is correct.

a) use dependency in your module info file, b) implement hook_requirements, c) activate the field only if the other module exists(ie. soft dependency).

  @Kevin, after you've enabled the module

Use a) and c) above.

  Drupal end-users get prompted to download and install the new dependency.

In c) you need to set a message to the user explaining why the field is unavailable and where to get the dependency.  Use function drupal_set_message.

Links:

D8: module exits, https://www.drupal.org/node/1894902 , see \Drupal::moduleHandler()->moduleExists($module)

D8: set message,  https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_set_message/8.4.x


Why is my cart empty after I click on the "add to cart" button?

I had the same issue in drupal 7. I disabled secure pages module and used .htaccess file for https stuffs.


Boost Cache helps some pages, hurts others?

There is an option in boost that let you count the number of hits even of cached pages. That version hits your database on each page hit. It's fairly small, but it still loads all the modules as it has to go through the standard Drupal initialization.

Make sure you turn that off if it is on to ease the load on the DB.


How to make a private file visible after changing file URI?

It sounds like Drupal is telling the browser that the PDF file is an image.

When you're modifying an existing file entity, File::save() will not change the filemime property of a file automatically. Drupal only does this during execution of ::preCreate().

The filemime property isn't being used when serving from the public dir, but is being used when serving from the private dir (where Drupal is serving the headers/payload instead of your web server).

Try executing $file_entity->setMimeType('application/pdf') or create a new file entity with your PDF artifact.


I did something similar using the module Views Field View.

Module Page Description:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Is it possible to dynamically disable a module at runtime?

The concept of disabling modules (separate to uninstalling them), did exist in Drupal 7, but it was removed in Drupal 8.
You will either need to uninstall the modules, or find a different way to disable the specific behaviours which are causing you problems, via events/hooks/etc.


Why is my validate function not receiving the value of my form element?

In the description for the "#name" attribute is reported the following text:

  INTERNAL, except for buttons. All button and submit elements on a form should have the same name, which is set to 'op' by default in Drupal. This does not apply to image buttons. For non-button elements, Drupal sets the name by using 'foo' in $form['foo'] as well as any parents of the element.

You should not set that attribute, which is considered internal.


Actually there seems to be nothing wrong about using *.inc files in D8. Have a look at the Update core module. Quite some *.inc files present: cgit.drupalcode.org.

Nevertheless I tend to follow Symfony's best practice examples when it comes to stuff like that.

[Symfony Docs] Organizing Your Business Logic

[Stack Overflow] Where to put model helper functions in Symfony2

Means you'll add a new class under src/Utils. For example:

src/Utils/HelperFunctions.php
src/Utils/FooBar.php

And then wherever you need it, you reference it:

use Drupal\MYMODULE\Utils\HelperFunction;
use Drupal\MYMODULE\Utils\FooBar;

And then you'd call a certain function like so:

$site_color = HelperFunctions::getSiteColor();
$foo_bar    = FooBar::returnFooBar();

And when I'm still unsure, I'll search inside the core and contrib modules how they did it.


You've got two options, depending on your needs

Static cache - data is built once during a single request and re-used where needed. Your query will run once but once only on every related request. See drupal_static() for example usages.
Backend cache - the results of your database query are cached, and you query the cache bins for the data instead of your database table. Your query will be run once only, until the cache is invalidated, when it'll obviously need to be run again. You'll still incur the overhead of querying the cache, so if your cache is database-based, this may or may not be worth it, depending on the size and complexity of your data. With this method you'll also need to think about how/when/if you invalidate the cache to get fresh data. See the Cache API docs for examples.


If you have a custom module, you can use drupal_add_feed, should work for both D6 and D7:

function CUSTOM_preprocess_page(&$vars) {
  drupal_add_feed(url('path/to/feed'), 'Feed Title');
  $vars['head'] = drupal_get_html_head();
}


How to render in template file with some conditions?

You should be putting the business logic of deciding what you want to show (or hide) in a preprocess function in your template.php and make use of the show and hide functions to specify what you want rendered.


How to add a base field for an entity reference to a specific vocabulary

Vocabularies are bundles of the entity type taxonomy term. If you want to reference a vocabulary then first set taxonomy_term as target type and second restrict the field to a specific vocabulary as target bundle:

$definition = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler_settings', ['target_bundles' => ['custom_vocabulary' => 'custom_vocabulary']]);

See change record https://www.drupal.org/node/2576151


Fatal error: Call to a member function fields() on a non-object

SelectQuery::join(), SelectQuery::leftJoin() etc. don't return the query (they return the alias to the created JOIN), so they can't be chained.

Just separate your code out like this:

$query = db_select('hd_lights', 'l')
  ->fields('l')
  ->fields('s', array('stamp', 'message'))
  ->orderBy('`order`', 'ASC');

$query->leftJoin('hd_status', 's', 'l.id = s.id');

$result = $query->execute();


Multiple filenames in Entity form notification mail

[UPDATED] Your Rule will need to have some additional actions preceding the Send Mail action.

Add variable (Text). Let's call it - [file_list]
Add Loop that loops over your file field [entity:field-uppladdarfaltet] and produces a List Item. Lets call the list item variable [file_n]
Add action Add Variable (text). Call it [file_item]
Add action Set a Data Value. Data to change will be [file_item]. Value to set will be [file-n:file:name]
Add action Set a Data Value. Data to change will be [file_list]. Value to set will be [file-list:value][file-item:value]<br>. This will add each uploaded file's name to the list with a line break after the name.
Print variable [file_list:value] in the email body.

Here's screenshot:


How to alter a views current pager label to node post date

One thing that comes to mind is to override theme_pager() in your theme's template.php. In fact, this post covers how to do that without messing up the first, previous, next, last labels.


How to use entity_metadata_wrapper for users particulary in hook_user_presave

Try casting $edit as an object:

function mymodule_user_presave(&$edit, $account, $category) {
  $ewrapper = entity_metadata_wrapper('user', (object) $edit);
}


I get the following error message while updating a Drupal site

According to http://drupal.org/node/1489394 some users experienced this problem when updating their rules module.  It looks like you'll need to update your rules, entity and internationalization modules all need to be updated to the latest versions (7.x-1.5 for internationalization and 7.x-1.0-rc2 for entities).  If you already have, try only updating those modules, before attempting to update the rules module (you can disable the rules module.  This should also solve the problem, but I assume you're using it for something or other).

As BetaRide points out above, checking into your web logs may shed some additional light on the problem, in case the above doesn't solve the problem.


Unset terms that show in taxonomy autocomplete

Your best bet would be to create your own autocomplete path. Here are the steps to implement this:

Create a custom module

In hook menu create a custom autocomplete path:

$items['my-module-taxonomy/autocomplete'] = array(
  'title' => 'Custom Autocomplete taxonomy',
  'page callback' => 'my_module_taxonomy_autocomplete',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
);

Create my_module_taxonomy_autocomplete function.  The easy way would be to copy everything from the  taxonomy_autocomplete() function and add conditions in your query. For example:

->condition('t.tid', array(1,2,3), 'IN')

In hook_form_alter() set the autocomplete field from using the default one to the custom one you just made:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_node') {
    $form['field_term'][LANGUAGE_NONE]['#autocomplete_path'] = 'my-module-taxonomy/autocomplete';
  }
}


How can I export Image Crop configuration with an Image Style for custom module?

Please see: https://www.drupal.org/project/drupal/issues/2247257

The uuid under the effects array is used as a "unique ID" for the effect.

Seems technically it "works as designed", but as you can see from the linked project task, there is talk about if it's designed correctly.

Fortunately, the uuid under the effects array is scoped to that effects namespace, so it is safe to have the same uuid under any effects array you have regardless of the image style.

Example:

langcode: en
status: true
dependencies: {  }
name: 136x91
label: '(35mm Film 96dpi) 136 x 91'
effects:
  42cf8d4f-246c-4a6d-835f-868e5bcea297:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- could be any uuid value
    id: image_scale_and_crop
    weight: 35
    data:
      width: 136
      height: 91
      anchor: center-center

Just note that if you have two effects in one image style, they will each need a unique uuid key.

Example:

langcode: en
status: true
dependencies: {  }
name: teaser_290x163
label: 'Teaser Image 290 x 163'
effects:
  bdd99645-b55a-47b4-9337-89453c12658e:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500779 // <- same as above
    id: image_scale_and_crop
    weight: 1
    data:
      width: 290
      height: 163
  4f4a1ff4-f127-4693-af57-d8f0cf3c9de0:
    uuid: 1cfec298-8620-4749-b100-ccb6c4500780 // <- needs to be unique
    id: image_resize
    weight: 2
    data:
      width: 290
      height: 163

So remove the uuid from the first line for the image style itself, but leave the uuid under the effects array when you export.


Drupal commerce - same product with different formats that determine price and get added to line item titles

Googletorp's suggestion seemed like it won't give me quite the result I needed so I tried to do the whole thing with my own add-to-cart form, line item/order creation and so on, but ended up with a lot of issues and work that made me go back and try the suggested approach. Got exactly what I needed much easier in the end. Posting the entire solution here to save possible trouble for others.

First I added a format field (that referenced the same taxonomy terms as the one attached to the product) for the used line item. Set it up so it would be included in the Add to Cart forms. After that I added the pricing rule via the GUI:

Events - Calculating the sell price of a product.
Conditions - Entity has field (line item format field).
Actions - Multiply the unit price by some amount (amount specified in the terms coefficient field).

To modify line item titles to show the selected format I found help here: http://digibits.org/blog/drupal-commerce-dynamic-line-item-titles. The code:

function mymodule_commerce_line_item_type_info_alter(&$line_items) {
  $line_items['product']['callbacks']['title'] = 'mymodule_line_item_title';
}

function mymodule_line_item_title($line_item) {
  $term = taxonomy_term_load($line_item->field_line_item_format[LANGUAGE_NONE][0]['tid']);

  return t('!product (!title)', array(
    '!product' => commerce_product_line_item_title($line_item),
    '!title' => $term->name,
  ));
}

Now I needed to restrict the format selection for customers depending of what the administrator has chosen for the product and display them all as add-to-cart buttons not a select list. This was doable via hook_form_alter():

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Alter add to cart forms.
  if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
    // If the product is available for sale.
    if ($form['submit']['#value'] == t('Add to cart')) {
      // The form should only be for a single product so we can get the id from the product_id field.
      $product_id = $form['product_id']['#value'];
      $product = commerce_product_load($product_id);
      // The original submit button isn't needed.
      unset($form['submit']);

      $i = 1;
      // Create a submit button and additional markup for every given format.
      foreach ($product->field_format_types[LANGUAGE_NONE] as $format) {
        // #name will be used to determine the selected product format instead of the select list value.
        $form['submit_'.$i] = array(
          '#type' => 'submit',
          '#value' => t('Add to cart'),
          '#name' => $format['tid'],
        );
        $i++;
      }

      // This form submit handler needs to be called before any others.
      array_unshift($form['#submit'], 'mymodule_add_to_cart_form_submit');
    }
  }
}

function mymodule_add_to_cart_form_submit($form, &$form_state) {
  //drupal_set_message('<pre>'.var_export($form_state['triggering_element'], TRUE).'</pre>');

  // Get the clicked submit button name.
  $name = $form_state['triggering_element']['#name'];
  // Use the clicked submit button name to set the correct product format.
  $form_state['values']['line_item_fields']['field_line_item_format'][LANGUAGE_NONE][0]['tid'] = $name;
}

In the end I hid the select list via css and that was it.


Capture generated Drupal 7 html output into a variable

Tracking the Drupal flow line by line and function by function reveals the culprit to be ob_flush in the drupal_page_footer function

Using the following instead of ob_flush would make the application a bit more friendly

$data = ob_get_contents();
ob_clean();
print $data;

Expanding on this,

Finally solved by adding a delivery callback to my module_menu function and handling things there to bypass the problem function.

/**
 * Implements hook_menu().
 */
function MODULE-NAME_menu()
{
    $items = array();
    $items['MODULE-NAME'] = array(
        'page callback'     =>  'MODULE-NAME_output',
        'access arguments'  =>  array('access content'),
        'delivery callback' =>  'MODULE-NAME_deliver_html_page',
        'type'              =>  MENU_CALLBACK
    );

    return $items;
}

/**
 * Page callback: Display MODULE-NAME HTML Output
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_output()
{
    return 'Some Output HTML';
}

/**
 * Delivery callback: Render MODULE-NAME Page
 *
 * @see MODULE-NAME_menu()
 */
function MODULE-NAME_deliver_html_page($page_callback_result) {
    /* Adapted from "drupal_deliver_html_page" */
    // Menu status constants are integers; page content is a string or array.
    if (is_int($page_callback_result))
    {
        // Integers mean an error page is required!
        // Send to the default Drupal function and exit.
        // Note use of exit instead of drupal_exit (not needed here).
        drupal_deliver_html_page($page_callback_result);
        exit;
    }
    elseif (isset($page_callback_result))
    {
        /* Print anything besides a menu constant if not NULL or undefined. */
        // Send the correct charset HTTP header if code running
        // for this page request has not already set the content type header.
        if (is_null(drupal_get_http_header('Content-Type')))
        {
            drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
        }
        // Send appropriate HTTP-Header for browsers and search engines.
        global $language;
        drupal_add_http_header('Content-Language', $language->language);
        // Render page
        print drupal_render_page($page_callback_result);
    }
    /* Adapted from "drupal_page_footer" */
    // Perform end-of-request tasks.
    global $user;
    module_invoke_all('exit');
    // Commit the user session, if needed.
    drupal_session_commit();
    if (variable_get('cache', 0) && ($cache = drupal_page_set_cache()))
    {
        drupal_serve_page_from_cache($cache);
    }
    else
    {
        $data = ob_get_contents();
        ob_clean();
        print $data;
    }
    _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
    drupal_cache_system_paths();
    module_implements_write_cache();
    system_run_automated_cron();
}


How can I programmatically get a checkbox value?

Install the Devel module and then use its dpm() function to print a variable to the message area of your page. So inside your submit handler put dpm($form_state->getValue('field_close_this_ticket')); and you'll see what the error message already is telling you: It's an array. While the logger expects a string. What you are looking for is inside $form_state->getValue('field_close_this_ticket')['value'], note the ['value'] at the end.
function helper_ticket_comment_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  if ($form_state->hasValue('field_close_this_ticket') && $form_state->getValue('field_close_this_ticket')['value'] == TRUE) {

    \Drupal::service('messenger')->addMessage(t('Ticket closed'));
  }
}


Removing /var/www/html/sites/all/modules/libraries/libraries.drush.inc cleared things up. I bungled things up somewhere. IRC #drupal-commons confirmed Clive's note above.


I've done something similar by implementing the ThemeNegotiatorInterface. In the function that determines which theme should be used, the following code snippet checks for a 404 Page Not Found exception:

$status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
if ($status && $status->getStatusCode() == 404) {
  return 'name_of_the_theme_that_should_handle_404_responses';
}


This could be a bug, see:

https://bugs.launchpad.net/ubuntu/+source/php5/+bug/1315888
https://bugs.php.net/bug.php?id=53829

As I had the same error and after deep diving I reached to modules/system/system.tar.inc at line 716 which calls gzopen(). Here the errors are suppressed using @.

Actually its giving following error on ubuntu 14.04:

Fatal error: Call to undefined function gzopen() in /var/www/html/drupcom/modules/system/system.tar.inc on line 718

So this is issue with Zlib.
I've tried to solve it using
these instructions, but no luck. Then I found that it is known bug.


The 'edit own' permission should be all you need. Allow the user to create content of a specific node type. Put a gallery, description and any other fields on it.

A little more detail:

Create a content type 'Pages'.
Make sure users can create new pages and edit own pages.
The user makes as much 'Pages' as he wishes.
Put a gallery and any other fields on the content type.

If you want to use other content types instead of fields, use entity reference.


One Option might be BUEditor if you're not tied to CKEditor. BUEditor buttons are easily and highly customizable.


External login , in case internal login fail

You can use:

drupal_external_login_register

  Helper function for authentication modules. Either logs in or
  registers the current user

An example implementation is detailed here:

https://api.drupal.org/comment/13434#comment-13434


Views Slideshow - Bullets or Numbered Pager not displaying

You can achieve pager using View Slideshow by following steps:

Step 1: In view, add Global: View result counter field and mark it as Exclude from display.

Step 2: Now click on Slideshow format settings, go to Pager part and select Global: View result counter field as a Pager Type.

Step 3: To give perfect bullets effect, you will have add some CSS as given below

.views-field-counter {
    float: left;
    margin-left: 5px;
}

.views-content-counter {
    text-align: center;
    width: 29px;
    background: url(../bullets.png) no-repeat scroll center center transparent;
    cursor: pointer;
}

Step 4: Please check out CSS Classes, ID's and HTML markups form below screenshot, which worked at my end.


Get the ID / class of the part of the form that has been repainted with an AJAX callback?

I don't know if its the best solution but this works:

  Drupal.ajax.prototype.commands.customSomething = function(form) {

    var formId = '#' + form.form.context.id;

  };


Change field from Multi-Value to Single-Value

Use VBO

Introduce a new, single-value field in the bundle, then use Views Bulk Operations (VBO) to copy the data from the old multi-value field to the new single-value.

VBO have an option to "Execute Arbitrary PHP Script" where you can insert a PHP-snippet to do the copying, something like:

$object->field_foo['und'][0]['value'] = $object->field_bar['und'][0][1]['value'];

The PHP above is only an example. Use dsm($object); (requires Devel installed) to figure out the datastructure of the entity object you need to manipulate.

When done, delete the multi-value field.

Alternate solution: Node convert

It is also possible to do bulk conversion with Node convert.

To use this method, you first clone the content type, then change the multi-value field into a single-value field in the clone.  Node Convert let you map content field by field, so you copy most fields directly, and then copy the first value of the multi-value field into its corresponding field.

The disadvantage with this method is that the machine name of the type changes, so you may need to fix that in a number of places if it is used a lot.  The advantage that you can do it all in the GUI, no need to write PHP.


Instructive message when a module is disabled accidentally

Absolutely. In the module that calls the function, use one of the following

Drupal 7:

if (module_exists('foo')) {
  // Use a function provided by the module
}
else {
  drupal_set_message('Something is wrong');
}

Drupal 8:

$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('foo')){
  // Use function provided by the module
}
else {
  drupal_set_message('Something is wrong');
}

If your code runs in a context that can use DI, inject the module handler service rather than getting it from \Drupal.

You're right, though, dependencies should be used and then this extra wrapping code isn't necessary.

Dependency management is definitely not "old fashioned", by any stretch of the imagination; not in Drupal, and not in the greater world of programming/frameworks. It's a thriving, constantly-improving area of work.

I'm not sure where you got that idea from, but if that's what's stopping you using the proper methods to solve your problem, you should probably think about reevaluating your opinion, as (and no offence meant by this), it's quite frankly just wrong at the moment.


function msearch_group_apachesolr_query_alter($query){
     $query->addParams(array('fl' => array('ss_firstname')));
 //  $query->addParams(array('fl' => array('ss_lastname')));
}


The file name convention for default views provided by a module uses the extension .views_default.inc.

Alternatively, if a module isn't using standard naming conventions, you can search the code base for hook_views_default_views_alter() implementations (e.g. grep -r '_views_default_views_alter' . ) to find these views.


Where is the content of the pop up bubble in my form validation coming from?

In our instance we used clumsyfingers's code but with parsing fix:

novalidate cannot be "1". It has to be either:

no value
empty value
value = attribute name

like so:

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

  if(strstr($form_id,'webform') !== FALSE) {
    // prevent html5 validation, i.e. on input type="email" fields
    form['#attributes']['novalidate'] = 'novalidate';
  }

}

CSE HTML validator was returning this message:

  The "novalidate" attribute for the "form" element has an invalid value
  "1". This is a boolean (true or false) attribute. The presence of a
  boolean attribute represents true and absense of the attribute
  represents false. Setting a value is not necessary, but if a value is
  set, then it must be an empty string or be a case-insensitive match
  for the attribute's name. NOTE: Never use the values "true" and
  "false".


In hook_form_alter how can I attach libraries on frontend only?

To answer your question, you can get the active theme name using below code in module file.

$activeTheme = \Drupal::service('theme.manager')->getActiveTheme()->getName()

and check if $activeTheme !== 'Your admin theme'.

Recommended way:

In your case as you want to add library specific to theme, it should be added in theme file and not module file.


Rebuild form is not working in #ajax callback

Setting the rebuild in the ajax callback will not work, as the form has already been built at that point. It needs to be set in a submit function, which is fired before the form is built. You also need to increment your counter in the submit function for the same reason - if you do it in the ajax callback, the form is already built so the increment is not saved. It needs to be done in the submit function.

function campaign_new_form_submit($form, &$form_state)
{
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}


Drupal Commerce Product SKU pane not showing after upgrade

SOLUTION:  I've found setting the View Mode to "Product List" makes this appear correctly.


Use the Print module that has an "email the content" functionality where you can control the look of that email including displaying only the page title and a body.


There are many modules available for your requirements. You will need to decide which module fits your requirements.
These are some useful modules.

Views Infinite Scroll

Views Load More

Image Lazyloader


How to export Panels and Mini Panels with Features?

Make sure the panel was not already added to another feature-module. You need to add the pagemanager stuff (handlers and pages) to the feature too.

BTW the pagemanager status enabled/disabled is set via a drupal variable, so check also strongarm: If i.E. node/%node is enabled, then the variable page_manager_node_view_disabled is set to FALSE.


This page was last modified on 1 January 1970

You are trying to access the property of a loaded Node's object in the page template. This variable, $node, will only be available to the page template, typically page.tpl.php, only if the current path is loading a node.

In other words, if you are loading a path like node/NODE_ID, then you are guaranteed the variable will be available. Otherwise it won't be.

The error you are seeing is because of this reason. Try to navigate to a valid node URL and the error will be gone, the variable will be defined, and you can access it normally.

Provide a conditional check in your page template to make sure the variable exists before you access it.

Good Luck!


How to embed a comment in an entity-field query

Provide the comment information via EntityFieldQuery::addMetaData, and then add the comment to the query in hook_entity_query_alter().


To fix the files permission, your folders and files needs to be readable and writable by Apache user.

Example commands to fix your permissions
(assuming www-data is your Apache user, prefix with sudo if required):

chgrp -vR www-data "$(drush dd %files)" "$(drush dd %private)"
chmod -vR ug+rwX "$(drush dd %files)" "$(drush dd %private)"

You need to have drush command available. If you don't have drush, just replace above sub-commands in double-quotes with proper locations to your %files and %private folders.

Then as Drupal admin go to Reports -> Status Report and check for file-system related warnings.


How do I set the default values for creating a new content type?

For content or config entities you can set default values in a hook_ENTITY_TYPE_create():

use Drupal\node\Entity\NodeType;

/**
 * Implements hook_ENTITY_TYPE_create() for 'node_type'.
 */
function mymodule_node_type_create(NodeType $node_type) {
  $node_type->set('display_submitted', FALSE);
}


What is the best way to handle post data in drupal?

You are doing it Wrong(TM). Both the question(!) and especially the answer. Yes, you need to implement hook_menu but your page_callback is drupal_get_form because you never, ever work with $_POST directly for security reasons.


Drupal Hook_Mail_Alter Custom Template fields

In Drupal 6, you can specify further settings:

Navigate to the Contact Form settings page (http://example.com/admin/build/contact/settings)
In the "Additional Information" section, enter the text to display with the contact form.
In the "Hourly Threshold" list, select the maximum number of submissions that a user can make per hour.


Access fields of node content type from event "rules_entity_insert:comment"

Couldn't find an answer using Rules, and ended up adding some code:

function my-module_comment_insert(Drupal\Core\Entity\EntityInterface $entity)
{
   // Get NID and load Node
   $nid = $entity->get('entity_id')->target_id;
   $node = \Drupal\node\Entity\Node::load($nid);
}

From there I can use $node->get('field_something'). Of course if it's an entity reference field (as per my case), there's some work to do.


Next to drupal_mail you also need https://api.drupal.org/api/drupal/developer%21hooks%21core.php/function/hook_mail/6 to send the mails.

This hooks tells Drupal what to do with 'params'. $params['body'] does not automaticaly becomes the body.

From the example module:

function email_example_mail($key, &$message, $params) {
  global $user;

  // Each message is associated with a language, which may or may not be the
  // current user's selected language, depending on the type of e-mail being
  // sent. This $language variable is used later in the t() calls for subject
  // and body to ensure the proper translation takes effect.
  $language = $message['language'];

  switch ($key) {
    // Send a simple message from the contact form.
    case 'contact_message':
      $message['subject'] = t('E-mail sent from @site-name', array('@site-name' => variable_get('site_name', 'Drupal')), $language->language);
      // Note that the message body is an array, not a string.
      $message['body'][] = t('@name sent you the following message:', array('@name' => $user->name), $language->language);
      // Because this is just user-entered text, we do not need to translate it.
      $message['body'][] = $params['message'];
      break;
  }
}

Take extra notice the body is an array!
Edit: some clarification:
The subject of the message is a string, like you would expect. So you can fill the subject line like this:

$message['subject'] = 'Any string, with '. $param['subject'] .  ' or not.';

The body however is not a string, and can not be filled this way. It's an array of strings. The very least you need one part. e.g.:

$message['body'][] = $params['body'];

In the end, Drupal wil implode the array to one big string.

Putting the body in parts allows for other modules to use hook_mail_alter, to change only parts of the e-mail, e.g. only the heading of the message.

/end edit

However, without this hook your mail should have been sent. But it is very likely it was blocked by a spam filter (empty body and empty subject from, probably, an unauthorized source).


Ckeditor uses the ckeditor.styles.js file to define the available styles in the Styles drop down.  Documentation in that file states:

'Styles' button is not enabled by default in DrupalFull and DrupalFiltered toolbars.

If you look at the file, it should be fairly straight forward to modify it using the given examples.

The ckeditor.styles.js file can be copied to a directory accessible by Drupal and modified to include your styles.  Then you have to configure your CKeditor profile to point to the new file, including any applicable CSS.


How can I sum up fields that reside in multiple nodes?

The SUM functionality is actually built into Views for D7.

If you go to your Advanced settings and enable Aggregation, you will see the Aggregation settings applied to each field.

Click on 'Aggregation settings' for the field you'd like to do the SUM functions for and you can select 'SUM' from the 'Aggregation type' dropdown as shown in this screenshot

Taken from Source Sum a field


Do you have an example of hook_menu() access callback?

Drupal is itself an example of how to write code.

The easier example is aggregator_menu(), which contains the following code.

  $items['admin/config/services/aggregator'] = array(
    'title' => 'Feed aggregator',
    'description' => "Configure which content your site aggregates from other sites, how often it polls them, and how they're categorized.",
    'page callback' => 'aggregator_admin_overview',
    'access arguments' => array('administer news feeds'),
    'weight' => 10,
    'file' => 'aggregator.admin.inc',
  );
  $items['admin/config/services/aggregator/add/feed'] = array(
    'title' => 'Add feed',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('aggregator_form_feed'),
    'access arguments' => array('administer news feeds'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'aggregator.admin.inc',
  );

In this case, the access callback is the default (user_access()), and the access arguments are an array containing the string for the permission. The code cannot check more than a permission; if the permissions to check are two, or the conditions to check are not just permissions, then the access callback should be a different one, including a custom one.

node_menu() define some menus that use an access callback different from the default one. The function contains the following code.

  foreach (node_type_get_types() as $type) {
    $type_url_str = str_replace('_', '-', $type->type);
    $items['node/add/' . $type_url_str] = array(
      'title' => $type->name,
      'title callback' => 'check_plain',
      'page callback' => 'node_add',
      'page arguments' => array($type->type),
      'access callback' => 'node_access',
      'access arguments' => array('create', $type->type),
      'description' => $type->description,
      'file' => 'node.pages.inc',
    );
  }

The function that is defined as access callback (node_access()) is the following one:

function node_access($op, $node, $account = NULL) {
  $rights = &drupal_static(__FUNCTION__, array());

  if (!$node || !in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) {
    // If there was no node to check against, or the $op was not one of the
    // supported ones, we return access denied.
    return FALSE;
  }
  // If no user object is supplied, the access check is for the current user.
  if (empty($account)) {
    $account = $GLOBALS['user'];
  }

  // $node may be either an object or a node type. Since node types cannot be
  // an integer, use either nid or type as the static cache id.

  $cid = is_object($node) ? $node->nid : $node;

  // If we've already checked access for this node, user and op, return from
  // cache.
  if (isset($rights[$account->uid][$cid][$op])) {
    return $rights[$account->uid][$cid][$op];
  }

  if (user_access('bypass node access', $account)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }
  if (!user_access('access content', $account)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }

  // We grant access to the node if both of the following conditions are met:
  // - No modules say to deny access.
  // - At least one module says to grant access.
  // If no module specified either allow or deny, we fall back to the
  // node_access table.
  $access = module_invoke_all('node_access', $node, $op, $account);
  if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }
  elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

  // Check if authors can view their own unpublished nodes.
  if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

  // If the module did not override the access rights, use those set in the
  // node_access table.
  if ($op != 'create' && $node->nid) {
    if (module_implements('node_grants')) {
      $query = db_select('node_access');
      $query->addExpression('1');
      $query->condition('grant_' . $op, 1, '>=');
      $nids = db_or()->condition('nid', $node->nid);
      if ($node->status) {
        $nids->condition('nid', 0);
      }
      $query->condition($nids);
      $query->range(0, 1);

      $grants = db_or();
      foreach (node_access_grants($op, $account) as $realm => $gids) {
        foreach ($gids as $gid) {
          $grants->condition(db_and()
            ->condition('gid', $gid)
            ->condition('realm', $realm)
          );
        }
      }
      if (count($grants) > 0) {
        $query->condition($grants);
      }
      $result =  (bool) $query
        ->execute()
        ->fetchField();
      $rights[$account->uid][$cid][$op] = $result;
      return $result;
    }
    elseif (is_object($node) && $op == 'view' && $node->status) {
      // If no modules implement hook_node_grants(), the default behavior is to
      // allow all users to view published nodes, so reflect that here.
      $rights[$account->uid][$cid][$op] = TRUE;
      return TRUE;
    }
  }

  return FALSE;
}

There are three points to notice:

The arguments declared with "access arguments" will be passed to the function in the same order; the function uses a third parameter because it is not used only access callback.
The function returns TRUE if the user has access to the menu, and FALSE if the user doesn't have access to the menu.
An access callback can also be used when a menu should be shown only in specific circumstances.


Roles and Permission creation programatically inside module

Create the roles on your development site and grab the configuration for them and place them in:

<modulename>/config/install

When the module is installed it will import that configuration. hook_install is deprecated for installing configuration with a module.

Remove any uuid information from the export as it won't be applicable in most sites.

If you are unaware how to export/import configuration in drupal 8, you should read:
D8 Configuration Management

edit: Just as an aside fact, you can in theory write your own config.yml files however until you are very familiar it's easier to just create the role, and export it.


Add javascript to returned form after ajax validation

you can attach custom jQuery functions in your modules every time you load content just attaching functions to the Drupal.behaviors like this:

(function($) {

  Drupal.behaviors.your_module = {

    attach: function(context, settings){
      $('#element').bind('click', function(event){
            alert('hello!');
      });
    }

  }

}

In this way, every time Drupal loads content, no matter via ajax or a page refresh, it will automatically attach the desired behaviors. Don't forget to include the js in your pages.


Removing breadcrumb from the Homepage in Bartik theme (Drupal 7)

You can also comment them out on the page.tpl.php like so

<?php /* if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

   <?php endif; */?>

And then if you want them back later... take the /* s out. :)


How to add a custom field to personal campaign page - Civicrm

At this time, you cannot currently add custom data to Personal Campaign Pages (see the list at example.org/civicrm/admin/custom/group?action=add&reset=1).  If you wanted to do that, your best bet would be to write the code (or pay someone to write the code) that does this, and get this contributed back into CiviCRM.


If they ask you to update menus then they should give your user role the permissions to make menu changes, whether you have access to FTP doesn't really matter in this case.


Drupal 7 -- Would like to use unique profile template per role

Have a look at ThemeKey.
From the project page (emphasis added):

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

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server


Adding an image base field to custom content entity

Looks like you need to specify the target_type.

It should get the default from FileItem::defaultStorageSettings(), I am not sure why that doesn't work.

Unrelated, but note that you should not call t() like that, as it makes it impossible for potx to extract translatable strings from your code. Also, watch out for https://www.drupal.org/node/2363099, you need to update it to use nt() then.

Edit: Turns out, the problem is that the code was using setSettings(), which is considered problematic because it replaces all existing settings, including defaults. Switching to setSetting() for specific settings should solve it.


Using Drush site-install with multisite and a single database

this is how I do mine...

drush -y site-install standard --db-url=mysql://$username:$pass@127.0.0.1:3306/$dbname --site-name="$sitename" --sites-subdir="$sitename"

sitename for instance could be test.drupalserver.com and to keep it in good practice for dbs i strip out the periods and the $dbname would be test_drupalserver_com.

I believe the way my drush command works, it creates a new db that matches the name of the site.


Clean URLs not working, I can't log in to Admin Panel

You can add this line to your settings.php file and it would allow you to login

$conf = array( 'clean_url' => 0,);

Another method is to find the .htaccess file in D7 root, and open it,
find the "# RewriteBase /drupal" in codes, delete the "#", change the "drupal" to your file's name: my file is "blog",
"RewriteBase /blog" - the end change to this.


How to do automatic card authorization during checkout process?

Is this a Drupal 7 or a Drupal 8 site? That will impact the admin URL as noted below:
8: /admin/commerce/config/payment-gateways/
7: /admin/commerce/config/payment-methods/

You will want to edit the Authorize payment method, and look for "Default credit card transaction type" - that setting should be "Authorization and capture" as opposed to "Authorization only"


Help debugging "cron run exceeded the time limit"

I suspect you could check that arg(0) == "node" and is_numeric(arg(1)), which would detect the internal path for a node display and not cron.  You would also need to check arg(2) for "edit" and a few others, that may (or may not) appear as local tasks for your nodes.


Decoupled Drupal - Security: files structure

I solved my problem, the calls were failing due to a wrong version of PHP (you need 7.2 or higher).
As for the files structure I just put all the files in the root folder, both for Drupal and Angular, it works having my Drupal site in the web folder, I don't know for other configurations.


How to prevent Drupal from automatically truncating blog entries?

The length of the body text for a node teaser is set in the "Manage Display" section for  the content type's fields.

Just go to http://mysite.com/admin/structure/types/manage/blog/display/teaser, and change the format/format settings (i.e. "Trim length") until the teasers look exactly like you want.


View list of teasers wrapped in  instead of

You could use the Views module to output an unordered list of teasers. You can use the HTML List display type, along with a Node: Teaser field.


How can i remove title requirement for content type

I dont' think you can entirely remove the title from the nodes but you may hide it and automatically populate it, as is below:

Auto node titles and Title override

I have used the first one before.


I'm pretty sure EPS files can't be displayed in browsers, which may be why you're having a problem. There's a module which will allow for EPS files to be converted on upload, which may solve your particular issue:

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


Drupal Multilanguage domain specific with PORT not working

I'm pretty confident that the reason for your issue / problem, is because Language detection by domain only works on port 80. That issue has 'some patches' attached to it', and status = Needs review.

Not sure if you want to try/consider experimenting with any of the patches in this issue though.

Something else you may want to check is your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. So try to experiment a bit with the various combinations in this order to see if it helps.

Curious to hear if either of those options will somehow help ...


It's ether in a block or in your template. First check the block admin page at admin/structure/block, and look in the section of footer (or something like that). If there is nothing there, it will be in your template. Most likely it will be located in page.tpl.php.


The best way would be to to store an additional value in local storage that is the last time you cleared it.

Each page view, you simply check that value and if the last time was > 24 hours ago, you clear the local storage and set the last clear time to now.

(function () {

  var lastclear = localStorage.getItem('lastclear'),
      time_now  = (new Date()).getTime();

  // .getTime() returns milliseconds so 1000 * 60 * 60 * 24 = 24 days
  if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {

    localStorage.clear();

    localStorage.setItem('lastclear', time_now);
  }

})();

Put this in a JS file that is added only when the current user is logged in.

Here is an example using a module named 'sample':

/**
 * Implements hook_init().
 */
function sample_init() {
  global $user;

  // User with uid 0 is anonymous/logged out, any uid greater is logged in.
  if ($user->uid > 0) {
    drupal_add_js(drupal_get_path('module', 'sample') . '/js/sample.js');
  }
}


It seems there is a module for this: OG Quiz. According to its description:

  This modules creates permissions similar to the core Quiz ones on the
  group level. This allows site builders to give Quiz
  creation/correction/taking permissions at the group level instead of
  globally.


How do I create a block that has links to site registration and forgot password programmatically?

If you want to learn, I suggest, look at the relevant part of drupal core:
user_block_info() - this is the block info definition.

user_block_view() - This builds the renderable array of block.

You see here $block['content'] = drupal_get_form('user_login_block'); This makes the complete user login form. If you want to show only the two link, just change this to something like this:

$block['content'] = array(
  '#markup' => 'the pure html of your links',
);

To check, how to generate the core these links, see the user_login_block() in core. The line 1323 is the html markup in you block's content, what do you need


What does the computed code do for a computed field in content type

The code fetches the id of the node_project.

For example if the node's project field is set 'Foo' it will get the id of that row where it was saved. As its not clear from where $node comes whether its current loaded node or any other node. But it seems that in computed field you are storing the ID of the project

What I think is causing the problem is if project names are FOO and FOO_BAR the query will result both the ids which can cause to store incorrect ids.

You can simply remove the like operator and add equality.


This is more than likely an apache configuration.  Changing it to the RewriteBase /drupal like above will simply allow drupal to know that /drupal is where the site is installed.  You need to either look into moving the files into the original directory that the domain is pointed to, or look into finding the apache virtual host file and point it to the /drupal folder.


status report asks me to run update.php but getting 'no pending updates'

Go to systam.module and check for if (max($updates) > $default) { line after this add dpm($module) you will get to know which module prevents this database update and fix that module accordingly. The code will look like below:

if (max($updates) > $default) {
   dpm($module);
   $requirements['update']['severity'] = REQUIREMENT_ERROR;
   $requirements['update']['value'] = $t('Out of date');
   $requirements['update']['description'] = $t('Some modules have database schema updates to install. You should run the database update script immediately.', array('@update' => base_path() . 'update.php'));
   break;
}


The two locations specified for sites/default/files are different in your example:

First part: http://demo.dolphin-sch.ir/nagara/fa/sites/default/files/mediaplayer/player.swf?file=

Second part:  http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3

I'd check your paths are set correctly everywhere.

EDIT:

This link works fine:

http://demo.dolphin-sch.ir/nagara/sites/default/files/mediaplayer/player.swf?file=http://demo.dolphin-sch.ir/nagara/sites/default/files/audio/12.mp3


How to create a folder after clicking on a button?

The #submit property takes an array of function names rather than a single string:

$form['create_folder'] = array(
  '#type' => 'submit',
  '#value' => t('Create folder'),
  '#submit' => array('custom_submit'),
);


You should set your Base URL to

$base_url="http://site-name.dd:9999";

From default.settings.php

  If Drupal is generating incorrect URLs on your site, which could
   be in HTML headers (links to CSS and JS files) or visible links on pages
   (such as in menus), uncomment the Base URL statement below (remove the
   leading hash sign) and fill in the absolute URL to your Drupal installation.


User added to a specific group should be blocked

Not sure which tokens you have available to select from, but the token site:current-user refers to the user performing the add to group, i.e. some "admin/'users with permissions to add to group". So your Rules Condition seems to be wrong. Due to which your Rules Action is not performed either of course.

And if the list of available tokens doesn't seem to have any relevant token, it may be because you're using the wrong Rules Event.


How to alter the URL path alias generated by content type programmatically?

You can use this module https://www.drupal.org/project/pathauto with this you define the custom path use token


I've done this before using the IMCE module. The description from the module page says:

  IMCE is an image/file uploader and browser that supports personal directories and quota.

So spot on for your needs.


How to disable Review step in Drupal commerce implementation?

Just remove any checkout panes from it in your checkout form configuration.


Try this. I am using this in my base theme, and it works:

global-styling:
  version: VERSION
  css:
    base:
      css/YOURCSSFILE.css: {}


How to make a region available to a non-page tpl file?

Sure, you can use a node_preprocess() hook to create the variable much like this:

function mytheme_preprocess_node(&$variables) {

   // whatever else you are doing goes here

   $block = module_invoke('AddThis', 'block', 'view', 0);
   $variables['mynewblock']=$block['content'];

}

which would call the AddThis module to invoke it's block hook and return block with delta 0.

Lots more detail can be found here:  http://www.pixelclever.com/how-insert-a-block-a-tpl-or-content-programmatically-with-drupal


All the pages should share the common path like
www.domainName.com/practice-areas/1
www.domainName.com/practice-areas/2
www.domainName.com/practice-areas/3

Like if we need to display a particular block on these URLs then we will write

practice-areas/*

Similarly % will only work if there is a common path.

Thanks.


hook_node_access() doesn't work for anonymous users

There is a typo in the code. The code would grant the access to anonymous users when the operation is view, but for any content type.
  if ($op == 'view' && $is_anonymous && $type='basic') {
    return NODE_ACCESS_ALLOW;
  }

The last part of the if() statement (&& $type='basic') always evaluate to TRUE.
That apart, hook_node_access() implementations aren't invoked for pages showing more than a node and when:

The user accessing the node has the bypass node access permission
The user accessing the node doesn't have the access content permission

In the first case, the user has the permission to access the node even if one of the hook_node_access() implementations doesn't give the user the permission to access it. In the latter case, the user doesn't have the permission to access the node even if all the hook_node_access() implementations give the user the permission to access it.
Even if the anonymous users would have the access content permission, a single hook_node_access() implementation giving them the permission to see a node isn't sufficient for anonymous users to see it. It's enough another hook_node_access() implementation returns NODE_ACCESS_DENY for anonymous users, and the anonymous users won't access the node.
The function invoking hook_node_access() is node_access(), which contains the following code. (Comments are mine.)
// Users with the "bypass node access" permission always have access to the node.
if (user_access('bypass node access', $account)) {
  $rights[$account->uid][$cid][$op] = TRUE;
  return TRUE;
}

// Users without the "access content" permission will never have access to the node.
if (!user_access('access content', $account)) {
  $rights[$account->uid][$cid][$op] = FALSE;
  return FALSE;
}

a comment after the invocation of hook_node_access() make clear in which case the access is granted.

We grant access to the node if both of the following conditions are met:

No modules say to deny access.
At least one module says to grant access.

Then, if a node is unpublished, anonymous users cannot access it. Only the user who created it can view it, if the user has the view own unpublished content permission, which isn't checked when the author is the anonymous user.
// Check if authors can view their own unpublished nodes.
if ($op == 'view' && !$node->status && user_access('view own unpublished content', $account) && $account->uid == $node->uid && $account->uid != 0) {
  $rights[$account->uid][$cid][$op] = TRUE;
  return TRUE;
}


db_affected_rows gives fatal error in drupal 7

There is no db_affected_rows() in Drupal 7 I'm afraid. Also you don't need include the quotes in your variable placeholder. Your code might look a little more like this:

$results = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchAll();

if (count($results) > 0) {
  $first_result = $results[0];

  $custom_theme = $first_result->theme_name;
}

It could be even simpler though:

if ($result = db_query("SELECT * FROM {template_config} WHERE user_role = :role", array(':role' => 'the_role'))->fetchObject()) {
  $custom_theme = $result->theme_name;
}


Colorbox isn't working, although all settings are correct

Try the following with colorbox:

Do you have the latest version? If you updated recently to version from colorbox notice that in the module page says Changes since 7.x-2.1: Important: When updating to this version of the Colorbox module you need to update the Colorbox plugin to v1.3.21.1 or later as well.
Mohammed Shameem mentioned in the comments above is valid. He remark the following: please note that colorbox 1.3.26 and 1.3.27 had an error due to which the script was not working with older version of jQuery so you should download the latest version.

However, the version of colorbox included in the Drupal 7.x colorbox module is NOT STATED.


Trying to using Rules to create page redirects to external links per node, but it's not working

Use the field redirection module. A great overview was provided by llulabot

https://www.lullabot.com/blog/article/module-monday-field-redirection

Mind you I've used Views with Conditional Fields to allow a single link to be either internal or external using a views template override when clicked (based on a radio button in the content type). Field redirection is easier to use than your custom solution.


Ideas for notification of map events occurring in some user defined area?

I've managed to find a solution for this one by myself. Here's how I did it.

Step 1: New Subscription and Notification

Create a content type for 'alerts'. This content type features fields like: title (composed by first + last name), first name, last name, email address, alert type (party or police, for instance), status (inactive, optin, optout), plain text (no D8 Geofield module required) with two fields to store map bounding boxes, geocode name, geocode ID and subscription key.
I've implemented a UI dialog in the map that interacts with the user (so she inputs a geocode search or a map draw) and the 'headless' D8.
By using the wonderful D8's RESTful Web Services module, that dialog implements code to POST user input data to the alerts content type. This code is smart enough to deal with subscriptions from a geocode search or user draw, as their requirements are a bit different. It also handles form field validation according to certain business rules, takes care of the verification key generation and forwards the request via Ajax to an external, custom made email verification script.
The custom made email verification script (not a D8 module, just plain PHP code with PHPMailer lib) receives the request and resolves the query string sent there. This guy takes care of query string values validation to the very same set of business rules applied to the form. If everything is fine, an email with the requested data is composed and sent to the user by using a secure SMTP. If there are errors in the query string validation (e.g. user is trying to bypass the form or fake someone), it returns with the validation step error code. At this point, the dialog in 3 above redraws itself to let the user know what have just happened (success or error code translated into human readable language).
All fine up to this point, the dialog code in 3 effectively POST the new alert content and email is sent to the user. This email displays The Big Red Button™ saying something like 'Verify Now!' When a user click (or tap) on it, the second step in the process begins...

Step 2: Subscription Validation

Another custom made, plain PHP script (also totally apart of D8) is called by the last user action from the above step. This scripts also counts on D8 RESTfull powers, the amazing (Guzzle PHP HTTP Client) (*3) to perform various actions related to subscription activation. Here they are:

'Click Here To Verify' call the activation scripts with some query string (e.g. D8 node id and verification key). These are first and foremost validated do the same set of business rules we had before. Looks good? Move on. Fake? Redirect to a nice error page.
A (Guzzle client) (*4) is set with enough options to make it run smooth and secure, '(cookies => true) (*5)' is among then.
A (POST request to login) (*6) is fired. I've created a special user and a role just for D8's API usage. This is to prevent sneakers from the outside. Also, by having a custom made script, I can rest assured the it is always calling on localhost (127.0.0.1), so the Ops guys could set all sort of firewall, proxies and CORS rules to backend protection.
We're in, GET D8's (CSFR token) (*7) for the session.
(GET node content) (*8) and retrieve just the information we need to verify (e.g. status, verification key and such).
Perform validation logic. Fine? Move on. Fake? Redirect to a nice error page.
(PATCH node) (*9) to update the signature status.
(GET logout) (*10) to finish the session, close the Guzzle client by adding header headers => [cookies => true] in this request, and some further cleanup magic.
All set? Redirect user to a nice success page. Something went wrong? Catch exception and redirect to an error page.

During the whole runtime of the script, a specially crafted debug stream and a try/catch carefully listens to any exceptions. When debug is enabled, the page redirection is hold and debug information shows up so the Ops could inspect what is going on behind the scenes.

Well, it doesn't stop there. There are still the optout and the subscription delivery features. However, the above works pretty well as a base for all the remaining steps.

For the sake of completeness to the OP question, the above looks pretty elegant to me (i.e. decoupled, maintainable, secure) and uses no 3rd party D8 modules at all, just the core ones. As a plus, the custom scripts are implement relying on well maintained, open source projects.

For moderators:

Please add the URLs bellow to the places their belong in the text above to as I'm in lack of reputation to do so.

*3 http://guzzlephp.org/
*4 http://docs.guzzlephp.org/en/latest/quickstart.html#making-a-request
*5 http://docs.guzzlephp.org/en/latest/quickstart.html#cookies
*6 http://dropbucket.org/node/6743
*7 https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AcsrfToken/8.1.x
*8 https://www.drupal.org/documentation/modules/rest/get
*9 https://www.drupal.org/documentation/modules/rest/patch
*10 https://www.drupal.org/documentation/modules/rest/javascript


Is there a field tpl for body and/or title fields?

Title does not use a template, but is rendered directly in page.tpl.php by default.

Display Suite can be used to override this behavior. Many examples available. Here's one for D8, but the principal is the same in D7: https://www.webwash.net/using-display-suite-drupal-8-how-to-use-display-suite-fields/

You may also find using preprocess hooks in template.php to be useful.

https://www.drupal.org/docs/7/theming/overriding-themable-output/setting-up-variables-for-use-in-a-template-preprocess-and

Proprocess hooks give you control over the entire render pipeline, so it's hard to give better guidance without knowing more specifics of your use case.


Creating view content link that links to data based on taxonomy terms

Here's how to achieve this:

Add relationship that references the taxonomy field you use in the content type.
Add a Taxonomy term: Term ID field in Views. Exclude it from output.
Add a Custom Text field in Views.
Under Rewrite Results check the Output this field as a link checkbox. In the link path use the token for taxonomy term id - [tid]. If you want to use the core page, just enter taxonomy/term/[tid].

Hope it helps.


Node limit - based on cck field of referenced content type

My point of view this can be done at node submission time

Alter the access callback for the menu callback:

function custom_module_menu_alter(&$items){
    $items['node/add/internship']['access callback'] = 'my_custom_access_callback'
    // Next line needed for Drupal 7
    unset($items['node/add/review-sites']['access arguments']);
}

Add a function as your custom access callback:

function my_custom_access_callback() {
   global $user;

   /*Now check the selected organization which you are selecting from dropdown of entity reference and call it as $no_of_places. Also check the existing internship with same referenced organization and call it as $occupied_seats*/

   if ($no_of_places > $occupied_seats && user_access("create internship")) {
     return TRUE;
   }
   else{
     drupal_set_message('Print message about exceeded limit and/or user permissions.');
     return FALSE;
   }
}


How to hide the content of nodes/ completely, and still maintain use within Drupal?

There are two Drupal modules that offer this functionality:

Rabbit Hole
Internal Nodes


Views Contextual Filters with Wildcards URLs

It seems that the error had to do with URL that was used in the path.

When I originally had the issue I was using "account/page/%" , but after removing account so that it read "page/%" everything began to work as expected.


Cannot access responsive image sources from Twig

-You can use a theme hook to wire in the responsive image sources (yourtheme.theme)

-You can set your content / (or custom entity) "manage display" / the image field: set responsive display. So it will send to the dom all of the url's when rendering the item.


Using hook_form_alter to add a label/placeholder insider a form  tag

You can specify placeholder attribute in '#attributes' array like this:

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['item']['#attributes']['placeholder'] = t('Placeholder text');
  }
}


500 error pages are strictly server error pages. Once the server hands off execution to PHP, Drupal/PHP are responsible for serving their own error page. You might try telling Drupal to redirect the user to a custom error page, along with an HTTP 500 status header, when it receives certain errors within a try...catch block.

However, note that some WSODs can occur at the system level and they could cause a fatal error that immediately halts execution and possibly prevent the catch to execute. One example of this is when your database is not properly tuned to handle queries of certain size (like when doing a Features revert all operation) - the database may choke up, giving you an insta-WSOD.

I'd say the best thing to do is check your apache, MySQL and PHP error logs, and try to isolate the root cause of WSOD on a case-by-case basis, as opposed to trying to cover them up with a pretty-error page. While the errors that cause the typical 500 server error pages sometimes are unavoidable, and having custom server error pages in production is feasible, having WSODs happening live is not.

It looks like you have the server error pages set up properly. You just need to make the distinction that typical server error pages != WSODs. Server error pages can be triggered because of high traffic and resource bottlenecks, but you shouldn't really be having WSODs happen in production, period. These typically happen because of poor coding, optimization or configuration. If you still see an WSOD, make sure you find (and solve) the root cause of the problem first, as opposed to trying to apply a band-aid to it.


It's a way to select by default N/A checkbox

The default N/A will comes the field is not required(not mandatory) and the value N/A will enter to database enen if you are not selected anything.

If you want a N/A selected . Enter another value named "N/A" and make the field as "Required"
and mark the default value as "N/A"(The new N/A will appear along with the default N/A).

Hope this will helps you


php.ini opcache path for multiple websites with shared code base

If I understand your question correctly, I believe you can use ini_set() in your settings.php files if your multisite required different PHP ini configurations.
Example 1a:
// @file docroot/sites/default/settings.php
ini_set('opcache.file_cache', '/path/to/opcache/default');

Example 1b:
// @file docroot/sites/my-other-site/settings.php
ini_set('opcache.file_cache', '/path/to/opcache/my-other-site');


You should take a look at the Unique Field module:

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


add a block of related products to any search result item

you should be able to do with a combination of these:

Views Field View Module

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

and

Views Related Content Module

  Views Related Content is an extension to the Views module. It helps
  show the related contents, related nodes on the content detail page.
  This module makes it easy for you to work with contents, nodes by
  adding the filter criteria by Author, Content Type, Taxonomy Terms in
  the Views configuration.

Adding the related content view as a field in the primary view should show the results for each row. Exactly how to integrate them depends on your set up.


It seems you have two Drush installations - /Users/ivan/drush and /usr/local/bin/drush I'm guessing that /Users/ivan/drush isn't executable and hence causing the error. I suggest just removing /Users/ivan/drush.


You can, of course, use the database API that comes with PHP.

To use Drupal's database API, configure your databases as described in How to connect to multiple databases within Drupal and use db_set_active() to switch between databases.


Default to "no limit" for maximum number of options in field type select

Try to increase  post_max_size value or disable the limit by setting it to 0


If you'd like both sites to use the same code/modules and database (thus sharing users and some content), use the domain access module at https://www.drupal.org/project/domain

If you'd like both sites to have the same code/modules but not the database, check out Multisite at
https://www.drupal.org/docs/7/multisite/multi-site-sharing-the-same-code-base


D7: How can I list duplicate entities based on the entity title and bundle, without custom coding

I'd look at the Entity Bulk Delete module. This module provides a Drush command that can bulk delete arbitrarily specified entity types.

The caveat here is the module does not delete based on your specified logic of duplicate titles. For that, you can modify its EntityFieldQuery in the _entity_bulk_delete_query() function so it matches your criteria for deletion removal.


Unfortunately, Drupal does support that.

The following states may be applied to an element:

enabled
disabled
required
optional
visible
invisible
checked
unchecked
expanded
collapsed

The following states may be used in remote conditions:

empty
filled
checked
unchecked
expanded
collapsed
value

The following states exist for both elements and remote conditions,
but are not fully implemented and may not change anything on the
element:

relevant
irrelevant
valid
invalid
touched
untouched
readwrite
readonly

When referencing select lists and radio buttons in remote conditions,
a 'value' condition must be used:
@code
'#states' => array(
// Show the settings if 'bar' has been selected for 'foo'.
'visible' => array(
':input[name="foo"]' => array('value' => 'bar'),

),
),
@endcode

You can see state support value, but value is array, so can't use condition of value.
See the process states documentation page for more information


turned out i needed an API key for embedly service from http://embed.ly/. here is a good guide on oembed http://mustardseedmedia.com/podcast/episode54

strange. some images showed up even without an API key.


How can I detect what control caused AJAX callback?

I use this code since drupal 7, only changed the first line for drupal 8:

$triggering_element = $form_state->getTriggeringElement();
if ( isset($triggering_element) ) {
  $trigger = $triggering_element['#name'];
  if ( $trigger == 'op' ) {
    $trigger = $triggering_element['#parents']['0'];
  }
}
else {
  $trigger = '';
};

If trigger is 'op', then it is a button and i get the name from the parent.

And see comment of Ivan Jaros, make the names unique.


How to make form buttons call only javascript?

the form button definition below works for me, the #after_build is useful for loading in javascript that can attach the click handler.

$form['add_button'] = array (
  '#type' => 'button',
  '#attributes' => array('onclick' => 'return (false);'),
  '#value' => t("Add"),
);

$form['#after_build'] = array('[module_name]_after_build');

Then my javascript that is loaded in a separate file by the after build function, looks something like:

Drupal.behaviors.[module_name] = function(context) {
  $('#edit-add-button').click(function() {
   ...Do something here
  });
};


How to add 100 contributed modules into git repository fast?

You can use submodule on if you want keep tracking all latest commit for each project, but that means that your project can have development code from one of these modules.

Or, you can also download all your 100 modules with Drush and just do a git add . in the parent directory (git add all files recursively).


To set a value to a date field follow below codes.

Using hook_form_alter

$form["field_event_date"]["und"][0]['#default_value']['value'] = $new_date;

Using hook_node_submit or hook_node_presave (Saving the value to the database)

 function MY_MODULE_node_presave($node)
  {
      $node->field_event_date['und'][0]['value'] =  '2014-09-23 00:00:00';
  }

Or if you need to save value of one custom field(defined in hook_form_alter) to another, see below codes.

function MY_MODULE_node_submit($node, $form, &$form_state) {
  if($node->type == 'my_node_type') {
    $test_date =  $form['test_date ']['#value'];
    //Ensure that $test_date format is '2014-09-23 00:00:00'
    $node->field_event_date['und'][0]['value'] =  $test_date ;
   }
}

I think it may help anyone who is searching for the solution.


Migrate custom content type from D6 to D7

You have to create the destination content type on the D7 site. Migrate/Migrate D2D won't handle that for you.

In your migration class you then use:

$this->addFieldMapping(destinationfield, sourcefield);

If you extend the D2D node migration class (DrupalNode6Migration) then you don't need to worry about defining a query.


Try
foreach($results as $key => &$value) {
    $value->MY_CUSTOM_KEY= "MY CUSTOM VALUE";
}


How to style a programmatically created page with a template?

In this case your page is a form, so you need to create a form template this way:

Implement hook_form_alter() in a module or template.php and set the form's #theme property:

function _mymodule_filedownload_form($form, &$form_state, $mycustomfile)
{
    ...
    $form['#theme'] = array('mymodule_filedownload_form');
    ...

}

Then implement new theme:

/**
 * Implements hook_theme().
 */
function hook_theme($existing, $type, $theme, $path){
  $path = drupal_get_path('module', 'mymodule');
  return array(
    'mymodule_filedownload_form' => array(
      'render element' => 'form',
      'template' => 'form--mymodule_filedownload_form',
      'path' => $path . '/templates',
    ),
  );
}

And then add form--mymodule_filedownload_form.php template with follow code to render complete form (you can render it also by components):

<?php print drupal_render_children($form) ?>


How do I inject a dependency into a @FieldType plugin?

An example for a field formatter plugin with dependency injections. This works differently from services. First parameter injected is the container to get all services needed.

Drupal\Core\Field\Plugin\Field\FieldFormatter

class StringFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

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

  /**
   * Constructs a StringFormatter instance.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Any third party settings settings.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('entity_type.manager')
    );
  }


Advice on using Organic Groups for course management in an academic context

I currently run a site where every 6-12 months users Groups (OG) will change. To help me, I use the Profile2 module, it makes dynamically changing user info such as OG memberships simple. If you're not already using it, have a read of the handbook.

The way I have solved the issue you have addressed is to have a spreadsheet of all the users who have changed groups, run a simple code on my spreadsheet to edit the "groups" column of the users to what they will now be, (you can simply cross reference another sheet, say the enrollment sheet for that class, and if the username or student ID appears there, put that class ID into the group column in the sheet), and when the spreadsheet is complete, simply export as a csv and then run an import through the Feeds module. This gives you the option to update the existing user information, and you have all of the old spreadsheets as an "archive". Alternatively, you could take a snapshot of the tables database, keep this in an archive, and run simple SQL Queries to update the groups of a user.

Let me know if you need more information, if you choose to approach it this way!


Drush dl with dependencies on a multisite environment

Nope; Drush doesn't pass --destination to the command used to download the dependencies.  The code is in drush_pm_enable_validate; patches welcome.

The issue is at http://drupal.org/node/1632578


Pseudo-field for custom entity without hook

As time goes by there's Extra Field now.

  Provides a plugin type for extra fields in entity view.

  This module allows developers to add custom fields by simply providing
  a plugin. Site builders can use these fields in entity view modes as
  normally. Extra fields do not store data and do not have a field
  widget. Extra fields typically combine existing entity data and format
  it for display.


How do I update a field to use a different field_type?

To change the field type you would have to write an update_hook:

Example:

function entity_test_update_8001() {
  // To update the field schema we need to have no field data in the storage,
  // thus we retrieve it, delete it from storage, and write it back to the
  // storage after updating the schema.
  $database = \Drupal::database();

  // Retrieve existing field data.
  $user_ids = $database->select('entity_test', 'et')
    ->fields('et', ['id', 'user_id'])
    ->execute()
    ->fetchAllKeyed();

  // Remove data from the storage.
  $database->update('entity_test')
    ->fields(['user_id' => NULL])
    ->execute();

  // Update definitions and schema.
  $manager = \Drupal::entityDefinitionUpdateManager();
  $storage_definition = $manager->getFieldStorageDefinition('user_id', 'entity_test');
  $storage_definition->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
  $manager->updateFieldStorageDefinition($storage_definition);

  // Restore entity data in the new schema.
  $insert_query = $database->insert('entity_test__user_id')
    ->fields(['bundle', 'deleted', 'entity_id', 'revision_id', 'langcode', 'delta', 'user_id_target_id']);
  foreach ($user_ids as $id => $user_id) {
    $insert_query->values(['entity_test', 0, $id, $id, 'en', 0, $user_id]);
  }
  $insert_query->execute();
}


How does one add a Total(s) row to Views results?

I'd like to make the Total row part of the table, rather than a hacky
solution where I calculate it in the view header or footer. How can
this be done?

I've never used that module, but alternatively, you could do the template file solution.
Since you want this to work in the View's preview, which uses core's admin theme and since you should never hack core, this cannot be solved via theme. Therefore, must be solved via custom module.
Example:

View ID: content
View Display ID: page_1

/mymodule/mymodule.module
/*
 * Implements template_preprocess_views_view_table()
 */
function mymodule_preprocess_views_view_table(&$variables) {
  $view = $variables['view'];
  if ($view->id() == 'content' && $view->current_display == 'page_1') {
    $variables['total_rows'] = $view->total_rows; // pass custom var to template
  }
}

/*
 * Implements hook_theme()
 */
function mymodule_theme() {
  return array(
    'views_view_table__content__page_1' => [
      'template' => 'views-view-table--content--page-1',
      'base hook' => 'view',
    ],
  );
}

/mymodule/templates/views-view-table--content--page-1.html.twig
Copy the code of views-view-table.html.twig and paste into this file and just change the last 3 lines to:
  {% endfor %}

    {{ 'Total'|t ~ ' | ' ~ total_rows }}


Which hooks can alter the display of a node?

It looks like the best solution is hook_node_view(). Unfortunately it gets called on all node renderings, so I'm putting in a check for my content type. The hook hook_view() also exists, but that's only for content types that are completely defined within the module.