How do I go about creating a paid subscription product with Drupal Commerce?

Is the mailing list internal or using an external provider like MailChimp or Constant Contact? If you're giving the user access to an external provider's form that will work but it may also allow them to work around it (for example if they want to share it with their friends).

The most secure way would be to use an API call/period import (for external services) or direct update (for internal mailings) using a conditional action or module that's triggered by completed orders.

Edit for further details: Mailchimp does indeed have an API - http://apidocs.mailchimp.com/ - and a Drupal module at http://drupal.org/project/mailchimp so the current functionality is half-way there. I would go the last step and create a custom module that adds subscribers to Mailchimp when they complete their order. At that point it's still a one-time thing, so for bonus points on recurring payments you could keep track of the subscribers and remove them from Mailchimp using the API if they stop paying.

It would take a little coding but it's a realistic setup. I can't see anything you can do without any coding unless the Mailchimp module allows you to set up a page that can then be limited to the role of users who paid (and then you still have an extra manual step).


Should the "install" button on admin/modules page say "enable"?

My understanding is that not all modules that are available in Drupal are installed. I am speaking for Drupal 7 as I am not sure about Drupal 8.

There are three phases:

Enabled: The code is downloaded to your server and the hooks in .module are being called.
Disabled: The code is downloaded to your server, but the hooks are being ignored.
Not-Installed: The code is downloaded to your server, but Drupal hasn't run the .install file for the module and/or hasn't been made aware to look for the hooks.

Also, it's worth noting that if you disable a module, all your data and configurations remain, while uninstalling a module invokes the uninstall hook and wipes both.

So as you can see, the label is relevant to whether or not the module needs to be installed or enabled. You can go from not-installed directly to enabled, but you must go from enabled to disabled to not installed especially before removing the module by deleting it's files.

https://www.drupal.org/node/1176662


Try

  $node->get('start_time')->getValue();

This actually gives you an array, if you inspect/dump the array, then you'll see that you can get the value like this.

$node->get('start_time')->getValue()[0]['value'];

Alternatively, you can simply use $node->start_time->value;

Note: I am using the default Date field from Core and assuming you're using a Node. Hence the $node, and also worth noting, usually your date machine name will be field_something. Which makes me believe that OPer is using some contrib or custom module.

If you're using some contrib module that allows you to have start and end times on your date field, probably will require a diff solution.


How to un-cache a specific node field (also for anonymous)

You have to make sure you add #cache data inside of a render array only to render elements (containing #type, #theme or #markup). In other places of a render array it doesn't work.

Where you add cache max-age or contexts inside of an entity doesn't make a difference though, because there is no field level, only entity level caching.

Another problem is page caching for anonymous users. See How do I disable Twig and block cache for a specific module?


query API calling db_query result a non-object, but SQL works

In the case of db_query, what you get back from it is a resource (it is just a wrapper around php's mysql_query.

But the answer depends on if you're in Drupal 6 or 7

Drupal 6:

In order to turn that into an object, you need to run db_fetch_object on the result, and if you have multiple results you'd need to loop through it.

For example:

<?php
    $sql = "SELECT buckles FROM foo WHERE llama = 'cheese'";
    $result = db_query($sql);

    while ($rowObj = db_fetch_object($result)) {
        echo $rowObj->buckles;
    }

Drupal 7

Use the nifty db_select api! The examples on that page pretty good, but basically it builds a query and then returns something that's very similar to a PDO object (see SelectQuery::execute for the following example)

<?php
  $matches = array();
  $query = db_select('table')
     ->fields('table', array('field_name'));

  foreach ($query->execute() as $row) {
     $matches[$row->relation_type] = $row->label;
  }


Assign Fields programatically to custom node defined by custom module

To add the body field to a content type, you use node_add_body_field(). To add a field that is not the body field, you use field_create_field(), if the field doesn't exist, and field_create_instance() to assign an instance of the field to an entity (e.g. a node or a user object).

As example of how to use those functions, you can look at standard_install(), which is the installation hook of the standard profile, that contains the following code:

  $field = array(
    'field_name' => 'field_' . $vocabulary->machine_name,
    'type' => 'taxonomy_term_reference',
    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    'settings' => array(
      'allowed_values' => array(
        array(
          'vocabulary' => $vocabulary->machine_name,
          'parent' => 0,
        ),
      ),
    ),
  );
  field_create_field($field);

  $instance = array(
    'field_name' => 'field_' . $vocabulary->machine_name,
    'entity_type' => 'node',
    'label' => 'Tags',
    'bundle' => 'article',
    'description' => $vocabulary->help,
    'widget' => array(
      'type' => 'taxonomy_autocomplete',
      'weight' => -4,
    ),
    'display' => array(
      'default' => array(
        'type' => 'taxonomy_term_reference_link',
        'weight' => 10,
      ),
      'teaser' => array(
        'type' => 'taxonomy_term_reference_link',
        'weight' => 10,
      ),
    ),
  );
  field_create_instance($instance);

The code is adding a taxonomy term field to the content type "Article."


How to select Google Web Fonts (via @font-your-face) from drop down in SWeaver UI?

There should be a solution in the issue queue for SWeaver; several other users have reported similar problems. 2 things to try would be to clear the cache and to install the latest development version.

http://drupal.org/project/issues/sweaver?text=%40font-your-face&status=All


Manually changing URL alias values via phpmyadmin? What does this affect?

Doing any manual updates to the Drupal database is a bad idea unless you know exactly what you are doing.

The {url_alias} table is written to with path_save().  If you look at the source, two hooks may be fired, depending on whether the path is new or update: hook_path_insert() or hook_path_update().

So, if you update  {url_alias} manually, you don't give any other modules the chance to react via the hooks.  Whether or not anything bad will happen depends on whether your system has any of these hooks in use.  Off the top of my head, I am unaware of any modules that do, but you would need to run a module_implements('path_insert') and module_implements('path_update') to be sure.

Your safest bet is to always use the API.  Write a standalone script, and execute it with drush -u 1 scr yourscrpt.php to make sure all of your hooks execute.


How can we sort view result, depend on cookie set or not

For any field you want to pull a value from a Cookie you add an exposed filter, here I add a contextual filter for the field, here a node->title:

Then we configure the filter to pull a value from the URL. If none is provided we define how to find the value via PHP code. This is the secret to pulling the value from a $_COOKIE value.

Then we supply a blurb of code to read the Cookie value:


Those attributes ("u" and "i") are not standard attributes. They seems from this JOSS slider or another slider.

Examine your Drupal modules and the View your want to modify to know which slider are you using. Then check the documentation for that slider.


If you had had that code directly in the page.tpl.php its normal, because your page is rendered in the same time as you try to add the JavaScript.

You should add your code in one file, at the root of your theme called template.php.


What's this type of content actually called?

I think those are called site content (but I don't know if you'll find a name for all of them written somewhere, as you said).


Putting sent private messages into a block

No need to use quicktabs. The tabs functionality is inherent if you use the privatemsg_filter addon module - inbox, sent messages and all mail are exposed as three tabs.

It was only needed to add a 4th tab with the option to send a new private message.

The tab already existed as a page, so adding it was simple using hook_menu_alter().

So the final code is:

<?php
function MYMODULE_menu_alter(&$items) {
  // Make the privatemsg new link a tab
  $items['messages/new']['type'] = MENU_LOCAL_TASK;
}
?>


How can a controller change the url reported to browser?

You've already tagged the question with "redirect", so this is what you need to do in step 2+3. Don't return a render array, but a redirect response to the second route providing a couple of extra parameters:

return $this->redirect('second.route', ['route_parameter' => '123'], ['query' => ['foo' => 'bar']]);


how to link a select field options with the database records

Check out the Form API reference, especially the part about select lists:

<?php
   $form['selected'] = array(
       '#type' => 'select',
       '#title' => t('Selected'),
       '#options' => array(
          0 => t('No'),
         1 => t('Yes'),
       ),
       '#default_value' => $category['selected'],
       '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
   );
?>

You can also consult the examples module for more information.


I can't tell you the exact steps but I can suggest you some workaround for this.

You can use Rules module & create a rule for sending mail after event register.

You can send mail in action. Use Token for mail formatting. Maybe you will need some Mail related modules such as Mime Mail for sending mail.


How do I add classes to main menu ul and li in Drupal 8

Override the twig file for the main menu by saving menu--main.html.twig to your theme. Copy the original menu.html.twig from /core/modules/system/templates/menu.html.twig or /core/themes/classy/templates/navigation/menu.html.twig if your theme extends from Classy.

You can then modify the Twig macro used to generate the menu output. To get a class on the ul's to indicate level, you could do this:

{% if menu_level == 0 %}
  <ul{{ attributes.addClass('menu', 'menu-level--' ~ menu_level) }}>
{% else %}
  <ul class="menu {{ 'menu-level--' ~ menu_level }}">
{% endif %}

You could do similar manipulations to the li's:

<li{{ item.attributes }}>

Just tack on .addClass('class-name') to attributes like so:

<li{{ item.attributes.addClass('class-name') }}>

If you're a HTML/class name snob like myself you can also remove classes like so:
{{ item.attributes.removeClass('menu-item') }}

Which I did on the line above the li in the for loop.


How can I style the webform submissions table?

Check out Is there a "best practice" for overriding a contributed module's controller in Drupal 8?
If you override the WebformSubmissionListBuilder, you can do almost anything you want to the results, including custom theming.


How can the items in a field collection view be restricted to those of its containing entity?

It is rather counterintuitive because the way the settings that need to be changed are labeled. The idea is to filter the view by the Node Id for the containing entity, but that doesn't show up immediately in any of the places you expect to see it..

The first step is to add a Relationships. When you click the Add button you get the option for applying to Add Displays or This block (override). In my case I am doing it for only that view so I chose This block (override).

The relationship I choose is Field collection item (Entity with theConfig Type (field_system_config_type).Config Typeandfield_system_config_type` are the friendly and machine names of the field collection.

The select list for choosing which category to filter on is redundant because Field collection item is the only one there.

The next stage is to choose the Contextual filter. This order has to be followed because unless the Relationship is chosen first, the right elements to select for the Contextual filter don't show up.

The element to select here is the node id for host entity - Content: Nid. It is easier to type it exactly as there are quite a number to choose from.

You then select it and click Apply (this display). After that there is a message This display does not have a source for contextual filters, so no contextual filter value will be available unless you select 'Provide default'. You click on Provide default and in the 'Fixed value select Content Id from URL and click on Apply (this display)

This returns you back to the main Views UI screen and you can save it now.

If you know the node ids of some of the content types, you can test it by typing them in the Update preview box and see the list of field collections they match.


How can I convert HTML entities imported from CSV via Feeds in to readable characters?

Feeds Tamper allows you to html decode your feeds content before nodes are saved.


Ajax callback on select box change event not working on second time

You are using wrong notation for form elements, instead of field_suffix you should use "suffix" tag, as drupal is not able to track your closing tag, for a form element.

function demo_pane_form($form, &$form_state) {

 $options= array(1=>1, 2=>2, 3=>3, 4=>4, 5=>5);

 $form['user_data_form']['reference_number_ajax'] = array(
  '#type' =>'select',
  '#title' => 'Select a Patient',
  '#ajax' => array(
     'callback' => 'demo_pane_dropdown_callback',
     'wrapper' => 'ref_number_list',
     'event' => 'change',
     'method' => 'replace',
     'effect' => 'fade',
   ),
   '#attributes' => array(
     'class'=>array('dynamic-select')
   ),
   '#default_value' => 1,
   '#options' => $options,
   '#prefix'=>'
',
   '#suffix'=>'
'
 );

 $form['user_data_form']['patient_name'] = array(
  '#type' => 'textfield',
  '#title' => 'Patient Name',
  '#value' => 1,
  '#prefix'=>'

',
  '#suffix'=>'

',
 );

 return $form;

 }

 function demo_pane_dropdown_callback($form, $form_state) {

   $form['user_data_form']['patient_name']['#value'] =
   $form_state['values']['reference_number_ajax'];
   $form['user_data_form']['age']['#value']          =
   $form_state['values']['reference_number_ajax'];
   $elements =  array(
     $form['user_data_form']['patient_name'],
     $form['user_data_form']['age'],
   );

  return $elements;
 }


How to insert user registration data to non-drupal table

This looks similar to what happens when someone tries to access CiviCRM tables from Drupal when the CiviCRM tables exist in different database containers.

https://www.drupal.org/node/1569656.

Are these tables in the same database container or just on the same database server?

You may want to look at How to use separate databases for Drupal tables?

It might also be worth looking at http://wiki.civicrm.org/confluence/display/CRMDOC44/Creating+a+Drupal+user+for+every+CiviCRM+contact

That gives both a manual process of generating Drupal users from a CSV export as well as the drush method.


Ajax callback is not working on views exposed filters

Something is weird in the code,
What is that return statement in the last two lines?

For the ajax, try using $form['field_categories']['widget']['#ajax']

Make sure that you have cleared the cache too and that your module is actually called module.


insert webform component values into a custom table

I would suggest taking the data straight out of the webforms DB tables.

To understand how to do that we need to look at how data is stored in the DB.

Each time a new webform is created a row for it is created in the webform table. Each webform has a unique identifier called nid.

Each component added to the webform is stored in the webform_component table and has a unique identifier of cid (cid is only unique per webform, nid is also required to make the primary key).

Now when a user fills in the webform a row is created in the webform_submission table (with a unique id of sid) and each fields value is stored in webform_submitted_data. Each row in the webform_submitted_data table has a nid (the webform ID), sid (submission ID) and cid (the component ID).

So, if you wanted to get all of the data from a particular submission with the name of the field (or component), uid and the data submitted you can use the following query:

SELECT c.`name`, sd.`data`, s.uid
FROM webform_submitted_data sd
INNER JOIN webform_component c ON c.cid = sd.cid AND c.nid = sd.nid
INNER JOIN webform_submissions s ON s.sid = sd.sid
WHERE sd.sid = {YOUR SUBMISSION ID}

Or to show all of the values submitted for a particular field with uid and date then you could use:

SELECT sd.`data`, s.uid, s.submitted
FROM webform_submitted_data sd
INNER JOIN webform_component c ON c.cid = sd.cid AND c.nid = sd.nid
INNER JOIN webform_submissions s ON s.sid = sd.sid
WHERE sd.cid = {YOUR COMPONENT ID}


Form API file upload field default value implementation using AJAX/AHAH

Unfortunately, depsite the vast amount of answers posted to this question, there was no easy way to do this.  In the end, I had to check when the form was being displayed if the form already had content, and if so, if the form had a file attached.  I then displayed a different value rather than the form field and made a validation workaround due to the fact that the file upload was mandatory.

My advice to others with similar problems: if you're using this as an user profile field, avoid FAPI and stick to CCK and Content Profile.  Although it can be a pain sometimes, all of this functionality is already taken care of.


redirect to prod url when creating content

Looks like you need to check the value specified for $base_url, within the settings.php of your dev.prod.com site. Assign a value of (eg) dev.prod.com and see what happens then.


How to override a single function in a core javascript library?

You can enable interface translation for English in /admin/config/regional/language/edit/en

[x] Enable interface translation to English

and then you are able to change the string you are looking for in User Interface Translation.


Replicating a page.tpl Region in Omega's structure

I have solved this issue.

I had to create a Zone. Then add the created Region to the new zone. I then created a zone--zonename.tpl.php file and within that i added

    <?php print $content; ?>

after that all content printed within this zone will be wrapped within my divs and .js and .css files will be applied.

Thank you 2pha for sticking in there with me and helping me with my overall brainstorming =-) hopefully this helps someone else messing around with this stuff.


How to set Media Styles in Media 7.1.2 / Media 7.2.X?

A lot has changed since the madness that was http://drupal.org/node/1092444. Thankfully, theming and setting display formatters for file entities is now much easier and more straightforward.

The following documentation is for Media 2.x and File Entity, although much of it works with Media 1.x with slight alterations (e.g., in Media 1.x, the link to the "File Types" page is in Configuration instead of Structure).

Displaying Media

The File Entity and Media modules work together to provide a unified method for storing, managing, and displaying Media in Drupal. They allow a user to create file fields that can be configured to store and display many different types of media, including images, video, and audio. among others. In order to display these different types of media, file fields need formatters, often provided by the module that provides the Media type, and a little extra configuration.

Definitions

I'll explain a couple of the moving parts first, and then get into customizing the display of files on a site.

File types

Files are grouped into File Types. Each file type is defined by a list of mime types, a universal way of specifying file formats on the internet. The default file types are Application, Audio, Image, Text, Video, and Other. There is currently no way to define new file types in the UI.

View Modes

View Modes are used to tell Drupal 7 (and soon 8) that a piece of content is in a certain context. The content can then be altered or displayed in a way that best suits that context. Two view modes that most people are probably familiar with are the default teaser and full modes. Custom view modes can be defined with modules like Entity View Mode, Display Suite, or in a custom module with hook_entity_info_alter().

The Good Stuff, or: Managing the display of your File Field

A file field's display is managed per file type. Navigate to Structure -> File Types. You will see a list of available file types with links to "Manage fields", "Manage display", and "Manage file display" for each.

Manage Fields

The File Entity module makes all files full fieldable entities, the same as nodes and taxonomy terms. Just like in the "Content types" section, you can add custom fields to each file type.

Manage Display

Again, like in "Content types", you can manage the display of custom fields on each file type. This section does not control the formatting of the files themselves, only the display of fields attached to the file entity.

In this section you will also see a toggle for "Custom Display Settings". When expanded you can enable and disable view modes available for this entity. A view mode must be checked here in order for it to be available in "Manage File Display". At this time it's recommended to use only custom view modes defined by the user and the following default view modes; the rest are left over from Styles module integration and will eventually be removed:

"Teaser" (Currently not included by default. You can add it with the patch in the issue above or define it as a custom view mode)
"Full"
"Preview" (Used in admin contexts, e.g., for placeholders in WYSIWYG fields, in the Media browser, and in the Media field widget)

Manage File Display

In "Manage File Display" you can configure formatters for your file types (yes!). Many Media provider modules add their own formatters here; for example, Media: Youtube and Media: Vimeo both provide a "Preview Image" and "Video" formatter.

Formatters can be enabled and configured for each view mode enabled in their file type's "Manage Display" section. For example, a user may want to display a Media: Vimeo preview image when a node is viewed as a teaser, the Vimeo video when the full node is viewed, and a video with different width and height formatter settings when the node is viewed with a custom view mode called "video gallery". Many formatters (notably "Image") allow the user to select the image styles they have defined in Configuration -> Image Styles.

Because multiple media providers can use the same field, formatters are arranged in a top-to-bottom cascade. Drupal will use the first formatter that can be applied to the output of a field. If a video field enables the "Media: Youtube Video", "Media: Vimeo Video", and "Large filetype icon" formatters for the "Full" view mode, Drupal will use the Youtube formatter if the file's mime type is video/youtube, the Vimeo formatter if the mime type is video/vimeo, and fall back to the large filetype icon if the mime type is video/{anything else}.

Configuring the File Field to display using "Manage File Display" settings

In order for the file field to display using the formatters defined in "Manage File Display", it must be set to display the "rendered file". Navigate to the "Manage Display" page for the content type that contains your file field. Choose "Rendered file" as the file field's format for all view modes in which you would like to use the formatters defined in "Manage File Display".

Further Theming

You can create custom theme functions and template files for even more control with theme hook overrides. The theme suggestions provided by the File Entity module are:

file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}

Replace all '/' and '__' in mime types with '_' for theme functions and '-' for template files.

Some Media provider modules replace these with their own templates and theme hook suggestions. You can view all available theme hook suggestions with the Devel Theme Developer module, Mothership's Poor Themer's Helper, or hopefully consult the provider's docs for more info.

Outro

Hope this helps. I plan on adding this to the Media documentation, so if I missed something, misspoke somewhere, or a section needs clarification please let me know.

And some short answers to the OP's specific questions:

Media 1.x vs 2.x: even though 2.x is unstable, it's as reliable as many stable version modules on Drupal.org. I think it's worth using for the vastly improved features, but because there's so much work going on support in the issue queue is slow, and as with any dev branch new updates may break your implementation. Still, I use it on production.
Media is in development. Some things don't work as you would hope yet (e.g., non-image WYSIWYG integration). But it still works better at what it does than the combination of modules you have to install to do what it does without it. And it's getting better.


How to prevent entering a time-slot that is already taken when using the Calendar module?

I'm not aware of any way to use the Calendar module for this. However, you may want to look at this set of modules (with an official D7 release) that may help to implement the logic you are trying to implement:

Availability Calendars (Reported installs: 2.061 sites).

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Rooms (Reported installs: 1.575 sites).

  ... is a booking and room management solution for hotels, vacation rentals and B&Bs.

Its module page also mentions some related modules you may want to look at, such as:

Rooms Package: Define special offers for bookings.
Rooms Availability Constraints - Allows admins to define availability constraints such as the minimum period of a booking.
Rooms Views- Provides a "Rooms availability" filter and a "Booking form" field to improve the Views integration for Rooms.

MERCI (Reported installs: 441 sites).

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict (Reported installs: 329 sites).

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Simple Reservation (Reported installs: 202 sites).

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependent on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

Room Reservations (Reported installs: 156 sites).

  ... for use by academic libraries to manage access to and use of their study rooms.

  All academic libraries have rooms set aside for student study and collaboration. These rooms are often available on a first come, first serve basis. Many libraries would like to have a room reservation system that would allow students to better plan their use of these often scarce resources, but setting up and administering such a system without computer support is a very difficult and time consuming undertaking.

  The Room Reservation module was created to meet this need. It allows any library to very quickly put together a reservation system customized to its own particular requirements. And once the system has been set up, it performs all the functions necessary to manage the use of group study rooms with practically no involvement from the library staff.

  Although this application was written specifically for use by academic libraries, it could also be useful to any facility that provides rooms that can be reserved and used on a short term basis.

Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

How to pick the module that fits best

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.

So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards. Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Disclosure:
I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).


Get custom field of node in frontend as its type

Finally i found what i want actually in front end.

The below code displays the form that it has on backend.

This form is for 'sports' content type. This wil bring all fields with its widget wherever we calling.

module_load_include('inc', 'node', 'node.pages');
$form = node_add('sports');
print drupal_render($form);


Drupal 7 Get field value by machine name and pass to javascript

It should be Drupal.settings.mymodule.test not Drupal.settings.test. All of this code should live in a preprocess hook (either page or node, whichever is more appropriate for your use case). For the node, you can try $node = menu_get_object('node');.

Example:

if ($node = menu_get_object('node')) {
  $tid = $node->field_test['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting');
}

In your console (like Google Chrome) you can type Drupal.settings to see the entire object, and you should see mymodule as a part of it. Within that you will find test with the term name as a value.


Multiple content types in views in order one by one

Yes that is possible. If A is the name of the content type and 1 is the ID of the content. Then you first sort on ID and then on Content Type.


Taxonomy widget - select maximum level depth

Content Taxonomy is what you're looking for. It extends the default select list widget and adds a maximum level depth.


Form with Site Content that Creates an Entity with User Created Content and Site Content Combined

check out Flexiform module. This can be used for adding/editing entities using custom form. It has its own drawbacks though. So far I couldn't find a way to create multi-step form using the Flexiform. The documentation says it is WIP. Not sure if it is available now.

Here is the article with the comparison on multiple form modules.


autocomplete on a multi value - custom field

If you modify your hook_form_alter to loop through the $delta of field_organization it should work for you on multiples...

/**
 * Implementation of hook_form_alter()
 */
function org_ac_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    foreach($form['field_organization'][LANGUAGE_NONE] as $delta => $field) {
      if(is_array($field) && is_numeric($delta)) {
        $form['field_organization'][LANGUAGE_NONE][$delta]['value']['#autocomplete_path'] = 'org_ac/autocomplete';
      }
    }
  }
}


Drupal 7 Views Exposed Filter - How to Select all Taxonomy terms Upon adding new terms?

You have the answer in the attached image itself.

Just Un-select the Limit list to selected items then save the configuration. Now the all the terms for that selected vocabulary will be listed automatically.

When you selected Limit list to selected items options, only the selected terms alone will be exposed to the user.


How do I use views to create a block that display image and title

Use CCK to upload image.
In Views, display the image with CCK. (Filter > Content:Image)


Unknown column errors because of table alias

I've used the MD5 alias patch from that issue queue here: http://drupal.org/files/issues/views-571548_40.patch (#40) to fix that issue.

You may need to apply the patch manually to views/includes/query.inc

The good news is, if you can do that, it should fix all those alias truncation issues for you.


Gmap for drupal 7 is missing a js file. See http://drupal.org/node/1061444. The discussion may lead you to solution.


I'm not sure what difficulty you're having using the function or what Drupal version you're on, but according to drupalize.me, in Drupal 7 og_is_member() takes parameters $gid (ID of group), $entity_type (defaults to 'user'), $entity (defaults to current user), and $states (optional, defaults to all), and returns TRUE if the entity (e.g. current user by default) belongs to the group.

For example, to find out if the current user is a member of group 4, I would use something like,

$current_user = global $user;
if (og_is_member(4, 'user', $current_user)) {
  // show the user some stuff from group 4
}

The above code is not tested but should get you started.


Instead of using the list field type, I'd suggest you to use taxonomy and term reference field. That way you can always update the referenced term independently, add new terms, delete terms etc.

Create a vocabulary for the field, for example, depreciation
Add as many terms as you want to have in the select list
Add a new field in your content type, and as field type select Term reference; as widget select Select list
In the field options you should assign the newly created vocabulary (e.g. depreciation) to that field

UPDATE:

I assume that you have

a content type called 'car'
a vocabulary called 'model'

You should create a new vocabulary for each list field that you need to make future editable/expandable. If I understood correctly, you want to have the 'depraciation rate' editable, so you should create a new vocabulary called depreciation_rate

Go to admin/structure/taxonomy/add
Name it 'Depreciation Rate' or whatever you like
Add as many terms as you want to have in your 'select list' field. The terms will be listed as options in that field.

Then, you need to create a field to reference this vocabulary on the car content type if depreciation rate is different for every car (or on the model vocabulary if the depreciation rate is different for every model).

Go to admin/structure/types/manage/car/fields
Add new field, name it 'Depraciation Rate' with the machine name 'field_depreciation_name', or whatever you like.
As field type select 'Term reference' and as widget 'Select list'
On the field settings, assign the vocabulary you created.


Are there any naming conventions for helper functions in modules?

How to name a function is described in Naming Conventions which says:

Functions should be named using lowercase, and words should be separated with an underscore. Functions should in addition have the grouping/module name as a prefix, to avoid name collisions between modules.

That is valid for hooks and other functions implemented from the module.
For functions that are not hooks, you could also prefix them with an underscore, right before the grouping/module name. If you do it, you are saying to the developers of other modules that the function is not supposed to be called from other modules, but it is private for the module defining it.
This is a practice followed from PHP which is also followed from Drupal. For example, theme() had been renamed _theme(), before being removed, to make clear it was a private functions modules should not call. It's described in theme() renamed to _theme() and should not be called directly.

The direct callability of theme() was removed in favor of building render arrays consistently. It has been renamed to _theme() and is for internal use only. Build render arrays instead of using _theme() in your code for the following reasons.
Calling the _theme() function directly raises several issues:

It circumvents caching.
It circumvents defaults of types defined in hook_element_info(), including attached assets
It circumvents the pre_render and post_render stages.
It circumvents Javascript states information.


Roster Views with User data plus office content type

Sounds like a perfect usecase for the Group module, whereas you'd use a group type like Offices. And so that you create 1 group (of group type Offices). From then on you have the Group permission system to configure access rules to fit your needs.

And BTW, this can be for either D7 or D8.


Drupal Commons on D6 - Visibility of 'Group members' and 'Latest group activity' blocks

I had an urgent need to fix this issue quickly so I added a few lines of code to one of the Drupal Commons files directly. Once I have more time I plan to extract the functionality into a custom module. Until then this was my fix:

Open file /profiles/drupal_commons/modules/features/common_core/commons_core.blocks.inc
Locate functions '_commons_core_group_activity_block_view()' and '_commons_core_group_members_block_view()'.
Add the following lines before the if statements:

//Determine group nid
 $url_parameter = explode("/", $_GET['q']);
 $group_nid = $url_parameter[1];

//Determine group membership, exclude Admins
 $is_group_member = og_is_group_member($group_nid,$include_admins = FALSE);
Add && ($is_group_member != '') as second condition to each if statement

If you know a better way please share.

Alex


Is it possible to create 'grouped' fields of related data?

You could use the Paragraphs module OR Field Collection module

Example (from paragraphs):

Then with a little CSS magic, you can put them side by side, if you really want it like that.


I solved like this:

function mytheme_preprocess_html(&$variables) {
    $variables['region_name'] = block_get_blocks_by_region('region_name');
}

and then I could do

<?php print render($region_name) ?>


Google/search engine links to Drupal site broken, why is domain missing a slash?

This ended up being a problem introduced with the freshly installed SSL cert and redirecting to https, in combination with using Clean URLs. Turns out there is documentation on configuring Clean URLs and HTTPS with Apache.


How do I disable caching for the Forum module or, alternatively, how do I fix caching?

This documentation is the most suitable for your query: https://www.drupal.org/docs/8/api/cache-api/cache-contexts

Please learn all the details on that page and the other associated page. This may resolve your issue.

Thank you.


How to detect entity translation without using path prefix or domain?

I am adding an answer so others can see what i had to do.

To resolve this we did the following:

Enabled the custom settings for language detection
Enabled "Selected Language"
Set "Selected Langauge" with the highest row weight so it is done first
Enabled "URL" with the second highest row weight
Modified Admin Content (/admin/content) view to output a customized URL that has "?language_content_entity="
Now on click of edit or translate of the that page, it will redirect to the correct language and all my issues are resolved.


It's simpler than attaching node as group post:

  <?php
  global $user;
  $node = new stdClass();
  $node->type = 'group'; // Change this to group node type name.
  $node->uid = $user->uid;
  $node->title = t('Title'); // Change title generation
  $node->body = t('Body'); // Change body generation
  $node->og_description = t('Group description'); // Change group description generation
  $node->og_selective = OG_CLOSED;
  $node->og_register = OG_REGISTRATION_NEVER;
  $node->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
  $node->og_private = 0;
  node_save($node);
  og_insert_group($node);
  og_save_subscription($node->nid, $node->uid, array('is_active' => 1, 'is_admin' => 1));

(ofcourse you also need to check the return values from alle the three functions)


Commerce Order email with an "Unknown" payment method (Drupal 7)

I now found the solution, I need to add the payment method to the order object, so the token system can pick it up and use in the order email.

Before save the order, we need to add the payment method.

$order->data['payment_method'] = 'bank_transfer|commerce_payment_bank_transfer';
commerce_order_save($order);

It can be placed before the transaction section.


When using the StringTranslationTrait in a service why should you inject the 'string_translation' service aswell?

If you didn't inject the string translation service into $this->stringTranslation, the trait would get it from the static \Drupal wrapper

  /**
   * Gets the string translation service.
   *
   * @return \Drupal\Core\StringTranslation\TranslationInterface
   *   The string translation service.
   */
  protected function getStringTranslation() {
    if (!$this->stringTranslation) {
      $this->stringTranslation = \Drupal::service('string_translation');
    }

    return $this->stringTranslation;
  }

and this should be avoided in OOP code. The main reason for this is to be able to inject mock-up services for code tests.


How to override the system timezone in settings.php?

The first example ($config['system.date']['timezone']['default'] = 'Europe/London';) is the correct way to override config values in your settings.php file.
It sounds like you've hit an issue noted in the config override system docs:

Note that values overridden via $config within settings.php will not be viewable from the Drupal administration interface (until #2408549: There is no indication on configuration forms if there are overridden values is fixed, until then you can use Configuration Override Warn or Config Override Inspector) or from inspection via drush (unless you add the --include-overridden flag). The administration interface displays the values stored in configuration so that you can stage changes to other environments that don't have the overrides.

So if you view /admin/config/regional/settings page or the drush cget system.date timezone.default command, it won't show the overridden value.
You can try something like drush cget --include-overridden system.date timezone.default or
drush eval 'print \Drupal::config("system.date")->get("timezone.default");' to confirm your overridden value is actually being set in your settings.php


EntityQuery PHP issue when assigning the query to a variable

Objects work differently than regular variables in PHP. They are "assigned by reference", generally speaking. The Objects and References page in the PHP manual goes into some detail about this. Basically, your = is not working as you expect. $entity_query and $entity_query_points1 are "the same object".
As noted by @baikho in the comments, you'll need to use clone to achieve what you're trying to do.
$entity_query = clone $entity_query_points1;


How to customize the data retrieved by a REST call?

All you need is to define your Resource, take a look at files in site/all/module/services/resources, you can find some examples, but for simplicity I will take you and example:

endpoint_user moduel:

endpoint_user.info file:

name = endpoint_user
description = endpoint_user
core = 7.x

endpoint_user.module file:

<?php
function endpoint_user_services_resources() {
  $endpoint_user_resource = array(
      'endpoint_user' => array(
          'retrieve' => array(
              'callback' => '_endpoint_user_resource_retrieve',
              'args' => array(
                  array(
                      'name' => 'uid',
                      'optional' => FALSE,
                      'source' => array('path' => 0),
                      'type' => 'int',
                      'description' => 'The uid of the endpoint_user to get',
                  ),
              ),
              'access callback' => '_endpoint_user_resource_access',
              'access arguments' => array('view'),
              'access arguments append' => TRUE,
          ),
      ),
  );
  return $endpoint_user_resource;
}

function _endpoint_user_resource_access($op = 'view', $args = array()) {
  return TRUE;
}

function _endpoint_user_resource_retrieve($uid) {
  $endpoint_user = user_load($uid);
  $endpoint_user->custom_field = 'Mohammad Ali Akbari';
  if ($endpoint_user) {
    $uri = entity_uri('user', $endpoint_user);
    $endpoint_user->path = url($uri['path'], array('absolute' => TRUE));
    // Unset uri as it has complete entity and this
    // cause never ending recursion in rendering.
    unset($endpoint_user->uri);
  }
  return $endpoint_user;
}

then create new Service in admin/structure/services and select endpoint_user.

open your browser and go to your service URL, like endpoint/endpoint_user/1

you will see:

<custom_field>Mohammad Ali Akbari</custom_field>

This result comes from $endpoint_user->custom_field = 'Mohammad Ali Akbari'; in _endpoint_user_resource_retrieve


Views Aggregation to count nodes tagged by terms

You can use Views Aggregation to count the number of nodes that each tag is assigned to, and use that as the Sort criteria.

In the Views of type Taxonomy term filter all the terms you're interested about. Add a Name Field to show the term name (you probably already have that covered)
Add a Relationship to the content that the terms are related to Content using field_yourname
Turn on Aggregation (Under Advanced, third column)
Add a Sort criteria Content: Title, (it will automatically use the Relationship from above), Sort descending and adjust its Aggregation settings to Count DISTINCT (if you allow nodes to use multiple terms then Count will count them more than once)

Your terms list will be sorted by the number of nodes tagged by each term in your Views results.

Views Summary for single value fields

If your Taxonomy term reference Field allows for only one value you can use Views summary in a Contextual filter to count the nodes tagged with a term.

You can do it from Taxonomy term Views or Content Views.

If starting from Taxonomy term Views you can use the above steps,
only instead of using Aggregation add a new Contextual filter Name from Taxonomy term Category and configure it to display a Summary:

When the filter value is NOT available
Display a summary
Sort order Descending
Sort by Number of records
Format List
Base path (you must enter the Page path if this isn't the first Page Display in your Views)
Display record count with link

This way you get a list of Taxonomy terms with node count next to them. When you click on them you go to another page listing the actual Fields you set up in Views (you'll probably want to list Content: Title here).

It's a similar procedure to do that from Content Views type.

You'll want to add a Relationship to the relevant Taxonomy field (Taxonomy term referenced from field_yourname),
then add a Contextual filter for Taxonomy term: Name, use the Relationship and configure it to display as a Summary.


Get term weight in node object for ordering with EntityFieldQuery

No, this is not possible. You can only order on actual field values, the term weight would require a JOIN to a non-field table and EFQ is not capable of doing that.

You will have to create a manual SQL query to do this. Note that Drupal by default maintains the node <-> term associations in the taxonomy_index table, that one is easier and more reliable to query than a field data table.


Multilingual translation for anonymous users

I found solution for my problem. The problem is in row weight of url present in detection and selection method in the path admin/config/regional/language/configure.

The row weight for url was -5 and row weight for default method was -6.
Then I changed row weight for url to -7. It works. Now the quizzes are translating properly for anonymous users also.


Print translated links in custom page--front.tpl.php

This might be an obvious answer to experts, but hopefully this will help some newbie someday. I painstakingly investigated the url stuff in Drupal and my findings surprised me - especially when I referred them to the docs.

In the tpl I placed the following nasty debug lines:

<?php dpm(drupal_get_normal_path('alias-en')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'es')) ?>
<?php dpm(drupal_get_normal_path('alias-en', 'en')) ?>
<?php dpm(drupal_get_normal_path('en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('/en/alias-en')) ?>
<?php dpm(drupal_get_normal_path('es/alias-es')) ?>
<?php dpm(drupal_get_normal_path('/es/alias-es')) ?>

And the results were:

alias-en
alias-en
node/298
en/alias-en
/en/alias-en
es/alias-es
/es/alias-es

Only the third result (node/298) was returned as desired, good for passing to i18n_get_path_translations. Even though the drupal_get_normal_path() function docs say the language parameter is optional, and subsequently called drupal_lookup_path() is said to put current language if NULL is passed, it does not seem to work this way.

drupal_get_normal_path() seems to require that you pass two parameters: alias and the language the alias is set for. Only then you'll get the result that will work reliably with i18n_get_path_translations.

I'm close to thinking it is a bug in Drupal or docs, and if no one sheds light on me, I'm going to file an issue.


Clear only CSS/JavaScript cache when files are aggregated

NOTE: I am using the s3fs plugin in order to store assets in an AWS S3 bucket, so if you are not using that your results could differ

This is probably not a suggested method of forcing the system to clear the asset cache, but I was in the same boat and for some reason my file systems got mixed up during multiple edits between local, development, and the live site. For the live site I was only able to get the styles working if the files were not aggregated using the Performance page.

As far as I know, the system will not update the CSS or JS files unless a change has been detected. Aside from going in and making a change to every file I started digging into the database. I found that the file location for the CSS and JS assets were located in the "cache_default" table with a value of something like below:

s3fs:uri:public://css/css_0WFR6_Et4WEJOkLOOpdg4f7EmvMRhsPkSk7KcrPyct4.css

and

s3fs:uri:public://js/js_-YxTfPGZervj7hTx1tF6zyt9ua2DxHPROTbub3I_WRg.js

BACKUP YOUR DATABASE BEFORE GOING FURTHER!
In case you mess anything up, CYA!

I went through and deleted all entries that were a CSS or JS file.
Be careful not to delete the directory reference entries that just
have the JS and CSS folders.
THEN, since I was using s3fs I went into the "s3fs_file" table and did the same thing.
I went back into the Performance page, enabled the CSS and JS aggregation, and saved.
Then cleared the site cache after that. This seemed to re-generate the
CSS and JS assets, re-built the asset table data, and the site was
back to normal!

I did have to dump the DB tables and import into my dev and local environments in order to mimic the new asset names, but this seemed to work like a charm.

SIDE NOTE: I am wondering if there would be some way for Drupal to add a style versioning system? Maybe that we could change the sites CSS versioning after major changes in order to have this done automatically? or maybe this is just something I will need to build my next module for!!


How does Drupal 7 page/block cache work?

From your question I get that you are trying to set the caching from the performance page admin/config/development/performance.

Cache pages for anonymous users only works for anonymous users, and the page markup is stored in database (to reduce the number of queries). And you can check the HTTP Header X-Drupal-Cache to see if this cache is HIT.

Cache blocks (if Page caching is disabled) works for anonymous and logged-in users. And again, the whole block markup is stored in database for the same reason.

Minimum cache lifetime is the amount of time before the Page cache gets cleared (the cache is cleared on cron run).

Expiration of cached pages works only if page caching is enabled and is only applied to external caching mechanisms (like the browser cache)


How can I set variables only once per block?

You can use static caching in your parse_some_xml function. Some people consider this a cleaner, less evil solution than using global variables (but I will not get into that discussion here).

With static caching, your my_module_block_view() would remain the same, but your parse_some_xml() would look like this:

function parse_some_xml() {
  static $parsed_xml;
  if (!isset($parsed_xml)) {
    // Do the actual parsing here, and store the data in $parsed_xml
  }
  return $parsed_xml;
}

See A Beginners Guide to Caching Data to learn more about static caching.


If you are experiencing it on Chrome only it's a problem with your setup, not Drupal itself. Here you have a bug report about it.

But more probable is that it happens on all browsers, and it's a problem with nginx config - you need to set up client_max_body_size about 35% larger than max file size you want to allow people to upload using Drupal (to have safety margin for Base64 and alike). That way your Drupal will catch "to large" exceptions, and not your nginx.

Note - HTTP does not force body encoding, so 35% margin may well stay unused. But nothing stops applications from doing it, and 35% is what I experienced to be safest bet to avoid future surprises. Hardly any encoding or wrapping wastes as much as Base64 with it's 4/3 overhead. Better safe than sorry and if your server is willing to accept 20MB files, then 27MB will not kill it.


How can I add a filter to an export display?

is there any way to add the same filter for the REST Export display ?

On your regular View page, apply filter for something, and you'll see a URL query gets appended to your URL. For example, when I'm filtering by content type, for mine, I see:
mysite.com/page-view?title=&type=article&status=All&langcode=All (This is based on the view filters I have).
Then all you have to do is append this query to your REST export URL.
mysite.com/rest-export?title=&type=article&status=All&langcode=All (Assuming you have the same filters as your page view, they should've been added by default when you added the REST view).
You'll need to create documentation for this. So people that are using your API know what parameter names & values are accepted.


How to export paragraph bundles with features?

Paragraphs in D8 are entity types. So to create a feature with a paragraph bundle definition, you will need at least:

The paragraph type definition
The Entity form display
The Entity view display
The field instances you use.
Core override fields.
Optionally, you will need the field storage definitions.. but generally it is best to put these in a separate feature like core since fields can be used in multiple places.

The easiest way to get all these is to create a new feature and search for paragraph.[type-machine-name].  E.g. I have a paragraph type named banner, so I created a paragraph_banner feature by searching for paragraph.banner and adding the results.


How to create a rule to automatically assign users to different profile 2 types?

Below is a potential solution for your "... based on the domain name of their email address, I'd like to associate them to different profile types ...").

You might want to try using the Conditional Rules module: use an "if condition" (contained in the Rules Action), and the Rules Action "... to associate them to different profile types ..." would only be executed if the "if condition" would be true. For a sample using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Instead of using Conditional (if/else) logic within the Rules Action, you can also use Switch logic.

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).


Yes, there's a module for that (of course ;) )

Download module:

  This module can compress any files attached to a node and provides a download link. To use this module you have to extract the PclZip library in /sites/all/libraries/pclzip which can be downloaded here: http://www.phpconcept.net/pclzip/pclzip-downloads.


Create a custom module that implements hook_menu().  Use that to create a path and a custom callback function that will run your query.  Something like:

/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['flags/remove/%user'] = array(
    'page callback' => 'MYMODULE_remove_flags',
    'page arguments' => array(2),
    'access callback' => 'MYMODULE_check_access',
    'access arguments' => array(2),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

// Adding custom functions, etc

To get started on creating a custom module, the Module developer's guide


Form is not calling custom submit function

Try next:

function myModule_simple_form($form, &$form_state){
  $form['firstname'] = array(
    '#title' => t('First name'),
    '#type'  => 'textfield',
  );
  $form['lastname'] = array(
    '#title' => t('Last name'),
    '#type'  => 'textfield',
  );

  $form['submit'] = array(
    '#value' => t('Search'),
    '#type'  => 'submit',
  );
  return $form;
}
function myModule_simple_form_submit($form, &$form_state) {
  drupal_set_message($form_state['values']['firstname']);
}

Any rendered drupal form already have a submit function. Also try: drupal_set_message($form); in your hook_from_alter when $form_id = 'myModule_simple_form' too see where is default submit function. You can also add a custom submit funtion in array but it is necesary only if you need more than 1 submit function for your form. In all othre cases use just form_id_submit.


Is there a way to not show some fields of a content type on the add form?

The Field Permissions module sounds exactly like what you're after.

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

  Features

  Enable field permissions on any entity, not just nodes. Role-based
  field permissions allowing different viewing patterned based on what
  access the user has. Author-level permissions allow viewing and
  editing of fields based on who the entity owner is. Permissions for
  each field are not enabled by default. Instead, administrators can
  enable these permissions explicitly for the fields where this feature
  is needed. Field permissions overview

Simply don't give anonymous users permission to add/edit these fields.


In Drupal, you will not find a specific "Real Estate Module". (Well, there is one, but it's a dev version for Drupal 5 and there's only 1 site using it :-)) Drupal modules tend to be more abstract: you take a module for building list pages, add a module for image handling, use a third module for send-to-a-friend functionality, etc. etc. The great thing about Drupal is that 99.9% of the time, you don't have to worry if those modules are compatible with each other. They just build on core concepts such as nodes, fields, menu's and users.

That said, I think you should be able to build a real estate site by combining the modules you need. This way, you will end up with a much more flexible system than a monolithic real estate plugin can ever offer.

I can't be really specific about which modules you need, because I don't know your exact requirements. For the basic functionality you don't even need additional modules; Drupal 7 core allows you to set up a content type (let's call it 'property'), add fields to the property content type (like an image field, price field, address field) and adjust permissions so logged in users (or anonymous, if you want) can create property nodes. Drupal core also includes basic search functionality.

After that, add contributed modules if needed:

Views to create all kinds of lists (plain, with filters, sortable tables, etc.)
Pathauto to create nice search engine optimized URLs
things like Location, Gmap and/or Locationmap (I haven't tried them yet in D7) for maps and geolocations

I recommend that you start building a basic site first and ask more specific questions when you run into them.


Adding extra attributes to webform input element

see this Form API Quickstart Guide http://drupal.org/node/751826 to review how to build forms, know how a form is builded:

  The Drupal Form API provides sophisticated form techniques and also
  allows for almost unlimited possibilities for custom theming,
  validation, and execution of forms. Even better, ANY form (even those
  in core) can be altered in almost any way imaginable--elements can be
  removed, added, and rearranged.

if your javascript is for validate fields of your form, I guess that this answer (related with validations of fields) could be useful How do I create custom content types in drupal?


Hook to get details of taxonomy term page

Taxonomy terms can also be loaded when you're not on a taxonomy page, so arg(2) will be empty, hence empty records.

To fix:

$term = menu_get_object('taxonomy_term', 2);
if ($term) {
  db_insert('reporting_api')
    ->fields(array(
      'tid' => $term->tid,
      'name' => $term->name,
      'vid' => $term->vid,
      'timestamp' => REQUEST_TIME,
    ))
    ->execute();
}


Use hook_menu_alter to change access callbacks

Your code is correct (that's definitely the way to override the access arguments for a path using hook_menu_alter()).

If it's not working you just need to clear your caches (and of course make sure that your custom module is installed and enabled).

I just copied your code into a test site, cleared the caches, and no longer receive 403 errors when visiting that page as an anonymous user.


How to display multiple fields in one line in drupal

As mentioned in the comments, you need to use CSS to achieve this. Drupal makes it really easy by wrapping the elements nicely with divs and relevant classes. For example, if you are creating a new issue in Drupal.org, the form provides http://drupal.org/project/issues/linkedin?categories=All this kind of structure.

Using an inspector tool, you can find the target divs and apply a CSS in this way to your theme:

.views-exposed-form .views-exposed-widget {
    float: left;
    padding: 0.5em 1em 0 0;
}

Thats it. Don't forget to clear your cache to see the changes!


Google analytics module vs direct code insertion in tpl file

It is fine if you want to put the snippet in the page.tpl.php file. You will basically benefit Google Analytics module's conditional-snippet features.

If you put the snippet in page.tpl.php file,

Admin theme will not be tracked (which is usually Seven, which is in core - don't hack core!)
Users cannot opt-put for tracking (See your drupal.org account edit page for an example). this is independent from browser's Do Not Track (DNT) header.
You will find it difficult to track custom variables.
You will find it difficult to track events (downloads, etc). But you can put a modified static snippet and it should work as if it was from Google Analytics module. You can also track messages ($messages) using GA module.
You will need to edit all your page.tpl.php variants to add the code.
Other modules will not be able to control your snippet. Not compatible with js_alters.
You will find it difficult to track internal search.
All users, including admin roles, which is usually not necessary to track.
Cache the code locally.

In my opinion (and some little home-done tests), caching the code locally is not a good idea. GA service is so popular so the chance of having a locally cached version of ga.js is very good. If you cache it, browser will have to download the same code from your server (But you can track users those who have blocked ga.js using AdBlock plugins).

For sites that I maintain in long run, I'm fine to use the snippet directly (in page.tpl.php or html.tpl.php). Many sites don't require A/B testing, goal tracking, custom variables and other bells and whistles. If you explicitly call node_load() , user_load(), user_access(), or other functions, that's a signal that you might want to use GA module instead of the in-house coding.


True/False exposed Views checkbox for Computed Field

Change exposed computed field's filter type to "Grouped filters",
Widget type to "Radios",
Check "Allow multiple selections" checkbox,
Expose one option equal to 1 with your choice of label

See screenshot:

The view export:

<?php

$view = new view();
$view->name = 'computed_field_test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Computed Field Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Computed Field Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['exposed_form']['options']['autosubmit'] = TRUE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: List 1 */
$handler->display->display_options['fields']['field_list_1']['id'] = 'field_list_1';
$handler->display->display_options['fields']['field_list_1']['table'] = 'field_data_field_list_1';
$handler->display->display_options['fields']['field_list_1']['field'] = 'field_list_1';
/* Field: Content: List 2 */
$handler->display->display_options['fields']['field_list_2']['id'] = 'field_list_2';
$handler->display->display_options['fields']['field_list_2']['table'] = 'field_data_field_list_2';
$handler->display->display_options['fields']['field_list_2']['field'] = 'field_list_2';
/* Field: Content: Computed */
$handler->display->display_options['fields']['field_computed']['id'] = 'field_computed';
$handler->display->display_options['fields']['field_computed']['table'] = 'field_data_field_computed';
$handler->display->display_options['fields']['field_computed']['field'] = 'field_computed';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Computed (field_computed) */
$handler->display->display_options['filters']['field_computed_value']['id'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['table'] = 'field_data_field_computed';
$handler->display->display_options['filters']['field_computed_value']['field'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['expose']['operator_id'] = 'field_computed_value_op';
$handler->display->display_options['filters']['field_computed_value']['expose']['label'] = 'Computed (field_computed)';
$handler->display->display_options['filters']['field_computed_value']['expose']['operator'] = 'field_computed_value_op';
$handler->display->display_options['filters']['field_computed_value']['expose']['identifier'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['expose']['multiple'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['is_grouped'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['identifier'] = 'field_computed_value';
$handler->display->display_options['filters']['field_computed_value']['group_info']['optional'] = FALSE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['widget'] = 'radios';
$handler->display->display_options['filters']['field_computed_value']['group_info']['multiple'] = TRUE;
$handler->display->display_options['filters']['field_computed_value']['group_info']['group_items'] = array(
  1 => array(
    'title' => 'Find all users where the Computed Field value is 1',
    'operator' => '=',
    'value' => array(
      'value' => '1',
      'min' => '',
      'max' => '',
    ),
  ),
  2 => array(
    'title' => '',
    'operator' => '=',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
  ),
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'computed-field-test';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'Computed Field Test';
$handler->display->display_options['menu']['name'] = 'devel';


When creating a view based on order products in ubercart, only people with access to all orders can see it

In the view's advanced settings, go to 'SQL Settings', and check 'Disable SQL rewriting'.

Drupal modules can hook in to SQL queries and alter them before they are executed. The Ubercart module automatically adds a permission check to queries that touch the Order table, to implement the 'view own orders' permission. Individual views can opt out of this rewriting mechanism, but that will prevent any module from altering the query. Be sure to thoroughly test that the view does not leak any sensitive information.


I'm not sure what you mean by moving something off of your local, but I really think your best bet is to use git and push the patch up, even if you don't have a local environment set up. You don't need a local server or database running, you're just altering code in the repo.

clone Pantheon dev environment locally
patch -p1 < name_of.patch
commit and push

You could edit the files manually using the SFTP mode, but I wouldn't recommend that.

Using Git with Pantheon


Ubercart email notification to store owner when order submitted

You can use "Conditional Actions" to achieve this.

Its available under Store Administration / Conditional Actions.
I believe there is a preconfigured conditional action for your request in Ubercart. Maybe you just need to enable it.

If not just create your own.


I would check /sites/default/settings.php and look into your $cookie_domain = setting - does it match your domain?


What's the right way to have a contextual link on controller action?

I did this using a reference from below.

Adding the contextual link render element

I added a variable to the theme, and passed contextual link in controller function to twig template using that variable. Please see code below.

File : mymodule.module

function mymodule_theme() {
  return [
    'mymodule' => [
      'template' => 'mymodule',
      'variables' => [              //Added a variable content
        'content' => '',
      ]
    ],
  ];
}

File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure My Module'
  route_name: 'mymodule.route_name'
  group: 'mymodule'

File : IndexController.php

public function index() {
    $data['content'] = [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: index'),
    ];

    $data['#contextual_links'] = [
        'mymodule' => [
            'route_parameters' => [],
        ],
    ];

    return [
        '#theme' => 'mymodule',
        '#content' => $data,        //Pass Contextual link to the variable
    ];
}

File : mymodule.html.twig

{%
set classes = [
'contextual-region'
]
%}

<div {{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}                     //Render here
</div>

--

Thanks


Block that shows nodes based on node type

There's currently 12,966 sites using the beta3 release of Views 7 (http://drupal.org/project/usage/views). I'd suggest that you install the module and try to produce what you're describing as I suspect it will work fine. A beta3 release suggests that the module is nearing a production release with no new functionality being added.

Be brave, adopt the new software rather than painting yourself in a corner by writing your own custom code.


Strange behavior while assigning the role programmatically

This is the roles element in $user object ( $user->roles )

roles => array(
  2 => "authenticated user",
  4 => "Site Administrator",
  6 => "Author",
),

You must set the user role like:

$user->roles[ROLE_ID] = 'ROLE_NAME'


Drupal database not found after running update.php

"No route to host" looks like something related to DNS. If you're not, try using an IP for your database server in settings.php

If it's localhost, use 127.0.0.1


Without using any hook, it's not possible, since to change the class used for an entity, it's necessary to implement hook_entity_type_alter(), which is problematic to implement when more modules need to alter the entity definition, for example changing the same entity handler, or the entity class, for the same entity type.
Imagine two different modules that try to add two different fields to the User entity by replacing the entity class used for it. For example, the first module could use the following code.
/**
 * Implements hook_entity_type_alter().
 */
function login_id_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setClass(LoginIdUser::class);
}

namespace Drupal\login_id\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\Entity\User;

class LoginIdUser extends User {

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = parent::baseFieldDefinitions();

    $fields['login_id'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Login ID'))
      ->setDescription(t('The ID used for the login credentials.'))
      ->setRequired(TRUE)
      ->setConstraints([
        'LoginId' => [],
        'LoginIdUnique' => [],
    ]);

    $fields['name']->getItemDefinition()
      ->setClass('\\Drupal\\login_id\\LoginIdItem');

    return $fields;
  }

}

The second module could use the following code.
/**
 * Implements hook_entity_type_alter().
 */
function admin_email_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setClass(AdminEmailUser::class);
}

namespace Drupal\admin_email\Entity;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\Entity\User;

class AdminEmailUser extends User {

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = parent::baseFieldDefinitions();

    $fields['admin_mail'] = BaseFieldDefinition::create('email')
      ->setLabel(t('Admin email'))
      ->setDescription(t('The email used from administrator users to contact the user.'))
      ->setDefaultValue('')
      ->addConstraint('UserMailUnique')
      ->addConstraint('UserMailRequired')
      ->addConstraint('ProtectedUserField');

    return $fields;
  }

}

With two modules implementing that code, only a field would be added to the entity. To get both the entity fields, LoginIdUser should extend AdminEmailUser, which would mean that a module should have the other one as dependency.
This assumes that admin_email_entity_type_alter() is executed before login_id_entity_type_alter(). This is what normally happens when the hook execution order isn't altered by a hook_module_implements_alter() implementation, or when the weight associated to module isn't altered by a call to module_set_weight(). In the case login_id_entity_type_alter() is invoked before admin_email_entity_type_alter(), for example because a module implements hook_module_implements_alter() and changes the order of those hook implementations, AdminEmailUser should extend LoginIdUser.
Implementing hook_entity_base_field_info() allows to modules to add different fields without interfering with each other.
As side note, hooks can be placed in a file different from a .module file, which is automatically loaded from Drupal. Which files are loaded from Drupal when looking for hooks is influenced by hook_hook_info(). With the implementations of that hook done from Drupal core modules, the files Drupal core looks for are the following.

<module_name>.tokens.inc
<module_name>.views.inc

If you are interested in reducing the size of the .module file, implementing hook_hook_info() to tell Drupal where your module hooks are could be a way to achieve it.


Updating computed field's value without needing to clear cache

Check out the rules module (http://drupal.org/project/rules):

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules).

You could add a rule to clear the cache whenever a new nodes has been added.

It's not exactly the way you asked for, but it gets the job done - updating the computed field's value whenever a new node has been created.


How can I add the sku code in [commerce-order:commerce-email-order-items]

Some tokens are generated by code others by views. This token is generated by code

So edit commerce_email.module and around line 420 you will see commerce_email_order_items function here you can add the sku.

Take in mind that this is not an ideal solution See hook_tokens_alter


How can you gitignore items in a Drupal project without modifying core?

While .gitignore, .htaccess and robots.txt will come as part of the package when you clone Drupal, they should not be considered part of core and you should not feel that they cannot be changed or replaced with your own files.

This is what I do: Prior to updating (drush up), I make a backup of those three files.  After updating, I use the CLI program diff to compare the newly updated version with my backup (typically, my .gitignore have more entries at the end than those that come with Drupal).  If nothing else has changed, I just overwrite the one that came with Drupal with the backup.  If diff shows that the "drupal part" of .gitignore has changed, I copy those changes into my backup version before overwriting.  (Same procedure with .htaccess and robots.txt.)


Absolutely, it's quite straightforward.

You'll need a path for the page:

function MYMODULE_menu() {
  $items['admin/foo/bar'] = [
    'title' => 'Foo',
    'page callback' => 'MYMODULE_admin_page_callback',
    'access arguments' => ['whatever makes sense'],
  ];

  return $items;
}

A theme declaration:

function MYMODULE_theme() {
  return [
    'funky_admin_page_content' => [
      'variables' => [],
    ],
  ];
}

Your function to build/get the content. Note that you could also put this in a template file, see hook_theme() for more details.

function theme_funky_admin_page_content() {
  // Build your HTML, return it as a string.
}

And your page callback:

function MYMODULE_admin_page_callback() {
  return [
    '#theme' => 'funky_admin_page_content',
  ];
}


How to generate a List of Dates with Start/End sorted by Month in Drupal7?

You will have to use Views and Group by Month then by Day.

http://www.jeremyfrench.co.uk/node/1461


Can't get jQuery UI autocomplete working

Adding drupal behaviours, as suggested by @2pha, did the trick:

(function ($) {
    Drupal.behaviors.infiniteScrollAddClass = {
        attach: function (context, settings) {

            $( "#business_category" ).autocomplete({
                source: [ "cat1", "cat2", "cat3" ]
            });
        }
    }

})(jQuery);


drupal_mail to users selected from database

On a first glance, it's because you are passing the whole object instead of the email address. Try this:

  $sql = db_select('users', 'u');
  $sql-> fields('u', array('mail'));
  $sql-> condition('uid', $value['uid']);
  $mail = $sql->execute();
}
foreach($mail as $m){
  dsm($m);
  drupal_mail('event_manager','event_approved', $m->mail, language_default());
}


Sharing the same templates by importing PHP files: Where should I store those PHP files?

Your question states "I feel like a module is an overkill", but (according to your own comment) the Domain ThemeKey module works perfectly for your use-case along with importing php files.
Some details about this module (from its project page):

Integration of Domain Access and ThemeKey.
Module provides additional ThemeKey properties:

domain:site_name - returns current domain's site name
domain:id - returns current domain's id
domain:machine_name - returns current domain's machine name
domain:is_default - returns true if current domain configured as default domain
domain:is_alias - returns true if system:host is an alias for current domain


download the font & css files, don't use a cdn
minify and concat your css, additionally you can use sass & gulp to
do the job for you


How to move my site files outside the Drupal folder on local computer?

Yes you can separate files folder out of Drupal core installation.
Follow these steps:

Go to admin/config/media/file-system
See public file system path, this needs to be relative to drupal installation. So if I want to make the files folder in parent folder of Drupal core installation, I need to give path like ../test_files
Go to admin/config/development/performance
Clear cache and if you have aggregated css and Js, disable them, clear cache and again enable them.

This works


I managed to get this working by using the following settings for the Content: Comment count field:

Format plural checked
Singular form: @count comment
Plural form: @count comments

Under No results behavior:

No result text: no comments yet
Count the number 0 as empty checked
Hide if empty  checked
Hide rewriting if empty checked


How to properly alter the output for fields of type file?

I'm guessing a bit here as I can't see what you have installed/configured...

The file formatter function is file_field_formatter_view(), and the only formatter which has an image attached to it runs through theme_file_link(). I would assume that's where the markup you're referring to comes from.

You can override that in your theme:

function MYTHEME_file_link($vars) {
  ...
}

Or, if you can get away without having to reproduce the function, just preprocess is:

function MYTHEME_preprocess_file_link(&$vars){
  ...
}


How to redirect programatically using a route with parameters?

As pointed out by @4k4, the problem is that the module did not ask for the route parameters, so I patched it.

Then you can call the redirect like this:

  if (!($account->hasRole('admin'))) {
    $routename = $test->getRouteName();
    $routeparameters= $test->getRouteParameters();
  }


Using Rules to block system email or prevent from sending?

Maybe a custom module and lines in the setting.php?

Here is a simple tutorial showing how $message['send'] = FALSE; can stop it. Of course, you can also use if statments to add conditions.

Note: The developer does mention that you shouldn't use it on production...


Add CKEditor widget (footnotes) from external addon

It turns out you need to call editor.ui.addButton() to get the buttons to show.

It seems to me that it is not usually needed in vanilla CKEditor development, because it is not included neither in the tutorials nor in the ckeditorfootnotes plugin. However, most of the current Drupal 8 CKEditor modules do include it in the plugin source.

For the simplebox plugin it would read like this, here command is the name of the defined widget.

editor.ui.addButton('SimpleBox', {
    label: Drupal.t('SimpleBox'),
    command: 'simplebox',
    icon: this.path + 'icons/simplebox.png'
});


If you've ever used CCK in D6, the Field UI will be rather intuitive. And unless you need to do very custom work, you won't need the Field API at all, just the Field UI.

But if you do need custom widgets or formatters, take a look at the Examples module for some very comprehensive usage of the Field API.


In general, this is pretty hard to answer without going into details and knowing what you did with your site. But to give you a few starting points...

To ask the obvious, you are testing this as an anonymous user without a session, right?
If you do have a session, check what values you have in there and who sets them
One thing to grep for is \Drupal::service('page_cache_kill_switch')->trigger();, although it could also be injected, so just look for ->trigger(). That's the equivalent of drupal_page_is_cacheable(FALSE) although are other ways to plug into that too.
Typical modules that set this are captcha or poll
If all else fails, look at FinishResponseSubscriber, that's the one that  adds those headers, specifically look at the request policies that return if a page is cacheable or not (the kill switch is one of those, as is the check for a session)


Hard to confirm why yours are not showing. If I am comparing like with like then I have built some Views and used Search API to give the custom data in the View columns and to provide blocks showing the count for each of the sub-types of that custom data.

Thing is there is so many steps involved I don't really know how to provide a clear recipe for you to follow assuming of course that would be better thank Mark's since I know I used that as part of my own journey on this.


How to change active link css class (is-active)

You can override the theme_menu_link function like this:

function theme_menu_link($variables)
{
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = \Drupal::service('renderer')->renderRoot($element['#below']);
  }

  foreach ($element['#attributes']['class'] as &$class) {
    if ($class == 'is-active') {
      $class = 'active';
      break;
    }
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);

  return '<li' . new Attribute($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}


How to Add Multiple Values to Prefix for Currency field as a Drop Down

Found the Solution in this post. Used the Measured Value Field in Conjunction with Units and Currency. Got a pretty neat solution.


Create a view with checkboxes per role, that generates an email to an admin

There is Views Send module, you may try this.

Views Send enables you to send mass mailing from a View.

This module support tokens and Global: Send E-mail with VBO.


In your hook_node_info, 'base' should not be node. It has to be something else and generally your module name is advised.

Explanation from the node_example.module

// 'base' tells Drupal the base string for hook functions.
// This is often the module name; if base is set to 'mymodule',
// Drupal would call mymodule_insert() or similar for node
// hooks. In our case, the base is 'node_example'.


Turns out the solution was to Disable Panels

or you could add the comment form to the Panel.


What is the value of $page['content'] in custom front page?

$page[content] returns the content for the current page, whatever that may be.  If a view is set at the content, it would return the view, or a node, or a block in the content region or anything else set to show in that region, either through the UI or programmatically. It returns rendered html for all elements in that region.

Chances are under blocks, that view? is no longer listed to render in the main content region as a result of whatever setting changes you made.

If it's a view and set as a block you can modify it under the blocks page, block configuration to show in the region.


Trying to get a field from a fetched entity in rules

Correct way to get the value is:

<?php print_r($entity_fetched->field_date_time['und']['0']['value']); ?>

The $entity_fetched is returning an object so to access it values you would need to use -> operator, and than you have array contents which you can access using the array subscript operator [].

Note: You cannot access object members via the array subscript operator [].
For accessing the object members you need to use the -> operator.
And to access the array contents we use the [] operator.


defining node multicolumn layout with twig template

Make a copy of node.html.twig and rename the copy to node--[content-type-name].html.twig which goes inside your theme's template folder.

Then in node--[content-type-name].html.twig find and delete {{ content }} and instead in there you put

{{ content.title }}
{{ content.body }}
{{ content.field_name }}

This is how you can render your fields individually.

Then, you can wrap them inside an id or class divs. Ex:

{{ content.field_name }}

{{ content.field_name_other }}


How do I render my date field using my custom date format?

In the node template you should be able to output your dates with your selected format by doing:

print render($content['field_date']);
print render($content['field_end_datetime']);


Use Views to display unpublished nodes to authors, but not to other users

Just to save anyone else some time and trouble, there's a filter under Views called, "Content: Published or admin." This will do precisely what is needed.


Tabs for Media:youtube multiple videos of single node

Maybe you use could use the Field Collection Tab formatter module with Field collection?

Here are some more details about these modules (quotes included are from their project pages):

Field Collection Tab formatter:

  ... provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.

Field collection:

  ... Provides a field-collection field, to which any number of fields can be attached. A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


How to save the webform data to custom table?

You can add custom submit handler to your Webform through hook_form_alter for inserting it's data into your custom table.

To achieve it check the below example.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;

function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
  if($form['#form_id'] == "YOUR_WEBFORM"){
    $form['actions']['submit']['#submit'][] = 'YOUR_CUSTOM_FUNCTION';
  }
}

function YOUR_CUSTOM_FUNCTION(&$form, $form_state){
  $query = Database::getConnection();
  $query->insert('YOUR_CUSTOM_TABLE_NAME')->fields(
    array(
      'FIELD_NAME_IN_TABLE' => $form_state->getValue('FIELD_NAME_IN_FORM'),
    )
  )->execute();
}


The problem is that you are adding your argument as an array, so your __construct() method receives an array. So this:

$definition->setClass('Drupal\my_module\MyModuleMessageNotifier')->addArgument([
  new Reference('logger.channel.message_notify')
]);

Should be this:

$definition->setClass('Drupal\my_module\MyModuleMessageNotifier')
  ->addArgument(new Reference('logger.channel.message_notify'));

(notice that the Reference is not wrapped in an array.


Query returns 0 rows on JQGrid filter due to translated rows

Ok. I've solved this in what I believe is a reasonable way but it won't really scale:

As I build up the data for the table and translate each cell, I store that into an array with the foreign language string as the key and the untranslated string as the value. (This could work either way round).

$strings[t($my_string)] = $my_string;

I save that array after I've done everything with the last snippet. This array is read at the beginning of loading the table data:

$strings = $saved_strings = variable_get('my_translated_strings_' . $language->language, array());

If the array has changed then I will save it:

if ($strings != $saved_strings) {
  variable_set('my_translated_strings_' . $language->language, $strings);
}

I can then manipulate the filter rules to filter on the original untranslated strings instead of the user's language.


The code to get the entity language is present in language_form_alter(), which you can take as an example to write your code.

  $form_object = $form_state->getFormObject();
  if ($form_object instanceof ContentEntityFormInterface && $form_object->getEntity()->getEntityType()->hasKey('langcode')) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_object->getEntity();
    $entity_type = $entity->getEntityType();
    $langcode_key = $entity_type->getKey('langcode');

    // Your code goes here.

  }

If you are sure the edit form is for a content entity (such as a node), you could remove the part verifying that $form_object is a content entity object. I would leave it, but that is my personal preference.


Remote database

To use a remote database, you just have to supply the IP/URL of your remote server instead of 'localhost' during install or in sites/default/settings.php file.

SQL Server

There's a module for SQL Server : Drupal 7 driver for SQL Server and SQL Azure.

And installation instructions are available on the module page.


I found a way but I'm not sure if it's ideal:

function THEME_preprocess_html(&$variables) {
  $variables['head_title']['title'] = 'title here';
}

Logic can be added for each page:

$path = $current_path = \Drupal::service('path.current')->getPath();
if ($path === '...')

Then, in html.html.twig:

<title>{{ head_title.title }}</title>

instead of

<title>{{ head_title|safe_join(' | ') }}</title>


How to remove contents type drupal advanced search page

Advanced Search field can be disabled in Permissions settings (it should be disabled by default).

If you rather want to leave Advanced Search, but limit to specific content types, you can 1) Use Custom Search module, as advised by @Lance or 2) Dig through modules\search\*.* directory to see which function controls the content type of the Advanced Search options, after which you can use your own module to override the settings.


If by "Last Updated" you are only talking about nodes, then yes, you can.

Create a new view for content (using views module), add a block display, do not filter by any content type, but I think that you can keep the "Published" status. Sort by updated time, descendant, set the pager to show only 1 node. And set the display to only show the updated time. That's all.


How to use websolr with Apache Solr module? (D7)

Apache Solr presents a generic API, and you should be able to use any search module which uses Solr with Websolr. We tend to recommend the Apache Solr Search Integration module.


Display comments according to the users roles

You are almost there. You just have to have new display
for each role. See below.

Set the path as below, per role per display:

It will appear as below in node page:


DBTNG Migrate: SQLite -> PostgreSQL fails because of custom fields

To answer my own question:

The migration should be run on an empty database. This way, everything gets replicated successfully.


How do I alter the output of a field using a views handler

You add your custom views handler using hook_views_data() like so:

function mymodule_views_data() {
  $data = array(
    ['my_table_name'] => array(
      'my_field_alias' => array(
        'real field' => 'my_field_id',
        'group' => t('Testing'),
        'title' => t('Testing'),
        'help' => t('Testing a thing.'),
        'field' => array(
          'handler' => 'my_custom_views_handler_test',
          'click sortable' => TRUE,
        ),
        'sort' => array(
          'handler' => 'views_handler_sort',
        ),
        'filter' => array(
          'handler' => 'views_handler_filter_string',
        ),
        'argument' => array(
          'handler' => 'views_handler_argument_string',
        ),
      ),
    ),
  );

return $data;
}

And then you declare your custom views handler:

class my_custom_views_handler_test extends views_handler_field {
  /**
   * Render some stuff.
   *
   * Data should be made XSS safe prior to calling this function.
   */
  function render($values) {
    $value = $this->get_value($values);
    return $this->sanitize_value($value);
  }
}

Almost all changes you'll be wanting to make should be made in an override of the render function.