Rewrite SQL on a specific content type node on Drupal 7

While the question is vague as to your purpose, you may be interested in

hook_query_alter
hook_query_TAG_alter

to alter queries in Drupal 7.


Server 500 error in a View which is working perfectly outside of the admin area

You are going to have to access the PHP error log file to determine the cause. Drupal may not always log an error since it the error may stop it from running. I would contact your host to see if they can provide you the log.


Edit admin email template for new user registrations

If you look into logintoboggan.module you would see that this message is hard-coded and appended using the hook_mail_alter function and that it's altering the  Welcome (awaiting approval) (user_register_pending_approval_admin) located in admin/config/people/accounts. So if you like to append the data in the middle, you can edit the said email body in the admin page but if you also like to alter the message by logintoboggan then you need to implement hook_mail_alter also.


You can either implement hook_ckeditor_css_alter or you can add ckeditor_stylesheets to your themes info.yml file.

See: hook_ckeditor_css_alter for more.

Example:

function mymodule_ckeditor_css_alter(array &$css, Editor $editor) {
  $css[] = drupal_get_path('theme', 'mytheme') . '/css/mymodule-ckeditor.css';
}

Or in mytheme.info.yml:

ckeditor_stylesheets:
  - css/styles.css


This is not the original image, it is a derivative generated by image styles. Fortunately it is a quick change to tell the field what to use.

Simply go into the display settings for the node or entity outputting the image, and change the field formatter from the image style setting to just "Original Image". The same option exists in Views if you are outputting the field.


You shouldn’t render field values like that. You should be doing it as {{ content }} or {{ content.field_name }}.


This is what you are looking for:

http://jimbir.ch/blog/changing-order-drupal-7-media-module-file-browser-tabs

I just tried and it works perfect:

  Blockquote

  Here is the original order of the file browser:

  In order to change the order and hook into this function, I created a simple custom module, mediamenu.  In this module, I will be able to hook into the media module using the hook Brandon showed me, and change the weight of the tabs, re-ordering them. The module has a folder named mediamenu, and inside two files, named mediamenu.info and mediamenu.module.  You can view and download these files from this github repo.
  mediamenu.info

  The .info file contains information about the module, name, description, version, which version of Drupal, and where to group it on the modules page.

name = Media Menu
description = This module organizes the tabs on the Media browser.
version = "7.x-1.0"
core = "7.x"
package = Media

  mediamenu.module

  In the .module file, we hook in and change the weights of the tabs, which will re-order them, the heaviest weight/lowest number first.

  The first two items here are provided by the Media module, and the Media Browser view (Machine name: media_default).  The two tabs are made by the two displays of the view,  media_browser_1 and
  media_browser_my_files.  The media_internet tab is provided by the module of the same name.  Upload is provided by the media module.

< ?php
/**
 * Change Order of Media Browser Tabs
 *
 * Implements hook_media_browser_plugin_info_alter().
 */
function mediamenu_media_browser_plugin_info_alter(&$info) {
  $info['media_default--media_browser_1']['weight'] = '-10';
  $info['media_default--media_browser_my_files']['weight'] = '-9';
  $info['media_internet']['weight'] = '-8';
  $info['upload']['weight'] = '-7';
}

  You may have additional tabs provided by other modules. You can find their machine name but looking at the source markup of the page, and looking for the data-tabid of the tab.


Instead of date() you should use format_date() instead per Drupal.

https://api.drupal.org/api/drupal/includes%21common.inc/function/format_date/7.x

format_date takes various settings and user config into account when formatting the date, whereas just date is a php function, and thus, will not. You can also pass it a custom date format name.

While you can use format_date() at the template level, usually it is best to do it in a preprocess function and pass it along to the template. If you have a module that is supplying variables to a template, supply them upfront.

Variables should be print-ready for the user, with the option of overriding later (extending or preprocessing at the theme level, etc).


The raw SQL would be something like this,

SELECT startDate, endDate
FROM YourTable
WHERE GETDATE() between startDate and endDate;

You might could do like this with db_select

$query = db_select('node', 'n');
$query->condition(now(), array(node__field_start_date, node__field_end_date), 'BETWEEN');

I hope it helps


Adwords conversion tracking on Ubercart store with payment gateway?

You have to make users come back to your site adding this query string in the URL:

?utm_nooverride=1

Then Google will discard referral modification caused by leaving the site.

See this question.

You will have to deal with your payment gateway to modify the return URL, I think.


Replacing an object of the UserLoginForm class with one of my own class

As I said in the question, the problem was that UserController::userPage() expressly created an object of the class UserLoginForm. The method has been changed, and now it contains the following code, which doesn't contain any explicit reference to that class.

public function userPage() {
  return $this->redirect('entity.user.canonical', array('user' => $this->currentUser()->id()));
}

Using a route subscriber that extends RouteSubscriberBase is possible to change the form associated with a route.

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class MymoduleRouteSubscriber extends RouteSubscriberBase {
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\mymodule\Form\MyModuleLoginForm');
    }
  }
}


Using .tpl.php templates instead of Twig templates

You don't need to write PHP in twig files. Twig is fairly expressive to the degree in which you need to template, for everything else, it should go into the .theme file, theme hook, and/or preprocess function.

There is virtually no reason to have PHP code in a template.

Spend a week with Twig and you won't go back.

Example:

<?php if ($page['content']): ?>
  <?php print render($page['content']); ?>
<?php endif; ?>

vs:

{% if page.content %}
  {{ page.content }}
{% endif %}

Much more readable.

I'll expand with a more advanced example.

Lets say you have list of things you want to output, but every 7 items, you want to make a new unordered list. The end goal is the CSS inlines these lists, think of a superfish menu where menu links are ordered top to bottom, then left to right.

    {% for chunk in items|batch(7) %}

        {% for item in chunk %}

            {{ link(item.title, item.url) }}

        {% endfor %}

    {% endfor %}

Where items is passed to the template. This small example will output a UL with 7 items until there is nothing left to print.

I have yet to run into an instance where I cannot accomplish something with Twig, or, because it's Twig.

Give it a shot and dive in, forget phptemplate.


Below codes work for two submit buttons given at webform for identify which button is click.

function modulename_form_submit(&$form, FormStateInterface $form_state) {

  $myurl = FALSE;
  $triggerElement = $form_state->getTriggeringElement();

  if (isset($triggerElement['#id']) && $triggerElement['#id'] == 'COMPARE BUTTON ID') {
    $myurl = Url::fromUri('internal:/SETYOURFIRSTACTIONPATH');
  }

  if (isset($triggerElement['#id']) && $triggerElement['#id'] == 'COMPARE ANOTHER BUTTON ID') {
    $myurl = Url::fromUri('internal:SETYOURSECONDACTIONPATH');
  }

  if ($myurl) {
    $form_state->setRedirectUrl($myurl);
  }
}


This could be caused by a bug in Drupal 7: Inaccessible menu items in navigation links cause "Notice: Undefined index: localized_options". There is a patch available which has worked for some people.


Modifying my theme's template.php requires apache restart to see changes

Thanks to Clive and MPD, that pointed to the answer.

It was because of APC.

I've installed the module apc_admin, which allows to access the APC interface (apc.php) from within drupal (Configuration » Development » Performance » APC).  That includes the "Reset APC cache" button. Just by pressing it, the changes in my template will show up.

Hope this helps also other users.


Per hook_views_data_alter, I came up with code along the lines of the following which seems to work for my example in the question:

$data['field_data_FIELDNAME']['dummy_name'] = array(
  'title' => t('Map field to other db column'),
  'group' => t('Custom mapping'),
  'relationship' => array(
    'base' => 'node_revision',
    'base field' => 'vid',
    'field' => 'FIELDNAME_value',
    'handler' => 'views_handler_relationship',
    'label' => t('Map field to db column'),
    'title' => t('Field to db map'),
  ),
);


Internal Server Error with Multiple Tags

SK , When you choose tag field in sort criteria, you will get two options Dropdown and Autocomplete. Choose Dropdown . This should fix your problem.


I would recommend against including this functionality on your site. Re-sizing text is best handled by browsers and assistive technology. Check out this discussion: https://groups.drupal.org/node/85254

The key thing is to use relative CSS units (em and %) when defining font-sizes and typography-related dimensions in your theme.


Naming conventions in Media entity vs File entity

After a bit of reading around, it seems that the core Media module was never adapted/updated from the File Entity module; it was a port of the Media Entity module (which didn't have its origins in File Entity either). See Bring Media entity module to core as Media module for the full details.

The "file" media type did have its origins in a plugin named "Document", provided by the Media entity document module, which provided the same basic functionality as File Entity's "document". So there may have been some crossover in their evolutions somewhere along the line.

But even so, reading through the proposal to Add "File" MediaSource plugin, it becomes clear that there was no intention to port the "document" type over in its previous form, rather just to use it as a starting point for the generic file type. From comment 24 on that issue, in response to a previous query of I'm wondering whether file should be document instead? File seems really generic as image is also a file:

  26-1: As commented with @dawehner on the sprint, the idea is that the Image handler extends this plugin, so this name is probably the most appropriate in this case. A "Document" plugin can be created also extending "File", if needed to expose specific UI improvements for documents.


Try view_unpublished module and check can you see unpublished nodes.

  Description: This module allows you to grant access for specific user
  roles to view unpublished nodes of a specific type. Access control is
  quite granular in this regard.

  Additionally, using this module does not require any modifications to
  your existing URL structure.


I've done this for Drupal 6.

In Views 2, I've had to define where in the URL the parameter(s) would be located positionally (e.g. blah/view_name/%/%) where the % represent parameters 1 and 2 respectively; then, in my next view (which was either another display or attached view within the same view file) I defined the arguments in the argument section and then they could be referenced as %1, or %2 respectively.


Unable to post message to wall on facebook using facebook rules module

The problem lies with proper permission.
You need to have permission "publish_actions" to post on someone's behalf. If you do need more permissions then follow the below link to get all the permissions provided via Facebook Graph API.

https://developers.facebook.com/docs/facebook-login/permissions/v2.0#reference-extended


Views: List of recent months containing nodes

You can create path alias to make the URL look how you want, but views need the year and month as a single argument.


Something like the following could help you.

Just Set $filepath  and $filename with your desired values.

$filepath = "/path/to/my/image/chart.png";
$filename = "chart.png";

$response = new Response();
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', 'image/png');
$response->setContent(file_get_contents($filepath));

return $response;


Any way to add something similar to Olark or Zopim

I don't know of a free Drupal service to do this.
Olark has a Drupal guide to get it working on your site. There is also the Olark Chat module. I know that VPS.NET and Lullabot are both using Olark.


Date Range filtering using Google Search Appliance crashing

So the drupal module uses curl to query the google search appliance, which means if your url is too long, you may run into issues.

It would be better to send a range to the Google search appliance by altering the $query['gsa_query_params'], ether by using the required-fields or partial-fields.

However, google doesn't currently support ranges to be sent via these options. Hopefully they'll add that functionality, but if you can't wait indefinitely for them to add the functionality, you can get a bit hacky and get it to work.

So, the Google Search Appliance has a flag, "inmeta" which does allow you to create a integer range. The catch here is it can only be used in a query field. IE a search for

  "John Doe AND inmeta:1901-1940"

What you could do though is use the GSA Drupal module.

hook_google_appliance_query_alter (where your altering your queries to create your other filters) to add to your q string "AND inmeta:[range]". The issue here is that when you use this, drupal will display the full q string, with the inmeta field showing. Which might look strange for your users. You could save a copy of the q string before adding the range to your $query variable. Then, before displaying the page, but after the query has been executed, switch the query string back out.


Views Bulk Operations Modify entity values on one form

Try creating a custom action in Rules that sets the entity value to the one you want rather than prompting for the value.  Then activate that action in your VBO view.

You can make new rules components at mysite/admin/config/workflow/rules/components/add


How to get field value from referenced entity inside a field collection

Based on what I read in the computed_field documentation, you have two options when creating the necessary code to compute the field. You could create the PHP into the text area of the field (I really dislike PHP in the database...but that's just me) or you can create a custom module with a specific function in it. Per the documentation:

Drupal 7

To use a function in a custom module instead of writing the code in text area create a function that looks like:

<?php
function computed_field_YOUR_FIELD_MACHINE_NAME_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $entity_field[0]['value'] = 'value';
}
?>
Parameters:

&$entity_field - The computed field. Used to store the computed value.
$entity_type - The entity type: node, user, comment, etc.
$entity - The actual entity (a node, user, comment, etc.)
$field - General field settings.
$instance - Field instance settings.
$items - The list of items.
Note:
Make sure $entity_field is passed by reference.

What is awesome about this method is we have the entity available to us via $entity (in your case, it would be an entity of type field_collection). From this approach, I would:

Create a custom module with this function
I would then create logic around calling the $entity variable, loading the entity (if required) and then getting it's entity reference, which will probably require another entity load.
Do compute field logic that you'd like.

Once this is done, you can use the same custom module to write another computer_field_YOURFIELD_compute() function for your initial field (on the node) that computes the combination for all field_collection computed field values.


Webform: how to display warning message, when clicking upload, and no file is chosen?

You could use the client side validaiton module install it then configure it for webforms , you could also use the module's hooks to customise error messages or create custom error handling functions  client side validation


When using a dev version of a module, how can I easily get a notification of the next stable release?

Some of your question seems a little ambiguous to me, but it might be answered here: drush: How to upgrade to a stable module release instead of dev?


How to have a field displayed depending on user's role in Views?

If this is a custom entity you may consider overriding the checkFieldAccess method of Drupal\Core\Entity\EntityAccessControlHandler.

Then assign your own handler as handlers/access in @ContentEntityType.

But it's only me who prefers being in coding hell instead of configuration hell :-)


how to make a field in a view be the link destination to another field?

Make sure the Row Style is Fields. Add both fields, link field first and then image field.

Edit the link field (in the Views UI) and check exclude from display and use the URL as plain text formatter.

Finally, edit the image field and check output this field as a link. There are replacement patterns you can use for the link destination, the link field should be available there. You will need to check use absolute path.


Autofill billing Information on checkout page in Drupal Commerce

This code works for me.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  if ($form_id == 'commerce_checkout_form_checkout' && $user->uid) {
    $user = user_load($user->uid);
    $loaded_billing = commerce_customer_profile_load($user->field_commerce['und'][0]['profile_id']);

    // For each field in customer profile, fill the form field with the $user value.
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address'] = $loaded_billing->commerce_customer_address['und'][0];
    $form['customer_profile_billing']['field_telephone_number']['und'][0]['value']['#default_value'] = $loaded_billing->field_telephone_number['und'][0]['value'];
  }
}

I tried to retrieve the commerce_customer_profile field list, but I didn't find a way to generalize an action for filling every field type in the form.


Additional parameters to aliased panels paths

I have a similar problem on a Drupal 7 site, and am posting as much to share my solution as to "subscribe" and hear from others about the potential pitfalls or alternative solutions.

In my case, I have a number of panels that display "related" content to a node.

Let's say that it's an artist node, and that I have a few panels or variants representing the

artist (url artist/[artist-nid])
their albums (albums/[artist-nid])
their band history (history/[artist-nid]).

For SEF urls, I want to alias those to something like

artist-name-profile
artist-name-albums
artist-name-band-history

Because pathauto doesn't "see" the panels, and because the urls are of an unusual structure (no '/' ) I wrote a custom module to do url rewriting using hook_url_inbound_alter() and hook_url_outbound_alter().

For Drupal 6 you can use http://drupal.org/project/url_alter It's baked into Drupal 7.

So basically, I maintain a cck field on the artist node containing a url friendly version of the artist name. Then use code something like the following.

function myModule_url_outbound_alter(&$path, &$options, $original_path) {
  $parts = explode('/', strtolower($original_path));
  $prefix = array_shift($parts);

  switch($prefix) {
    case 'albums':
      if (!empty($parts[0]) && is_numeric($parts[1])) {
        $url_fragment = myModule_get_unique_url_safe_artist_name($parts[1]);
        $path = $url_fragment.'-albums';
      }
      break;
    // etc
  }
}

function myModule_url_inbound_alter(&$path, $original_path, $path_language) {
  $parts = explode('-', strtolower($original_path));

  $suffix = array_pop($parts);

  switch ($suffix) {
    case 'albums':
      $map = implode('-', $parts);
      $nid = myModule_get_nid_from_unique_url_safe_artist_name($map);
      $path = 'albums/'.$nid;
      break;
    // etc
  }
}

Pros,

I get a great deal of flexibility on the url design - non-conventional urls are possible
I do not need to have over 50,000 records in the url_alias table.
I can quickly and easily change the urls without having to rebuild the alias table
I can reach those pages pathauto can't
It works.

Cons,

every url passes through this test and the ones that match will be slowed down by at least one db query. (this doesn't appear to be much of a performance hit by YMMV)
url changes require developer intervention
For large numbers of panel variants, this function can become difficult to maintain, particularly because you have to be careful not to allow conflicts to arise. See below for example.
This doesn't smell right as an approach

Conflicts can come up based on your url matching methodology. I the above case we split on '-', this can become a problem in this specific case if the artist url were simply artist-name and the artist's name was literally "Michael-albums" since this would be interpreted as an album page for "Michael" rather than an artist page for "Michael Albums".


Okay, I think there must have been a typo somewhere or something, but anyway, this setup works:
info yaml:
name: Search Icon
description: This module replaces search value by an icon.

type: module
core: 8.x
core_version_requirement: ^8 || ^9

module:
<?php

/*
 * Implementation of hook_form_alter()
 */

function searchIcon_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['actions']['submit']['#value']= 'TESTSEARCH';
    }
}

Please note that the module does not work as intended yet, the value should be replaced by an html decimal code for the desired icon.


Have you enabled the "Workflow Views" module (in the workflow 'module')?
With it you get a example "workflow summary" view with a list of all content with its current state, title and type of the content.
In views you get access to a few new fields like "current state", "previous state", ...


Exposed filters with dropdown selections

The problem here is that the fields are custom text fields. If the "product type" field was of the type "List (text)" instead it would be a drop down in Views when exposed.

Maybe the product type would be good to have as taxonomy terms instead? Then product types could easy be added to the vocabulary as the site grows. The field in your content type would then be a "Term reference" to the Taxonomy vocabulary product type. If the product types rarely or never change you could stick with "List (text)"

I would probably make the field year into a date field or taxomomy, or list (integer).

I hope you see where I am trying to go here, the fields needs to be of the correct type for Views to be able to interpret the fields correctly and "automatically" give you dropdowns when the filters are exposed etc.


Different taxonomy term title for menu and term page

You can use drupal_set_title() with implementing hook_preprocess_page().

/**
 * Implements hook_preprocess_page().
 */
function mymodule_preprocess_page(&$variables) {
  $langcode = $variables['language']->language;
  $term = menu_get_object('taxonomy_term', 2, $langcode);
  if (!empty($term)) {
    drupal_set_title($term->custom_field[$langcode][0]['value']);
  }
}

menu_get_object() may not work because some module may override the menu entry taxonomy/term/% as mentioned by mxh.

If you want more robust way to retrieve the term object. Please use below snippet.

if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
  $term = taxonomy_term_load(arg(2));
}
if (isset($term) && !empty($term)) {
  // code.
}


You can achieve that by adopting the below snippet to your use case.
source:
  constants:
    PROFILE_PICTURES_FILE_DIRECTORY: 'public://profile_pictures/'

process:

  profile_picture_destination_filename_base:
    -
      plugin: concat
      source:
        - title
        - field_account_id
      delimiter: '-'

  profile_picture_destination_filename:
    -
      plugin: callback
      callable: basename
      source: field_profile_picture # This is the photo URL column.
    -
      plugin: callback
      callable: ucfirst

  profile_picture_destination_full_path:
    -
      plugin: concat
      source:
        - constants/PROFILE_PICTURES_FILE_DIRECTORY
        - '@profile_picture_destination_filename_base'
        - '@profile_picture_destination_filename'
    -
      plugin: urlencode

  profile_picture_source_image_path:
    -
      plugin: urlencode
      source: field_profile_picture # This is the photo URL column.
  uri:
    plugin: file_copy
    source:
      - '@profile_picture_source_image_path'
      - '@profile_picture_destination_full_path'
    file_exists: 'rename'
    move: FALSE


I figured I would reply to this question since I figured out an answer.  Don't know if this is the best way, but it works.

If you use the views-view-fields.tpl templates, you can skip the loop and directly list and style your fields ie:

print $fields['title']->content;
print $fields['field_location']->content;

**the code above is inside your php tags


How to replace internal links with a view (similar like the Open Graph feature)?

The correct way to do this is to write text filter and add it to input formats your users will be using. Here you have Basic description of filters and formats - for Drupal 5 and 6, but concept is still valid. They are applied on display - Drupal agrees with you that you should save just what user wrote.

You need to use hook_filter_info(). Read about it, and then about rest of filter hooks family and you will have an idea.

To provide proper content for filter, well, there is no definitive solution. If users will only input node id, simple node_load is enough. Every set of scenarios and every use case calls for it own methods. Views are elastic tools, I guess for pretty big part of use cases they can be the tool.


Is there a way to suppress warnings on the D8 Status Report page?

Unfortunately there is no hook_requirements_alter yet. As a workaround you may override system manager service which is responsible for invoking that hook.

src/SystemManager.php

namespace Drupal\example;

use Drupal\system\SystemManager as DefaultSystemManager;

/**
 * System Manager Service.
 */
class SystemManager extends DefaultSystemManager {

  /**
   * {@inheritdoc}
   */
  public function listRequirements() {
    // Suppress some unwanted warnings on Status report page.
    return array_filter(parent::listRequirements(), function ($requirement) {
      return $requirement['title'] != t('The message about CDN.');
    });
  }

}

src/ExampleServiceProvider.php

namespace Drupal\example;

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

/**
 * Overrides the system manager service to suppress some warnings.
 */
class ExampleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $container->getDefinition('system.manager')
      ->setClass('Drupal\example\SystemManager');
  }

}


Is there a way to dynamically apply a CSS to a menu that includes the taxonomy term of the current page

You could probably use Field Formatter CSS Class in some form or fashion, that can add a class to the node based on a taxonomy term, etc.


How do I pull content from a view into an array?

Not sure if it's what you're looking for, but if you're using a template to display that view, you can access an array of the view data by using the php code

$view->style_plugin->rendered_fields;

This will give you an array of everything that the view has returned.


Is there a way to re-invoke #ajax on forms when the form itself is returned with ajax?

I found the answer!

I simply was asking the wrong question. What I needed to do was re-attach the drupal behaviors with Drupal.attachBehaviors().

I added this code to my JavaScript code.

jQuery('.ajax-processed').once().ajaxSuccess(function() {
    Drupal.attachBehaviors();
});

Voilà! Everything works as it should.


Dynamically hiding / showing Field API fields in Drupal 7

In Drupal 7 you can use $form #states instead of custom jQuery script. Example:

  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    // This #states rule says that this checkboxes array will be visible only
    // when $form['student_type'] is set to t('High School').
    // It uses the jQuery selector :input[name=student_type] to choose the
    // element which triggers the behavior, and then defines the "High School"
    // value as the one that triggers visibility.
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

Here is example if you want to use #states for multiple values condition:

 $form['student_type'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'textfield',
    '#title' => t('What standardized tests did you take?'),
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type[high_school]"]' => array('checked' => TRUE),
        ':input[name="student_type[undergraduate]"]' => array('checked' => TRUE),
        ':input[name="student_type[graduate]"]' => array('checked' => FALSE),
      ),
    ),
  );

See the form_example/form_example_states.inc from examples module for more details and examples.


Setting up a Drupal environment on Ubuntu

So, Ubuntu doesn't come with LAMP out of the box but it's super easy to set up with sudo apt-get ubuntu command. The basics of setting up a lamp environment are beyond the scope on an answer here, but there are plenty of tutorials on how to do it and robust community of Ubuntu users for questions.

Based on what you're describing, I would recommend using ubuntu desktop rather than server on your VM. This will give you a GUI interface which will be a little more familiar than trying to run Unix commands through your terminal on the VM, which will require further setup of your windows box.

Once you've set your VM up the basics you will need are: Mysql (or your db of choice), php, and Apache (or your web server of choice). You can download and install all of these free, but you'll do most of this from the command I mentioned above, so I would school up if you're not comfortable Ubuntu LAMP set up. There are many tutorials on how to turn Ubuntu into a wed dev machine, pick and choose what you find useful.

You'll have to set up the Mysql server and most of the programs manually before you have a set up you can install drupal on.

To answer your two questions:

No, you don't need any tools that you didn't mention, although depending on your set up and being new to Unix environments I would look into GUI tools like Mysql workbench.
Ubuntu Desktop and Server have a designated html folder it will be in
 /var/www/html

Where it gets tricky for someone who isn't familiar with the environment is that you need to configure your folder and file permissions  for the /var/www/html folder. It has to be owned and readable to the apache or your webserver user.

This here is a good tutorial, it will get you where you need to go once you have a working LAMP server on your dev machine.Ubuntu Drupal

So, from here you have to ssh into your virtual machine or use the GUI interface to set your drupal install. This is the same as on windows:

Get a copy of Drupal Core in your web root folder.
create a drupal database, database user
point your site to the db with settings.php in your sites folder.
Run the install.php script in your web browser.
drupal and profit.

You mentioned using a lot of Drupal dev tools. You'll have to configure those yourself, but you'll have to either do it on the VM (and work natively on VM) or configure your windows drush to connect to your VM like you would a remote server. This is all good practice but, beyond the scope of a single post.


how to change max upload size of media file

What have you tried, what are your limitations? You should be able to change your php.ini if you have access per this.


Views_embed_view fatal error in views.inc

First thing I would try is using  instead of passing the arguments as an array. I recall hitting this issue because views_embed_view() uses func_get_args() to process view arguments and behaves oddly if an array of them is passed.

If that doesn't work, your best bet is to step through the code with Xdebug and see if you can find the difference between that variable when it works (all other times) and when it doesn't (this time).


How to write a property callback for a custom field to use with the Entity module

Kind of :) ... if its just numbers and strings you can cheat a little. I added some basic integer columns to the User table and wanted EntityAPI and views etc to be aware of them and did the following:

/**
 * Implementation of hook_entity_property_info(). This dpeends on the EntityAPI.
 *
 * This defines the properties/attributes/"fields" of our Entity regardless of
 * whether they are drupal Fields or custom data (in the base table).
 */
function dew_nagging_entity_property_info_alter(&$info) {
  $properties = &$info['user']['properties'];
  $properties['dew_survey_count_to_complete'] = array(
    'label' => t('Number of Surveys to Complete'),
    'type' => 'integer',
    'description' => 'When a student logs in the system derives how many surveys they must complete. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_count_to_complete',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_survey_completed_count'] = array(
    'label' => t('Number of Completed Surveys to Date'),
    'type' => 'integer',
    'description' => 'This is a count of the completed surveys completed by a student in real-time. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_completed_count',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_surveys_all_completed'] = array(
    'label' => t('Has the student completed all their Surveys?'),
    'type' => 'integer',
    'description' => 'This is a boolean indictator (0,1) of whether or not a student has completed their surveys. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_surveys_all_completed',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  return $info;
}

entity_property_verbatim_set and *_get just pull the field from the database if $info['schema field'] is defined.

I also had to make the DB changes in my .install file with db_add_field() for each database column. I also had to notify EntityAPI of my schema changes to the user table via hook_schema_alter(). All these DB schema fields and EntityAPI meta data field defintions must correlate properly.

if its more complicated, you do something like found in Ubercart products, you're just returning the item from the given Node and Field.

See http://api.ubercart.me/api/drupal/ubercart%21uc_order%21uc_order.module/function/uc_order_uc_order_get_properties/7.

EDIT

Apparently the entity_metadata_* functions have been deprecated and you should call entity_property_verbatim_get(), or entity_property_verbatim_set().


Install a module that creates a content type with fileds via YAML

For a node type + fields + formatter/widget settings, you need:

The node type, you already have that
The field.storage.node.* config entities for your fields. If they are shared with other node types/modules then it gets a bit complicated. You can't define the same default config as another module. You could make it optional config, but then all your config needs to be optional
The fields themself, like the example the one that you already have.
The core.entity_form_display.node.article.* config entities for the different form displays, for node, probably just default.
The core.entity_view_display.node.article.* config entities for all the view modes you want. default, teaser, ...

Also, note that tis is install configuration. It will only get created when you install the module. There is no standard mechanism to update configuration when you change the files and the module is already installed. There are modules for that, like config_update, features possibly also contains that.

If this is a custom module that you just need on a single site and want to use it for dev -> staging -> production (or whatever you call your environments) deployments, it's easier to use the global config folder for that. Create your config, export it, commit it, and then import again. That also does updates and deletions.


Drupal 8: Node "options" does not exist for Node "Drupal\Core\Template\TwigNodeTrans" error after update

According to https://www.drupal.org/project/drupal/issues/3051269 this is now resolved by the drupal team. Whatever caused the error seems to be fixed now in drupal 8.7.0


Seeking a point/level module to encourage user activity

For various voting and similar systems you could check these modules (including some quotes from their project pages):

Voting API:

  ... helps developers who want to use a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

Fivestar:

  ... adds a clean, attractive voting widget to nodes and comments and any entity.

User Points:

  ... provides an API for users to gain or lose points for performing certain actions on your site. In conjunction with other modules, such as the Userpoints Nodes and Comments users can accumulate points for actions such as posting nodes, commenting or moderation duties.

Flag:

  ... is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.


How to disable i18n language dropdown in node form?

So, the i18n dropdown is attached to the node form afterwards. For now I simply unset($form['#after_build'][0]) where _i18n_node_form_node_form_alter is called. Unsetting it hides all other available languages from the dropdown making it impossible to change it. To me that seems fine. If there's a more appropriate way to do this, please let me know.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE && $editor) {
        unset($form['#after_build'][0]);
    }
}

Finally I did it like @J.Reynolds suggested with hook_module_implements_alter to ensure that my module runs after Locale module

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
    }
}

function MYMODULE_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'form_alter') {
        $module = 'MYMODULE';
        // store
        $group = array($module => $implementations[$module]);
        // unset
        unset($implementations[$module]);
        // add to the end
        $implementations = $implementations + $group;
    }
}


Why isn't ['field_name'][0]['#markup'] work for getting taxonomy of this node?

Please don't print some result directly. You should print the content of field like below.

print drupal_render($content['field_case_category']);

Hope this solves your problem. Also please check whether your node contains the value for the field_case_category field.


Views contextual filters programmatically alter add to or

If you have a way of knowing both filter values (like NULL and 12), then I would use hook_views_pre_build and unset the NULL field.

function test_views_pre_build(&$view) {
  // Do some checks for view name and current_display
  unset($view->display_handler->handlers['argument']['null_field']);
}


How to install latest stable Drupal version from drupal/recommended-project branch?

Instead of forking and running composer install, you should run composer create-project drupal/recommended-project <project_root_dir>. This will install the latest stable version of Drupal and you can of course add this to your version control system (don't forget to exclude all files that you don't have to track in your VCS).

When you use the composer.lock file from the GitHub repository directly, Composer installs the software versions as defined in the lock file (in this case the development versions).


Unless you are using some sort of opcode cache, the code in your module itself won't be cached. Some hooks will only be run in certain cases and/or have cache. Most likely this is what is giving your problem.

A possible solution would be to uninstall and reinstall it again. (don't just disable the module, but uninstall it). Doing so removes a lot of the information about the module and could fix the problem.

If you gave more detail on the code/hooks you were using, a more detailed answer could be given.

Update

hook_install is run when the module is installed. This is a once per install only, so changing the code after the module is installed won't do anything. A new install is the only way to test the changes, after proper cleanup have been made.


You can achieve this functionality by using the Fieldgroup cck module.


How to create a cronjob to update all nodes

You need to create a custom module to do this.
Implement hook_cron to create a cron job in custom module
You can update a node programatically.. For more details see node_save


How to use Value Objects in Content Entities

I think I understood the motivation behind the entity api.

The entity api is not an orm. It is a dbal. The entity definitions do several things:

define the database schema
define the hydration to a concrete object.
define form handling
routing

What does this do with handling Value Objects?

Storing Value Objects

Let's assume we have the following interface, we want to create an entity for:

<?php
interface Product
{
   public function getId(): int;
   public function setId( int $id );

   public function getTitle(): string;
   public function setTitle( string $title );

   public function getPrice(): Price;
   public function setPrice( Price $price );

}

Which means we got one value object Price, which has a value and a currency.

Store the value objects values as fields

When thinking about storing a value object in a table, you would normally define a table as follows:

+------------------------+-----------+---------------+
|id|title                |priceValue | priceCurrency |
+------------------------+-----------+---------------+
|1 |Hitchhiker           |4200       |USD            |
+------------------------+-----------+---------------+

In drupal you define the schema in the static baseFieldDefinitions method and in the annotation, though that mainly just says which table to use. Please note drupal requires an id and uuid field.

<?php
/**
 * @ContentEntityType(
 *   id = "product",
 *   label = @Translation("Product"),
 *   base_table = "product",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */
class Product extends ContentEntityBase implements ContentEntityInterface
{
    ...

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {

        // Standard field, used as unique if primary index.
        $fields['id'] = BaseFieldDefinition::create('integer')
           ->setLabel(t('ID'))
           ->setDescription(t('The ID of the Product entity.'))
           ->setReadOnly(true);

        // Standard field, unique outside of the scope of the current project.
        $fields['uuid'] = BaseFieldDefinition::create('uuid')
           ->setLabel(t('UUID'))
           ->setDescription(t('The UUID of the Product entity.'))
           ->setReadOnly(true);

        $fields['title'] = BaseFieldDefinition::create('string')
           ->setLabel(t('Title'))
           ->setDescription(t('The title of the Product entity'))
           ->setSettings([
                'default_value' => '',
                'max_length' => 256,
                'text_processing' => 0
            ]);

        // define the necessary fields for our Price object

        $fields['price_value'] = BaseFieldDefinition::create('integer')
           ->setLabel(t('Price Value'))
           ->setDescription(t('How much does the product cost in the currencies smalles unit (e.g.cents)? '));

        $fields['price_currency'] = BaseFieldDefinition::create('string')
           ->setLabel(t('Price Currency'))
           ->setDescription(t('The currency the Price is given in'))
           ->setSettings([
              'default_value'   => 'USD',
              'max_length'      => 3,
              'text_processing' => 0,
           ]);

    }
}

Now that we have defined what the database should look like, let's take care of hydration

<?php
/**
 * @ContentEntityType(
 *   id = "product",
 *   label = @Translation("Product"),
 *   base_table = "product",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )
 */
class Product extends ContentEntityBase implements ContentEntityInterface
{

    public function getId()
    {
       return $this->get('id')->get(0)->get('value')->getValue() ;
    }

    public function setId( $id )
    {
       $this->get('id')->setValue($id);
    }

    public function getTitle()
    {
       return $this->get('title')->get(0)->get('value')->getValue() ;
    }

    public function setTitle( $title )
    {
       $this->get('title')->setValue($title);
    }

    public function getPrice()
    {
       return new Price(
            $this->get('price_value')->get(0)->get('value')->getValue(),
            $this->get('price_currency')->get(0)->get('value')->getValue()
        );
    }

    public function setPrice( Price $price )
    {
       $this->get('price_value')->setValue($price->getValue());
       $this->get('price_currency')->setValue($price->getCurrency());
    }

    public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
    {
        ...
    }
}

Storing a list of value objects

Let's say our product comes in different formats (I know no one would actually design it that way, I just can't come up with a better example)

<?php
interface Product
{
   public function getId(): int;
   public function setId( int $id );

   public function getTitle(): string;
   public function setTitle( string $title );

   public function getPrice(): Price;
   public function setPrice( Price $price );

   public function getFormats(): array;
   public function setFormats( Format ..$formatset);

}

For the sake of brevity I will pretend a Format only has one property.

as fields of the product table

If there is a known upper bound to the number of formats I could pretty much design my database as before

+--+---------------------+-----------+---------------+-------------+-------------+
|id|title                |price_value|price_currency |format_title1|format_title2|
+--+---------------------+-----------+---------------+-------------+-------------+
|1 |Hitchhiker           |4200       |USD            |hardcover    |balloon      |
+--+---------------------+-----------+---------------+-------------+-------------+

as a referenced table

It would be nicer to design it as two tables, that way it can easily grow without changing my database

+--+---------------------+-----------+---------------+
|id|title                |price_value|price_currency |
+--+---------------------+-----------+---------------+
|1 |Hitchhiker           |4200       |USD            |
+--+---------------------+-----------+---------------+

+----------+------------+
|product_id|format_title|
+----------+------------+
|1         |hardcover   |
+----------+------------+
|1         |balloon     |
+----------+------------+

And that somehow seems possible, but I didn't dig into that, yet.

serializing

The least nicest, but easiest solution in Drupal is serializing the list of formats

+--+---------------------+-----------+---------------+-----------------------------------+
|id|title                |price_value|price_currency |format_set_serialized              |
+--+---------------------+-----------+---------------+-----------------------------------+
|1 |Hitchhiker           |4200       |USD            | #!gobblediegook%&                 |
+--+---------------------+-----------+---------------+-----------------------------------+

The hydration would then look like the following

<?php
class Product extends ContentEntityBase implements ContentEntityInterface
{

    ...

    public function getFormats()
    {
        return unserialize(
            $this->get('format_set_serialized')->get(0)->get('value')->getValue()
        );
    }

    public function setFormats( format ...$formatSet )
    {
       $this->get('format_set_serialized')->setValue(serialize($formatSet));
    }

    ...
}

What about computed fields, custom type data and custom storage handlers?

These exist to put field specific hydration logic in the dbal part of your entity.

The question is "Will someone access the data through the entity api (dbal layer) instead of your fully hydrated domain class?"

If the anyswer is yes, then consider writing a repository service, that is available everywhere. I imagine most use cases revolve around getting domain specific data into drupal's database. So circumventing the domain logic seems like a very bad idea.

If the answer is still yes, then go for it.

I tried following the process described here. It worked but I had to add functions, that were not mentioned and were not part of the interface (specifically postSave and preSave). Also I encountered some very unhelpful errors on the way. After I had a working solution I scraped it for the simpler process outlined above. Your mileage may vary.


Shipping price for different countries using Commerce Kickstart

An easy solution is to create multiple flat rate shipping methods. As each of them is create as a rule, you can add different conditions to them, being the value of the contry in the shipping address.

Commerce shipping with then only present the user for the flat rate shipping that has the correct contry, and the price you setup will then be applied.


adding twig variable in html.html.twig from module

Just tested what I can of your code, and this works from a custom module:

function examplemodule_preprocess_html(&$variables) {

 $variables['cta_bar'] = ['#markup' => '
Test CTA Bar
'];
}

It then can be output in the theme with this template:

/themes/custom/mycustomtheme/templates/layout/html.html.twig

like this:

{{ cta_bar }}

Of course, you need to register your preprocess function by clearing the cache.

Other than that, I think it must be a problem with your theme function insusite_cta_bar_actions.  Can you give us more info on that?


I would like to just comment on this, because my answer is not exactly a solution to your particular implementation, but I do not have enough reputation :/

I will just say that in my opinion your approach to the problem is wrong. Because you are loading Angular as a JS library from Drupal, you are adding lots of unnecessary overhead to your application, especially to the initial load of the page and you are defeating the purpose of using a Front-end framework.

In my experience, using a Front-end framework like Angular is a solution to completely decouple the Front-end from the Back-end. So my suggestions is just that:

Create a regular Angular application and inside that Angular app you create a sub-folder that will contain your Drupal application.

And from this point on you can use REST webservices for fetching the data from Drupal. The core Views module combined with the core REST module provides out of the box Drupal functionality for this, and in addition Symfony provides the JsonResponse class that you use for sending simple responses. ( I really recommend using the JsonResponse, because it just bypasses Drupal's entire rendering system)

This way, you have nice Back-end code that can be organized in different controllers, which will callbacks to routes exposed as REST endpoints and a completely decoupled Front-end layer that will only call a number of select REST methods on different routes.

PS: for more information on this topic, please search for the term Headless Drupal, and you will find lots of helpful info


Protected $view values inside template_views_pre_render function?

To access the value of the view object you can use the method get():

$view->get('id')

Or if the object provides a special method for the id, which is the case with the view object:

$view->id()


How to redirect to another drupal site/alias after file upload

You can add a custom submit handler onto your form and add a $form['#redirect'] attribute to the target destination. There are many examples of form redirect questions on this site, and also examples for custom submit handlers for forms.


It's not possible to set it in the UI, but it's still possible through code.

If you check the exported configuration for your field, you can see that it has an allowed_values_callback property. Create a custom module, create a function that returns the allowed values, set that property in config and then import the configuration again. Or use drush cedit or a similar tool.


Why file attachment has different URLs in icons links and default link on node page?

I believe, there can be custom or some contributed module doing the trick.
The menu - download/file/fid/[id] is created by some module and allowing you to download the file.
Might be a case that the logic is written in the same callback.

try searching your modules with this callback and you might see some results...


Login and get homepage content with a Bash script

You might want to double checking your encoding or the headers that you're sending over that might cause the problem. I've found trying to do this with a pure Bash solution very fickle at times. Here's an example function I've used that will login into a D7 site on the /user page (an easier manner since every D7 install can be logged in from that path).

#!/bin/sh

# https://gist.github.com/cdown/1163649
#Usage: urlencode "string"
function urlencode() {
  old_lc_collate=$LC_COLLATE
  LC_COLLATE=C

  local length="${#1}"
  for (( i = 0; i < length; i++ )); do
    local c="${1:i:1}"
    case $c in
      [a-zA-Z0-9.~_-]) printf "$c" ;;
      *) printf '%%%02X' "'$c" ;;
    esac
  done

  LC_COLLATE=$old_lc_collate
}

#Usage: login "user" "pass"
function login() {
  URL=https://www.example.com/user
  name=$(urlencode "$1")
  pass=$(urlencode "$2")
  post_data="name=$name&pass=$pass"

  #Retrieve login page, login form, & input fields.
  login_page=$(curl -s -H "Content-Type:application/xml"  "$URL")
  login_form=$(echo $login_page | grep -o '<form[^>]*action="/user"[^>]*id="user-login"[^>]*>.*</form>')
  login_input=$(echo $login_form | grep -o '<input[^>]*/>')

  #Create Post Body
  while read -r input; do
    input_field=$(echo "$input" | sed -e 's/.*name="\([^"]*\)".*/\1/')
    if [[ $input_field != "name" && $input_field != "pass" ]]; then
      input_value=$(echo "$input" | sed -e 's/.*value="\([^"]*\)".*/\1/')
      input_field=$(urlencode "$input_field")
      input_value=$(urlencode "$input_value")
      post_data="$post_data&$input_field=$input_value"
    fi
  done <<< "$login_input"

  # Depending on your hosting environment you might need additional headers to make yourself not look like a bot
  user_agent="User-Agent:Mozilla/5.0 "
  referer="Referer:https://www.example.com/user"
  origin="Origin:https://www.example.com"
  content_type="Content-Type:application/x-www-form-urlencoded"

  # For further authenticated requests, you will need to parse output "Set-Cookie: ..." and set
  # the session cookie in a -H "Cookie: ..." option
  curl -s -L -H "$content_type" -H "$user_agent" -H "$referer" -H "$origin" --request POST "${URL}?destination=/" --data "$post_data"
}

login 'USER' 'PASS'

I've found logging into Drupal via Bash much easier with if you can work with a scripting language that has built in HTTP clients & parsers. Depending on your scenario, you might want to consider that if you need a more robust solution.


Which function(s) actually create the physical resized image files?

The function that generates the image URL basing on the style is theme('image_style'), which is called by theme('image_formatter'), which then called from image_field_formatter_view(); this function is the implementation of hook_field_formatter_view(), the hook that in a field formatter outputs the content of the field in the view for the entity containing that field.

The image is only generated when you access its URL. I tried the following code:

theme("image_formatter", array("image_style" => "thumbnail", "item" => array("uri" => "test.png", "title" => "Image title", "alt" => "Alternative text")));

The output that I obtained is the following:

<img typeof="foaf:Image" src="http://tero.local/dr72/sites/default/files/styles/thumbnail/public/test.png" alt="Alternative text" title="Image title" />

If you look at the code of image_menu(), you will find the following lines:

  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  $items[$directory_path . '/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

image_style_deliver() is the function that generates the image.


What's the purpose of the authmap table?

The "authmap" table is used when a user is authenticated using an external site, for example an OpenID server.
For example, in my test site I have used OpenID to create an account. In that table, I then found the user ID of the user account created by Drupal, and the OpenID URL used to authenticate the user (the one provided by the OpenID server).

The comment in user_external_login_register() gives a short explanation of how that table is used, and which functions the modules integrating with an external authentication server should use.

  Helper function for authentication modules. Either logs in or registers the current user, based on username. Either way, the global $user object is populated and login tasks are performed.

Keep in mind that in Drupal 8 the "authmap" table, and the functionality provided by the functions using it have been removed. Any module providing the integration with an external authentication server will need to use its own database table, which is what the OpenID module did in Drupal 8, before being dropped off.


Translate hard-coded strings with source language other than english

We also have a lot of sites with a primary language which is not english.

After several different approaches we opted to write all user exposed string in our modules in english and translate them with the t() function.

We then use a crawler like wget to crawl the whole site (to get all strings into the translation database).

We enable the module Translation template extractor (https://www.drupal.org/project/potx)  and export all strings from our module with this module in our languages.

The resulting language-files are edited and translations are added.

This file is then put in a "translations" subfolder in our module file with a *.po extension.

Uninstall and reinstall the module to activate the translations for your languages.

It may sound like a lot of work, because it is, but this is the only method that actually worked for us.


How do you change the email recipient of drupal 7 webform based on checkbox value using hook form alter?

You do not need to use hook_form_alter for this, you can set this up in Webform on admin, here is how:

Go to the Edit interface of your webform
Go to E-mails
At the bottom, choose 'Component value' and choose your checkbox field, click Add http://cl.ly/image/1K3V2N3k3q30
At 'Component e-mail options' you can specify an email address for each option http://cl.ly/image/1g3c1r15060r

Description below says:

"You may enter an e-mail address for each choice. When that choice is selected, an e-mail will be sent to the corresponding address. If a field is left blank, no e-mail will be sent for that option."


How do I show content based on relationship?

Create a new View with whatever fields, teasers that you want.
Click on the "Advanced" tab and that should open up a whole bunch of
sections.  You need the "Relationships" section. Click "Add". In the
popup find "User Relationships: Requester user" that's your key.
Now you need to validate who that Requester is. You do it through
the Contextual Filters. Click "Add" and find "User Relationships:
Requester user", and inside it's options select "Current User".
Now you need to filter content that is written by "friends of" the
current user. For that you need to add another relationship "User Relationships: Requestee user" which is a relationship of "User Relationships: Requester user" that you have already established.
Under "Filter Criteria" click "Add" - find "node Author", and
in it's options choose "requestee".

These are the basic directions, you can play around with it under different combinations.


Using Views to add comments to user profiles

Some hints which might push you in the right direction:

Ratings can be handled with the five star module.
I didn't test this, but the profile 2 module gives you the ability to tye a content type to a drupal user. Enabling comments for this content type could get you going.


Spammers apply for an account, how to disable other users from applying for an account on my website

There are several options. In addition to disallowing vistor registration (Navigate to Administration → Configuration → People → Account settings and select "Administrators only" under "Who can register accounts?", you may you one of several contributed modules that is designed to prevent spammer and spambots from registration.

My personal favourite is Mother May I.  It adds a field to the registration form where the registrant must type in a "secret word". If the registrant gets this wrong, no new account is created.  This is perfect for invitation only sites, where the invitation reveals the "secret word".  However, I find it works pretty well on other sites as well, where the "secret word" may be the answer to some a "riddle" that is solvable by humans but not by 'bots.

As an alternative to the above, there are are several contributed modules that let you add various types of CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) challenges to forms, including the user registration form. These block spam robots, but do not block human spam registrations. However, blocking 'bots take care of about 99 % of spam registratons, so doing this helps a lot.  The most popular module providing a CAPTCHA is named CAPTCHA. It comes with a built-in challenge, but is really a framework that to manage a set of CAPTCHA plugin modules, letting you experiment with these to find one CAPTCHA method that is effective for your site.

There are also contributed modules that provides a Drupal  interface to some external third party anti-spam service. The most effective of these is http:BL. an interface to the project Honeypot blacklist.  I've found that this module provides efficient blacklist lookups and blocks malicious visitors effectively.  (There a few false positives tho', in particular if your site attracts visitors that connects through TOR.)


With i18n module pack, there is a module for translating settings, like front page and 404 pages. This means you can setup your 404 page per language, fx node/1 for en and node/2 for fr etc.


What is causing the unusual output when trying to create charts in Drupal 7 using the pChart library?

The output you are seeing is simply the PNG file that is being outputs it would be a text file. That is because Drupal already sets the "Content-type" header to "text/html; charset=utf-8," while the method you are calling is setting it to "image/png."

   function stroke($BrowserExpire=FALSE)
    {
     if ( $this->TransparentBackground ) {imagealphablending($this->Picture,false); imagesavealpha($this->Picture,true); }

     if ( $BrowserExpire )
      {
       header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
       header("Cache-Control: no-cache");
       header("Pragma: no-cache");
      }

     header('Content-type: image/png');
     imagepng($this->Picture);
    }

   /* Automatic output method based on the calling interface */
   function autoOutput($FileName="output.png")
    {
     if (php_sapi_name() == "cli")
      $this->Render($FileName);
     else
      $this->Stroke();
    }

What you could do is:

Use pChart to create a file containing the chart you want to show
Output a  tag that references the created file

If imagepng() used the PHP stream wrappers (which is true for file_get_contents()), the following code would work.

/* Render the picture (choose the best way) */
$uri = file_create_filename('example.basic.png', file_build_uri('pictures'));
$myPicture->Render($uri);
echo('');

In this case, the code is slightly more complex.

/* Render the picture (choose the best way) */
$uri = file_create_filename('example.basic.png', file_build_uri('pictures'));
$instance = file_stream_wrapper_get_instance_by_uri($uri);
if ($filename = $instance->realpath()) {
  $myPicture->Render($filename);
  echo('');
}

I wrote a conditional statement around $filename = $instance->realpath() because DrupalLocalStreamWrapper::getLocalPath(), the method called by DrupalLocalStreamWrapper::realpath(), can return FALSE when it cannot determinate the real path.

file_create_filename() is a function that returns a unique filename; in the case there is already a file with the name passed as argument, the function adds a number at the end of the filename, checking every time the file doesn't exist already. If "example.basic.png" is the name of an existing file, the function will try with "example.basic_0.png"; if there is already a file using that filename, it will try with "example.basic_1.png"; the loop is continued until the function find a filename that is not already used.

In the case you need to the filename to a function, as in this case, try first the file_create_filename($filename, file_build_uri($directory)) approach, when you are not sure the function to which you are passing the filename is using PHP stream wrappers; only in the case it doesn't, you should use file_stream_wrapper_get_instance_by_uri() as in the second snippet.


Create a custom front page for anonymous users

in your THEME_preprocess_page(&$vars) hook you can put something along the lines of...

if ($vars['is_front'] && !$vars['logged_in']) {
   $vars['template_files'][]='page-front-anonymous'; // drupal 6
   $vars['theme_hook_suggestions'][]='page_front_anonymous'; // drupal 7
}

which should work using the is_front and logged_in variables set by the various modules before you get to it.  if you are using a module, and don't want to rely on weight/execution order, you could do it with:

global $user;
if (drupal_is_front_page() && !$user->uid ) {
.....


Node Access Product Module (nap) - Really embarrassing error message

This error is thrown when an object is empty, and you attempt to determine the value of a property. In this case the following code is responsible:

 // Go through each of the products purchased.
  for ($i = 0; $i < count($product_nodes); $i++) {
    // Easy referencing.
    $node = &$product_nodes[$i];
    $settings = nap_get_nap_settings($node->nid); <- Throws error

My guess is that $product_nodes is empty.

Try wrapping the for loop as follows:

 // Go through each of the products purchased.
  if (!empty($product_nodes)) {
    for ($i = 0; $i < count($product_nodes); $i++) {
      // Easy referencing.
      $node = &$product_nodes[$i];
      $settings = nap_get_nap_settings($node->nid);

      ..rest of loop code ...

    } //End of for loop
  }

This should work. You should also bring this up as an issue on the project page.


It sounds like the file /var/www/drupal7/sites/all/modules/migrate_example/beer.inc is missing.


Add epsacrop to programmatically added image field

I had the same problem. If you change managed_file to media, you will have availability to manage EPSA cropping for the form image.


Prevent rule from triggering on Entity Reference Fields

It shouldn't fire because of an entity reference field..

Have you added a Content is of type  condition to the rule?

Data selector: node
Value: Contacts.

Edit:

It could be that the display mode of the referenced entities is counting as a view.

Add a condition, data comparison for site:current-page:url and node:url

This will force rules to check the page url which will return FALSE for every page except the nodes's pages.


How do I access the "#default_value" property from $form_state['values']

The array indexes contained in $form_state are reported in Form generation.

The default values are only present in the $form array, which is passed as argument to the form validation handlers, the form submission handlers, and any implementation of hook_form_alter() (including hook_form_FORM_ID_alter()).

The only way to access the default value for a form field is to know the array structure of $form. If the code is using a form created from a module you are writing, that is not difficult; if the code is using a form created by a module you didn't write, you need to check the structure of the form array created by that module.


Combine two fields to be displayed together

A simple way is achieve your job by jquery,( but if you have drupal developing knowledge you can do it in  tpl.php or custom module) but quick method is using jquery, get text from one element , the append it to second and hide first

blah 1

blah 2

and your js will be something like this

$('.second').append($('.first').text());
$('.first').hide();


Entity reference Hierarchical Select between three content types?

You could try that module conditional_fields

That link also may help Update multiple fields with ajax callback in form


In Commerece 2.x can address be selected in the country's official language?

Country and subdivision translations are selected based on the current language. If your site language is "zh" you should be seeing the local labels.

For non-native languages the latin script alternative is shown for readability. If this is not working as I described, you can open an issue in the address issue queue.


prevent user creating a duplicate node title

You can try the Unique field module.

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

I have not tested it yet, but it seems promising.


you can sale services in both Commerce and Ubercart. But if you look for simplicity I should tell you Commerce is simple and light enough.

At this time I can't remember any other solution on D7 except writing custom module. which I don't recommend.


Filter criteria with entity reference field doesn't work

I hover over the field. It says event_author_id. It should be the id of the author, instead of text. Or If I want to use text 'author1' in filter. I need to add a relationship in the view. Like a mysql join.


A quick way to load images from a list of urls

Haven't tried it, but I would use the Feeds module with a csv import of the urls to the files.

You may also need http://drupal.org/project/media_feeds.  I think this video shows how to do this http://ia600704.us.archive.org/35/items/WorkingWithMediaInD7/usingmedia.mp4


using ajaxComplete with drupal quicktabs

Of course after posting on here I was able to figure out my mistake.

jQuery('#quicktabs-tab-find_a_doctor-1').click(function(){

  // Making room for loading icon
  jQuery('#quicktabs-tab-find_a_doctor-1').css({
      "float":"left",
      "padding-right":"5px"
    });

  // Adding the loading icon to tab
  jQuery('#quicktabs-tab-find_a_doctor-1').parent().append('

');

  // Once ajax is complete remove loading icon from page
  (function($) {
    Drupal.behaviors.LoadingIcon = {
      attach: function() {
        $(document).ajaxComplete(function() {
          $('#loading-icon').remove();
          $('#quicktabs-tab-find_a_doctor-1').css({
            "padding-right":"0px"
          });
        });
      }
    }
  }(jQuery));
});

According to http://api.jquery.com/ajaxcomplete/
You need to attach the .autoComplete() onto the document as stated right here:

  As of jQuery 1.8, the .ajaxComplete() method should only be attached to document.


How to add a default taxonomy term to all nodes in a migration?

Well, i don't like it, but this works:

<?php

use Drupal\migrate\Row;
use Drupal\migrate\Plugin\MigrateSourceInterface;
use Drupal\migrate\Plugin\MigrationInterface;

/**
 * Implements hook_migrate_MIGRATION_ID_prepare_row() for upgrade_d7_node_quote.
 */
function portside_upgrade_migrate_upgrade_d7_node_quote_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
   $term_name = 'Portside Quotation';
   $term_array = \Drupal::database()->select('taxonomy_term_field_data', 't')
     ->fields('t', ['tid'])
     ->condition('vid', 'categories')
     ->condition('name', $term_name)
     ->execute()
     ->fetchCol();
   if (isset($term_array[0])) {
     $row->setSourceProperty('field_categories', [['tid' => $term_array[0]]]);
   }
}

I create the taxonomy term with default content, so it's there after site install and ready for the migration.

In the migration's YAML file (for upgrade_d7_node_quote), there's simply a plain mapping as if field_categories were a real thing:

  field_categories:
    plugin: iterator
    source: field_categories
    process:
      target_id: tid

And remember, there is no field_categories in the source.  The migration doesn't mind at all and works fine with one inserted into the source in this prepare row hook.


How do I add a link to a table row in a custom module?

This worked for me

use Drupal\Component\Render\FormattableMarkup;
  $rows[] = array(

      array('data' => new FormattableMarkup('@name',
        [':link' => $entry['link_url'],
        '@name' => $entry['name']])
      ),


Downloading, and loading Google analytics script locally and daily with Drupal Cron

This has been built into the Google Analytics module for sometime. In the configuration form, under Advanced Settings there's a Locally cache tracking code file checkbox. It will persist a local cached version of the JS code for day before a cron run will re-cache it.


how access $content array inside a block php?

If you need to extract the comment of a node and put it in a block you can achieve this with a view.

Create a new view who show 'Comments' and create a block.
Now you can add a contexual filter:

Comment: Nid
The node ID to which the comment is a reply to.

After that select 'Provide default value'
and 'Content ID from URL'

Now you can add a 'Validation criteria'
and select 'Content' and check only the content type you want with this block.
now set 'Action to take if filter value does not validate' to 'Hide view'

Now you can add this block to a region in the block page and you have the node's comment displayed in a block.

Let me know if this will work for you ^^


Store custom checkout pane data to order

I found a solution. With my custom field called "Test me" and machine name "field_test_me" created in my Order Type entity I could save the data from Custom Checkout Pane with $this->order->set() function instead of $this->order->setData(). Of course I needed to change $this->order->getData() to $this->order->get() everywhere where used.
I don't understand what's the difference between set() and setData(), but it seems to store my Custom Checkout Pane values to my custom fields created in my Order type entity.


How to add an editable text box to a page

OK thought i would answer my own question and show the method in which this is done. First declare a block, with a block view and then define a custom callback function that defines the textarea, are any output from Drupal's Form API.

function hook_block_info() {
  $blocks['box_question'] = array(
    'info' => t('Box question area'),
  );
  return $blocks;
}

function hook_block_view($delta = '') {
  $block['subject'] = t('TEST');
  $block['content'] .= drupal_render(drupal_get_form('custom_block_form'));
  return $block;
}

function custom_block_form($form, &$form_state) {
  $form['question'] = array(
    '#markup' => 'this is a block,
  );
  $form['answer'] = array(
    '#type' => 'textarea',
    '#resizable' => FALSE,
    '#default_value' => $default,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#name' => 'save',
    '#attributes' => array(
      'class' => array('save-button'),
    ),
  );
  return $form;
}

The custom_block_form is what defines the form blocks, call the submit functions to make your own callback on what to do when the form is saved.


Menu has an inconsistent pattern for machine names with most other parts of the system, that was simply not unified when converted to use the config system.

There is no reason, but it also can't be changed now as existing menus would then be invalid.


How Can I have Exposed filter for Taxonomy vocabulary in Heirarchical Select?

Solution of My problem:
I use SHS module and in views filter fields select "has taxonomy term (with dept) - simple_hierarchical-select" and in dept field of its settings set 1 .
Now with select any parent term or subterm , views has the result.


Unable to save data from custom drupal form

As stated by @Molot this should not be used generally. Recommended methods would be db_insert and db_merge.

Placeholders are layed wrong, they need to be in single array. Use

 $sql = "INSERT INTO {customers} (first_name,last_name,email_addr,password)
         VALUES(:fName, :lName, :email , :cpwd)";
db_query($sql,
    array(
      ':fName' => $form_state['values']['fName'],
      ':lName' => $form_state['values']['lName'],
      ':email' => $form_state['values']['email'],
      ':cpwd' => $form_state['values']['cpwd'],
   )
);


I find.

In my instance, I use :

 'allowed_values' => array(),
 'allowed_values_function' => '_get_list_catalogue',


Looks like the problem is with the CSS rather than the id part. The typical id would be something like this: edit-field-date-und-0-value-datepicker-popup-0 and this id is dynamically generated and not grandee that it would stay same (i.e. you may get edit-field-date-und-0-value-datepicker-popup-1 if you have the same field twice in the same form).

You can use name instead of id. Here is the working fork of your jsfiddle with name: http://jsfiddle.net/vijaycs85/C4sh9/


theme still use caching even when flushed cache and using devel

Since it sounds like you've got all the Drupal-related items checked, perhaps it's worth a shot in the dark...

Pull up the site in Chrome and inspect the element that's supposed to have the updated colors (right click and select "Inspect element"). This may reveal one of two things:

Click the "Computed" tab in the right-hand column. Is your color change being overwritten by a more specific declaration? (eg: #foo .some-class { ... } will supersede .foo-class .some-class { ... } regardless of the order in which they appear)
Perhaps you've been editing the wrong file? I know I've done it before...  Click the Sources tab and make sure the page is loading the file you expect it to load. Make some random changes, reload and check that those changes show up.

Hope that helps.


What is the best way to alter image style in view for a teaser

While I would generally just access this from the field output type from the View. I would recommend looking into some theme adjustments (and preprocessing Views). Since you are outputting content to the Teaser, you could add some additional verification from the template (https://www.drupal.org/node/53464).

Some helpful links would be:

template_preprocess_views_view_fields
theme_image_style


How can a div at the top of the page coexist with Adminstration Menu?

One way of doing that with the CSS is as below:

.dev-query {
    position: fixed;
    top: 33px;
    width: 100%;
    left: 30px;
    color: #000;
    z-index: 100;
}

I have tried that and it seems to be working for me.

Another way of doing this with the JS I have mentioned here is somewhat like below:


How to import multiple taxonomy terms from csv using Feeds

Taxonomy CSV import/export

This module will help you to import the taxonomies in system.


Image shows on home page but not other pages

right now its appending after the url of whatever page you are on.

yourwebsite.com/hello/sites/default/files/image-name
yourwebsite.com/article/sites/default/files/image-name
yourwebsite.com/contact-us/sites/default/files/image-name

instead of appending after your domain name.

yourwebsite.com/sites/default/files/image-name

so you just need to add a / at the beginning, so it appends after your domain name only.

so your code needs to be:


Call apachesolr_mark_entity without node_save

apachesolr_mark_entity() needs node_save() to work.

I would have to disagree; this is the code:

function apachesolr_mark_entity($entity_type, $entity_id) {
  module_load_include('inc', 'apachesolr', 'apachesolr.index');
  $table = apachesolr_get_indexer_table($entity_type);
  if (!empty($table)) {
    db_update($table)
      ->condition('entity_id', $entity_id)
      ->fields(array('changed' => REQUEST_TIME))
      ->execute();
  }
}

As you can see it's just a simple database update, node_save() is not involved.


How do I check if a module is being used by another?

drush pm-info mymodule|grep "Required by"

grep or don't grep is up to you ;)

Beware this does not list fields that require the module. This implies to views that use fields too.

fields: admin/reports/fields

views: admin/reports/fields/views-fields

those will list fields only, so if you have special pagers, formatters or something else that come from a module you will still have to search for them.


Vocabulary Term Translation Edit/Delete Page Get Access Denied/ Doesn't Function Correctly

Just check "Content language" under "Content language detection".


Is there anything like attached data storage for a view?

If you're comfortable in code, you can do that with Panels and ctools contexts.


Add this to your template.php file.

function THEMENAME_preprocess_node(&$variables) {
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
}

You might need to add this to your node.page.tpl file.

$variables['submitted'] = t('Submitted on !datetime', array('!datetime' => $variables['date']));

The source is this post.


If you are trying to place some block below the site logo, there should be a region below it. CSS come later.

If your block is going below menu, that means the region where you are placing are rendered below menu in the page.tpl.php

You have two choice here - either render the same region just after site logo or create another region in there.

Open your page.tpl.php & try to find -

<?php if ($logo): ?>
  /*more text*/
<?php endif; ?>

Render your region just after it (assuming your region name is header) --

<?php print render($page['header']); ?>

You can add DIV class or ID according to your need around it or do it in if-else, like -

<?php if ($page['header']): ?>
  <div class="header" >
    <?php print render($page['header']); ?>
  </div>
<?php endif; ?>

You can add your own region in theme.info file if you don't want to use the same where you were trying to place your static content.


Why are existing entity reference fields not available to add to a media type?

I found the resources I was looking for with help from a comment by Clive:

A field can only be used on the same entity type. There is an open issue for this in the queue. According to the issue and my recollection this is a change from Drupal 7. If so it feels like a major regression.

The documentation is also incorrect at the time of this writing.


Displaying data by views from external API

If all you need to do is display data from the API, then you don't need to do anything special within views.  Just select that you'd like to view rendered entities of your users with a specific view mode.

In the preprocess function for that view mode, you can hit the API and load the additional data that you need.  Data loaded within a preprocess function should cache, so it shouldn't hit the API on subsequent page loads.

function mymodule_preprocess_user(&$variables) {
  /** @var $account \Drupal\user\UserInterface */
  $account = $variables['elements']['#user'];

  // custom code to hit the 3rd party API


Autopublish content from drupal to wordpress

This is more of a Wordpress question, but on drupal side you could expose the new content with a feed or JSON View and after that use some WP module to import the data.

Edit
And here's something that you can use on WP side to autopost from a feed: https://wordpress.org/plugins/wp-rss-multi-importer/


Context module not triggering Delta snapshot

ok...so I'm dumb. I guess this is for anyone else who is going too fast, like I was - I created the delta module for another theme. I didn't realize that the delta snapshots are per theme, which makes sense.


Displaying relative dates in a Views Exposed Filter

Edited - You can apply datepicker to the field, as Jquery Ui date picker is available in Drupal8. For reference see to this

Or,

you can programmatically alter the view query in hook_views_query_alter()

function module_name_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
 // Query alter to provide dynamic date ranges.
 if ($view->id() == 'VIEW ID' && $view->current_display == 'page_1')
 {
    foreach ($query->where[0]['conditions'] as $key) {
      if (array_key_exists(':node__field_start_date_time.field_start_date_time_value[]', $key['value'])) {
        // do anything you want...
        ...
        ...
      }
    }
 }


Programmatically insert field collection of Phone fields

This code works fine for user entities under Drupal 7:

  $values['field_office_phone'][LANGUAGE_NONE][0]['number'] = '0412345678';
  $values['field_office_phone'][LANGUAGE_NONE][0]['country_codes'] = 'au';

Adapt countrycode to your user's country.
I don't think I'm using Profile2 and there are multiple different modules that implement phone number fields. My server has cck_phone-7.x-1.x-dev installed.


How do I add my new Paragraph type to a content type?

Turns out I was missing a step:

Structure>>Content Types
Edit the content type you want to add the Paragraph to
Go to Manage Fields tab
Find the Paragraphs entry in the list and click edit
Check your bundle from the list


In your feed importer mapping, change the Source to Watch page.  It seems Video URL is broken.

I have it working right now with the following modules:

Feeds (feeds)  7.x-2.0-alpha7
Feeds: YouTube (feeds_youtube)  7.x-2.0-beta1+7-dev
Media Feeds (media_feeds)  7.x-2.0-alpha1+9-dev
Media (media)  7.x-1.2
Media Internet Sources (media_internet)  7.x-1.2
Media: YouTube (media_youtube)  7.x-2.0-rc1

All dev versions were as of today (Dec. 1, 2012).  And for anyone that's trying, I found Embedded Media Field (emfield) to not work with Feeds at all.

Using the File field type (the widget type doesn't matter for feeds imports), set the display to Rendered file.


How to Auto-save a custom entity to database in response to a new user account using Rules?

Your issue (about "no account has been created in DB table") might possibly be because of the event (= "after saving new user account") you are using, which might simply not be the right event.

Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).

Not sure if this is "the" reason for your issue, but I'd definitely give it a try to see if it helps (debugging is the art of taking away all possible causes for an issue ...).


Somehow forum's got associated to wrong taxonomy vocabulary. Need help

Option 1
Go to the Forum Topic manage fields and click edit in the forums field.
Check that the vocabulary is set to Forums
If it's not, delete the forum field and add the term reference field again.

Option 2
Have u posted content already to the forum? or do you care about the forum content? if not, disabling and uninstalling both Forum and Advanced Forum would be an option you could try and then enable them again.


How to send notification email to individual users

I just implemented the same thing this morning. I hope my solution will help you, but it probably depends on if your content type field is set up like mine.

My user list is presented via an Entity Reference view that I created. Users check off who they want email sent to and save the content type.

My rule is as follows:

Event:
    After saving new content

Conditions:
    Content is of type
        Parameter: Content: [node], Content types: User message

Actions:
    Add a variable
        Parameter: Type: List of user items, Value: [node:field-people]
        Provides variables: List of members to email (members_to_email)

    Loop
        Parameter: List: [members-to-email]
        List item: Current member (member)

        Send mail
            (contents of email listed here)

You'll obviously have different names for your content type, node field, variable names, etc. but hopefully this will get you started in the right direction. If you want the export of the Rule instead of what I posted here, let me know. I thought that showing you what I did through the interface might be an easier start for you.


This doesn't work anymore like this and the reason is render caching.

After calling view(), you only get a minimal render array, that will use #pre_render callbacks to complete itself in case of a cache miss. On a cache hit, it will return the cached HTML, without having to build all the fields.

The information you want to hide is in the template, both the title and the authored by information (which can be hidden for a node type for all bundles but not per view-mode).

The correct way to deal with that is to define your own view mode (default is wrong anyway, you should use 'full', not 'default', default is the fallback view display, not a view mode).

For that view mode, you can then provide a template/preprocess hook/hook_entity_view/hook_entity_view_alter hook, use any of those or a combination of it to achieve the desired result. To not show the authored by information, you can for example unset $variables['display_submitted'] as it uses that in the default node.html.twig template. Or provide a template suggestion for your view mode that removes that part completely. Both work, a preprocess is a bit easier from a module.

The important part is that you need your own view mode for that unless it is ok that full should never show that information, then that's fine too. The default cache key is entity type/entity id/view mode. There are other ways, you could add a cache context or you could even add another cache key, but you still need to do it within those hooks/template and the most obvious way to flag it for that is a view mode, that's what they exist for.


In addition to this code, you must use this code.

function custom_edit_form_submit(&$form, &$form_state) {
   $form['actions']['submit']['#submit'][] = 'custom_edit_form_submit';
}

whenever a submit is to be altered, we need not to override the index of default submit functionality instead we create a new one to perform a functionality on submit.

I hope, it will work for you!


How can I add custom client-side validation to a Webform field using advanced custom properties?

Although this answer does not provide the solution to add custom client-side validation to a Webform field using advanced custom properties, it provides a working alternative to add client-side validation to a Webform field.

Given that Webform UI comes with the option to add custom CSS and Javascript to a Webform, I have made use of this option to add my custom validation.


Form element with type = value odd behaviour

You can use form properties:

$form['#mystore'] = $fields;

The form properties are not sent to the client, but are available in the submit hander. For example, core use $form['#node'], $form['#user'], etc.

Updated:

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html#val

  Note that as of Drupal 6, you can also simply store arbitrary
  variables in $form['#foo'] instead, as long as '#foo' does not
  conflict with any other internal property of the Form API.

Updated 2:

Your problem may be related to this issue: http://drupal.org/node/1381830


#attached property doest't work!(render array/form api)

after many hours of searching and debugging for an anwser, i finally realize  it's a naming issue. you cannot name the css file as style.css. i changed the name  to custom.css,then it works as expected!