How can I change the page title for user/login for unauthenticated users?

You have alot of good information there (seriously). What you want to do is probably use hook_form_FORM_ID_alter() on the user form.

You want to set the #title attribute of the form element for the name element of the login form.

Some example code:

function MYMODULE_user_login_form_alter(&$form, &$form_state) {
  $form['name']['#title'] = 'Your Nickname:';
}

You'll probably want to check that a user is not logged in yet with something like user_is_logged_in() or your own custom logic.


token_filter module: [node:nid] for custom block?

[current-page:url:unaliased:args:value:1]

gives you the [node:nid] even when called from a block.

As per:

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

..."[current-page:url:unaliased:args:value:0] (The first value, of the array of arguments, of the unaliased URL of the current page)."


Why are my custom fees disappearing from my orders?

You need to apply commerce fees after "checkout_checkout" status and also move order to next status i assume "checkout_review".

commerce_fees_apply() is a rule callback and you are calling it directly from your code.This function first removes all fee type line item and then adds add the same and expects values from rules config.

I tried this and it worked.

module_load_include('inc','commerce_fees','commerce_fees.rules');
$order = commerce_order_load(3);
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$fee = 'test';
commerce_fees_apply($order_wrapper, $fee, 500, 'USD');
commerce_order_save($order);
commerce_order_status_update($order, 'checkout_review');

But curious to know why you are writing code for this.You can easily achieve this using rules.


Using entity query build to select entities applying conditions on all revisions

Yes. EntityFieldQuery has a property EntityFieldQuery::$age that is a flag for the age of the returned entity revision. It can be set to:

FIELD_LOAD_CURRENT (default): for only the current revision (e.g. $query->age = FIELD_LOAD_CURRENT;)
FIELD_LOAD_REVISION - for all revisions (e.g. $query->age = FIELD_LOAD_REVISION;)

Support for this flag ultimately depends on the EFQ's queryCallback function. In the default field_sql_storage_field_storage_query() function, it is recognized and queries the appropriate revision tables accordingly.


Custom module pages not rendering when added to admin menu

All I can suggest is to look at page callbacks that already render on administrative pages (like the ones in core). There should be nothing special between a core or third-party module in this respect.

More thoughts:

You should not call drupal_render() in a page callback. Return the render array and let core do the rendering
No need for 'theme callback' in a menu definition here


What does "attach to content type" option in Feeds importer do?

Yeah - I found this confusing as well.

Personally, I always select "standalone" which means that when I'm ready to import nodes with an importer I've created, I go to the path /import (e.g., http://example.com/import)

On this screen, I can select my importer and then launch the actual import (the one I created under /structure/feeds).

If you decide to attach to a content type instead, it just means that you go to /content/add/[content type] to launch the import process rather than /import. This way just never made sense to me conceptually, but there are probably good reasons to use this approach. Probably depends on who (which roles) you want to be able to use feeds imports.

Anne


How to implement hook_views_query_alter?

.views.inc file is to separate the views alter logic.

hook_views_api to add the mymodule.views.inc file which can be with path your-module/includes/views or at the root of your module.

You also can use mymodule_views_query_alter at mymodule.module file which should work fine.

Please remove the cache after applying the changes.


You can use CSS to style the tags.

If your html output is this:

Tag 1</l1>

Tag 2</l1>

Tag 3</l1>

Tag 4</l1>

Then use the following CSS to align tags horizontally.

.tags li { display:block; float:left; }


Export and import modules of an installation

It sounds like you are describing two kinds of workflows.

One way is to use Features - where you package functionality into modules. In your case, you would create a Feature, select modules as dependencies as well as any configuration you want to carry forward. When the feature is enabled, all those modules are enabled.

Another way is defining dependencies with Composer (8.x) and combine that using Features and build tasks to automate this further, where nuking and reinstalling Drupal returns to the same state, kind of like an install profile in a sense.


Taxonomy Menu: Display Descendants does not work

With taxonomy menu 2.0alpha2 if you select multiple you'll see the warning : "Multi-terms path is not available in Drupal by default, which means that you will have to register it using a module like Views for example."

Luckily views provide by default a taxonomy term view to emulate drupal default taxonomy term handling, so you need to activate it.
But even with this view activated you wont see your menu items, and this is because the path generated by taxonomy menu(ie: taxonomy/term/tid1+tid2 ) is still not handled.

This is because default taxonomy term view handle multiple terms ids argument but does not validate them (WTF !?).

So what you need to do in a nutshell:

  In taxonomy menu 2.0alpha2 module, select "Menu path type => Multiple terms"
  Activate taxonomy term view
  In [ Contextual filters =>  Content: Has taxonomy term ID (with depth) => Specify validation criteria => Filter value type ] change to "term IDs separated by , or +"

There you go !

ps : I did not try this with taxonomy menu 1.4, anyone ?


Is there a Drupal tool to aggregate and compress CSS files

I'm not 100% sure I'm right in thinking this, but if you're looking for something to reverse the CSS aggregation/compression, but if you are then it doesn't look like there is anything that exists that will give you exactly what was initially compressed. However, the cache Drupal creates is an array that is keyed by the original filename of the cached CSS, so you should be able to find out WHICH CSS files are being cached relatively easily (I think the variable_get('drupal_css_cache_files'); will get the array for you.

If you are looking to mimic what Drupal does when it aggregates and caches your CSS, then take a look at the drupal_build_css_cache() function (which, as an FYI, is called by drupal_aggregate_css()).

As a point of interest, there is also a drupal_build_js_cache as you'd expect.


Can't drupal_execute('filter_admin_format_form') on hook_install?

You can execute that code, but you need to give a unique name for the input format being saved.

As alternative, if you want to be sure there is an input format called Full HTML, you can save the input format in the database using db_query(), and using the code of filter_admin_format_form_submit(), the form submission hander for the form you are executing, as guideline.
The involved database tables are two: filter_formats, and filter_formats; the first contains the data about the input format, and the latter contains the data about the input filters associated with an input format. The relevant executed queries are the following ones.

  if (!$format) {
    $new = TRUE;
    db_query("INSERT INTO {filter_formats} (name) VALUES ('%s')", $name);
    $format = db_result(db_query("SELECT MAX(format) AS format FROM {filter_formats}"));
    drupal_set_message(t('Added input format %format.', array('%format' => $name)));
  }

db_query("DELETE FROM {filters} WHERE format = %d", $format);

  foreach ($form_state['values']['filters'] as $id => $checked) {
    if ($checked) {
      list($module, $delta) = explode('/', $id);
      // Add new filters to the bottom.
      $weight = isset($current[$id]->weight) ? $current[$id]->weight : 10;
      db_query("INSERT INTO {filters} (format, module, delta, weight) VALUES (%d, '%s', %d, %d)", $format, $module, $delta, $weight);

      // Check if there are any 'no cache' filters.
      $cache &= !module_invoke($module, 'filter', 'no cache', $delta);
    }
  }

In Drupal 7, it would be easier, as you can call filter_format_save(), which always save the input format passed as argument, and eventually merge the format you passed as argument with the existing one.

The function that shows the error you are noticing is the form validation handler,  filter_admin_format_form_validate(), which contains the following code.

if ($result) {
  form_set_error('name', t('Filter format names need to be unique. A format named %name already exists.', array('%name' => $name)));
}

As the form validation handlers, and the form submission handlers are executed when you call drupal_execute(), the same error is returned, even when drupal_execute('filter_admin_format_form', $form_state, $arg) is called from hook_init(); it just happens that the error message shown with form_set_error() is not immediately visible when hook_init() is invoked, but the input format is not saved.
To notice that filter_admin_format_form_submit() executes the following code.

  $format = isset($form_state['values']['format']) ? $form_state['values']['format'] : NULL;
  $current = filter_list_format($format);
  $name = trim($form_state['values']['name']);
  $cache = TRUE;

  // Add a new filter format.
  if (!$format) {
    $new = TRUE;
    db_query("INSERT INTO {filter_formats} (name) VALUES ('%s')", $name);
    $format = db_result(db_query("SELECT MAX(format) AS format FROM {filter_formats}"));
    drupal_set_message(t('Added input format %format.', array('%format' => $name)));
  }
  else {
    drupal_set_message(t('The input format settings have been updated.'));
  }

Supposing that the form validation handler doesn't return an error, the form submission handler is not saving any data in the "filter_formats" table, if the input format is not new; in such case, the function executes the else part of the control statement, which just output a message.


How to remove the comma between Link multi-value field

My suggestion would be to modify the way the links are displaying using the Display Suite module's field templates. Field templates gives you a high level of control over all the ways Drupal outputs the fields.

I found this tutorial that is pretty in depth, but in short you want to add the Display Suite module, enable it and the "Display Suite Extras" module that comes with it.

Next go to the display suite settings and enable "Field Templates." This is under Structure > Display Suite > Extras.

Once those are enabled, find the display settings for your content type (Structure > Content Types > YOUR CONTENT TYPE > Manage Display.

On that page, in the vertical tabs at the bottom you'll see an option to set a layout. Select "One column" or "Reset". Selecting a basic layout here will enable the additional features Display Suite offers.

After your layout is set, you'll see many more options on each field for how it is displayed. You can set the field template to "Expert" and you'll get control of the wrappers, prefix and suffix content (i.e. comma or no comma), and a lot of other stuff.

I hope that points you in the correct direction. Play around with DS a bit and I think you'll really like the control it gives you.


How do I get $entity in hook_form_alter()?

I think that it should be possible to do something like this.

if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity = $form_state->getFormObject()->getEntity();
  $entity_type = $entity->bundle();
}

UPDATE: In Drupal 7 it should be done like this:

$node = $form['#entity_type']; // E.g this could be, (#node, #user etc.)

Take a look at this site, drupal discussion.


How to join 2 views block with a views page

If I understand your question correctly, you want to display the result of a View into another View. You can do this by using the contributed module Views Field View:

  views_field_view allows you to embed one view into another view and pass arguments along

By using this module you can add an extra field to your View1 and View2, which shows the result of your View3.

===

In your updated question, Views3 has become a separate block. Using a contextual filter you can limit the rows to be only from a specific node (id), the one that is being displayed. The answer on How to associate the current Node ID when running from Block layout? should point you in the right direction, your contextual filter should be similar to the one you used in View1.


I went with only solution which came to my mind - foreach the view results, check the image fields and then apply image style and create derivatives. Because when view render image fields programatically it doesn't actually set the files in proper styles folder, it is done on browser request but this doesnt suit our use case.


Move content from field to field collection

You can do it with 3 step

In your content type, creat new field collection
Write one module, use function hook_node_presave(). In this function, you can copy data from old fields to new field collections.
Go to page admin/content. Select your content type. Select all node. In tab UPDATE OPTIONS chose Publish selected content and submit. This action to do run code your module write in step 2.


Intermittent Access Denied errors for anonymous users

Figured this one out, not particularly efficiently (never really found a good way to backtrace this), but got there nonetheless.

The issue was coming from the Custom Permissions module, which I'd incorrectly written off as innocent early on in troubleshooting since I use it on other sites without issue. Whoops.

That module lets you create permissions via a UI for any path you'd like. We had one in place that created a permission that was already defined by core (managing blocks -- accessing admin/structure/block). Removing this redundant permission fixed our problem here. (Uninstalling the module also fixed the issue.)

I'll post an issue in that module's queue if it's reproducible with a clean install.


View node public OR only to verified/role by choice user

Found a way to do this with tags. Feel free to add information about doing this with tags:

Added a taxonomy 'visibility' with 2 tags: public and closed.
Added to Contenttype a field with a selection-list (so, a user can only choose one).

(set it to requiered to only have 2 options.)
(in my case, i set the default to public.)

Enabled taxonomy-module 'Taxonomy Access Control'
go to admin/config/people/taxonomy_access >> anonymous >> choose [edit access rule]

(in my case it's admin/config/people/taxonomy_access/role/1/edit)

Under New >> choose the term 'closed' (or your equivalent like 'not for mother-in-law ;-) ).
Set everything to D (Deny)
When Content Access is also on, set grant priority to -1 on the   contenttype-page (admin/structure/types/manage/[contenttype]/access


How do I check if the user is watching the front page or the user is logged in?

I think you will want the following:

<?php if ($logged_in || $is_front_page): ?>
    Do something
<?php endif;?>


How to theme the node edit form to group fields into collapsible containers?

I would recommend you to first try the Field Group module that provides the option to do that kind of grouping and many more options.


View showing Teasers - getting path for full content in teaser template

Normally, you can access nid with $row->nid in your template.

From that, you can easily build the link to your node content with node/ . $row->nid path.


You can write your own WebformHandler to do so. Just extend WebformHandlerBase and write your code into the postSave() function. Here is a little example: https://gist.github.com/mharmuth/0ab021d5b65e4cab7c6efec951fc59e9

This class has to be stored in your custom module in the directory your_custom_module/src/Plugin/WebformHanlder/CreateUserHandler.php

After creating this handler, you will be able to add it in your webform under "Email/Handlers".

Hope this helps ;)


Migrated Servers now 500 Error _db_error_page('Access denied f...')

and set server settings to match old server

That process went wrong - ereg() was removed in PHP 7.0, and Drupal 6 couldn't have been running on a version of PHP that high on your old server.

I think PHP 5.3 is about as high as you're likely to be able to get with Drupal 6, you should get your server admin to downgrade to that version ASAP.


Using Views API to create a status field based on other field values (Sortable and Filterable)

I had started in the right direction this morning Thanks to this article:  Drupal 7: Using SQL Expressions in Views 3

This afternoon, after some digging, I found that you can manually join the tables that you need to work with in the same handler as mentioned in the article, and this expression field can be added to the "views" index of the data variable, and it will still be added to the base query.

So in, mymodule.views.inc

function mymodule_views_data() {
    $data = array();

    $data['views']['student_status'] = array(
        'group' => 'Content',
        'title' => t('Student Status'),
        'help' => t('The current status of a student based on when they we last interacted with, paid, etc...'),
        'field' => array(
          'handler' => 'mymodule_views_handler_field_expression',
          'click sortable' => TRUE,
          'expression' => "
                CASE
                    WHEN
                        field_data_field_some_table.field_some_value = 1
                    THEN 'Registered'

                    WHEN
                         DATEDIFF(NOW(), field_data_field_last_interaction_date.field_last_interaction_date_value) > 30
                    THEN 'Needs Attention'

                    ELSE 'Unregistered'
                END
            ",
      'expression_alias' => 'student_status',
    ),
   'filter' => array(
     'handler' => 'mymodule_views_handler_filter',
     'allow empty' => TRUE,
   ),
    'argument' => array(
      'handler' => 'mymodule_views_handler_argument',
     'allow empty' => TRUE,
    ),
   'sort' => array(
     'handler' => 'views_handler_sort',
   ),
  );

 return $data;
}

And then in mymodule_views_handler_field_expression.inc

class mymodule_views_handler_field_expression extends views_handler_field {
  var $expression_alias = 'unknown';
  var $expression = NULL;
  /**
   * Construct a new field handler.
   */
  function construct() {
    parent::construct();
    if (!empty($this->definition['expression'])) {
      $this->expression = $this->definition['expression'];
    }
    if ( !empty($this->definition['expression_alias']) ) {
      $this->expression_alias = $this->definition['expression_alias'];
    }
  }

  /**
   * Called to add the expression as a field to a query.
   * Overrides and based on views_handler_field->query().
   */
  function query() {
    // Make sure the table is available, and get the alias.
    $table_alias = $this->ensure_my_table();

    // Boilerplate from views_handler_field->query().
    $params = $this->options['group_type'] != 'group' ? array('function' => $this->options['group_type']) : array();

    //HERE'S THE NEW STUFF
    $this->query->add_table('field_data_field_last_interaction_date');
    $this->query->add_table('field_data_field_some_table');

    // Insert the table alias into the expression and its alias, and use the add_field method of the underlying query object.
    // See add_field() in views_plugin_query_default.inc
    $this->field_alias = $this->query->add_field(NULL, $this->expression, $this->expression_alias, $params);

    // More boilerplate.
    $this->add_additional_fields();
 }

}

ALSO NOTE:
In order to use this custom field in the Context Filter and Filter Criteria, I had to create custom argument and filter handlers to replace the WHERE statement with a HAVING statement, as well as, clean-up the alias that it uses.

Argument

class mymodule_views_handler_argument extends views_handler_argument {
     /**
   * Set up the query for this argument.
   *
   * The argument sent may be found at $this->argument.
   */
  function query($group_by = FALSE) {
    $this->ensure_my_table();
    $this->query->add_having('Content', $this->real_field, $this->argument);
  }
}

Filter

class mymodule_views_handler_filter extends views_handler_filter_string {

     /**
   * Add this filter to the query.
   *
   * Due to the nature of fapi, the value and the operator have an unintended
   * level of indirection. You will find them in $this->operator
   * and $this->value respectively.
   */
  function query() {
    $this->ensure_my_table();
    $field = $this->real_field;

    $info = $this->operators();
    if (!empty($info[$this->operator]['method'])) {
      $this->{$info[$this->operator]['method']}($field);
    }
  }

  function op_equal($field) {
    $this->query->add_having($this->options['group'], $field, $this->value, $this->operator());
  }

  function op_contains($field) {
    $this->query->add_having($this->options['group'], $field, '%' . db_like($this->value) . '%', 'LIKE');
  }
}


The redirection is happening before the login is processed, hence the error. The way I'd handle this would be to do the check when the profile page is viewed, rather than during the login process. So the trigger for the action is on viewing a page, specifying the user view page and adding a condition that the user being viewed is a seller.


Multisite or multiple sites setup with Open ID server

I think multisite would work well if you're keeping all of the same code.  I know you can do it with subdomains (or even completely different domains) using the sites.php file, I'm not so sure about sub-directories.

Have a look at the Features module which will allow you to import all of your standard settings as a single module on new sites.


Use superfish module for building your menu, and then whatever you type in your description depend on configuration will be print out too.

Under Advanced HTML Settings > Hyperlinks enable the "Include hyperlinks description (title) in hyperlinks text."

then simply add a display: block; style to the ul li a span to make it look the way you want.

you can see a demo HERE


Cron job stops when another one is running

It looks like ultimate cron can run parallel jobs.


You might consider the Workbench Access module: It is a hierarchy based approach to grants; it might be a much better match for your use case, and it can use a number of different hierarchy management tools, such as the Menu system, Taxonomy, etc.


How to show results from the last search?

You could try Search API Saved Searches Module

  This module offers users the ability to save searches executed with
  the Search API module and be notified of new results. Notifications
  are done via mails with token-replacement, their frequency can be
  configured both by admins and/or users and saved searches can also be
  created without first executing the search.

  Facet, Views or other filters set for the search will also be included
  in a saved search, thus reflecting exactly the same search results as
  displayed.


Security concerns with cache_get() and cache_set()

currently there are no known  bugs which would cause any security issue using cache_set and cache_get. You can put any values there
both key and value are escaped.
for example you can try this key '; drop table abr;--'
and it will be saved without any issues


Adding Taxonomy terms programmatically with specific tid?

tid will be assigned to the terms automatically by drupal. My suggestion is first create the terms then you can use taxonomy_get_term_by_name function to find the term and then map it to the respective node while importing.


banner image showing on all pages except forum and views result pages

A quick inspection of your html shows that the block is showing up.  However, the issue is you have a relative path in your img src, eg, you have this:

and that works fine when you are in the top level of your site.  But, when you go "down a level" it fails.  Changing it to:

should fix the problem.


The order's billing profile will always be authoritative on an order. If you want to be able to provide tax/shipping estimates, you have two options:

Use something like Commerce Cart Estimate to provide an estimate by request to a customer. This doesn't put it on the order, but simply provides the estimates in a block.
Take the result of the SmartIP lookup and stick it in the billing address on the order. That way when the customer sets the actual billing address, it will just override it and it will stick. You should be able to swing this with the Smart IP module since it has a rules integration. Just tack it onto the order if it doesn't already have a billing address. Then, let commerce's rules do the rest and output the order's values.

Something that isn't out of the box would be to ask the user: Pop up a box or a block somewhere on the page that asks them to verify their country/postal code.


how to render html link within dsm message?

You can't with dsm() I'm afraid, it's run through Krumo which encodes any special chars into HTML entities. Check out the dpm() documentation (which is called internally by dsm()) and follow the function trail through and it'll make more sense.

You'll have to resort to good ol' drupal_set_message():

$loglink = l("logs", 'admin/reports/dblog');
$msg= "See $loglink for watchdog messages";
drupal_set_message($msg);


The theme location moved to /themes, while the core themes moved to /core/themes.

This is how the directory structure looks like in Drupal 8.


You can implement custom relationship using hook_views_data_alter() and define exactly in this hook which fields to use for JOIN - https://api.drupal.org/api/views/views.api.php/function/hook_views_data_alter/7

Example:

/**
 * Implements hook_views_data_alter().
 */
function custom_log_views_data_alter(&$data) {
  // Expose uid as a relationship to users.
  $data['custom_log']['uid'] = array(
    'title' => t('User information.'),
    'help' => t('Information related to user who triggered the event.'),
    'relationship' => array(
      'base' => 'users',
      'base field' => 'uid',
      'relationship field' => 'uid',
      'handler' => 'views_handler_relationship',
      'label' => t('User information.'),
    ),
  );
}


What is the purpose of modulename.api.php?

An .api.php file contains the hooks that a certain module supports, and is available for reference.

It offers documentation and example code on how to use the hooks in other modules. It is not specific to Drupal 8 as several modules in Drupal 7 offer it as well.

It does not actually implement or call the hooks and is for reference only.

As for an example of how to write it, it depends on the different hooks your module implements. Explain the different input and return parameters, adding additional data alterations as you see fit.

search.api.php is one of many examples in core. Hooks are either invoked, as for example, in common.inc:

$updaters = \Drupal::moduleHandler()->invokeAll('updater_info');

That is the the current way in procedural code. In object-oriented terms, with Dependency Injection, refer to this example in ModuleInstaller:

$this->moduleHandler->invokeAll('module_preinstall', array($module));

There are also alter hooks, like this one in BreadCrumbManager:

$this->moduleHandler->alter('system_breadcrumb', $breadcrumb, $route_match, $context);


solution: you can access the fields with 'content'

e.g. content.body or content.your_field_name.value

in a iteration it looks like:

  {% for item in content['#view'].result %}
      {% set topic = item._entity %} {# just for shorter writing #}

{{ topic.title.value }}
 {# or topic.yourFieldName.value #}

  {% endfor %}

Hope it'll help


Drupal 7 Views Question - How to pass 2 arguments

I think I know the answer.

I suppose the path to your view without any arguments is "organization".

So first you need to add the contextual filter "department" to the "attachment"-display too. This filter needs to be in first position.

Then:

When filter value is not available > check "Provide default value" > type= Raw value from url> Path component= "2" > save this filter.

Next:

Still inside "attachment"-display open up contextual filter "Content: Title" and change Display a summary > Base path to "organization/%/department/%/staff-listing".

Hope this helps


Unknown map column when migrating users from CSV file

The 'Column not found' (map.sourceid4) error sounds like migration table related to source mapping is not complete.

You should identify the table (e.g. using drush command):

drush sqlq "SHOW TABLES LIKE 'migrate_map_%'"

Note: You can also execute above in SQL editor by using quoted part only.

and check the list of available columns for that table:

$ drush sqlq "DESC migrate_map_foomigrateusers"
sourceid1   varchar(128)    NO  PRI NULL
sourceid2   varchar(128)    NO  PRI NULL
sourceid3   varchar(128)    NO  PRI NULL
destid1 int(10) unsigned    YES     NULL
needs_update    tinyint(3) unsigned NO      0
rollback_action tinyint(3) unsigned NO      0
last_imported   int(10) unsigned    NO      0
hash    varchar(32) YES     NULL

The number of sourceidX column should match with number of columns in CSV file. If they won't, probably you've modified the CSV file and after each structure change you have to re-register your migration class (see: hook_migrate_api).

So please reregister any statically defined migration classes by (check list by drush ms):

drush migrate-deregister FooMigrateUsers
drush migrate-register FooMigrateUsers

In case of further problems, these drush commands can be handy as well:

drush migrate-mappings --all # To verify mapping.
drush migrate-fields-source --all # To list source field mapping.

When ready, try re-importing the data again:

drush mi FooMigrateUsers


If you don't use sub themes of Aegan, you need edit file aegan.theme

Add more use class at top:

use Drupal\image\Entity\ImageStyle;

Replace code line 53->73

if ($slideshow_path && $show_slideshow) {
    $vars['slider'] = array();
    for ($i = 1; $i <= theme_get_setting('slideshow_count', 'aegan'); $i++) {
      $fid = theme_get_setting("slide_image_{$i}", "aegan");
      if (!empty($fid)) {
        $file = \Drupal\file\Entity\File::load($fid[0]);
        $uri = $file->getFileUri();
        $image_path = file_create_url($uri);
      }
      else {
        $image_path = THEME_PATH . "/images/slide-{$i}.jpg";
      }
      $vars['slider'][] = array(
        'name' => !empty($fid) ? $file->getFilename() : "slider-{$i}",
        'url' => theme_get_setting("slide_url_{$i}", "aegan"),
        'src' => $image_path,
        'description' => theme_get_setting("slide_description_{$i}", "aegan"),
      );
    }
  }

with

if ($slideshow_path && $show_slideshow) {
    $vars['slider'] = array();
    //replace large with image style you want
    $image_style = 'large';
    $image = ImageStyle::load($image_style);
    for ($i = 1; $i <= theme_get_setting('slideshow_count', 'aegan'); $i++) {
      $fid = theme_get_setting("slide_image_{$i}", "aegan");
      if (!empty($fid)) {
        $file = \Drupal\file\Entity\File::load($fid[0]);
        $uri = $file->getFileUri();
        $image_path = $image->buildUrl($uri);
      }
      else {
        $image_path = THEME_PATH . "/images/slide-{$i}.jpg";
      }
      $vars['slider'][] = array(
        'name' => !empty($fid) ? $file->getFilename() : "slider-{$i}",
        'url' => theme_get_setting("slide_url_{$i}", "aegan"),
        'src' => $image_path,
        'description' => theme_get_setting("slide_description_{$i}", "aegan"),
      );
    }
  }


This is indeed a way to check if it is the front page and should return a value if you check the method code.

I am using it in a few preprocess hooks:

$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();


Using drush to change options of contrib module

Check to see if the contrib module has a modulename.drush.inc file in it.  If it does, then the module provides Drush commands, and you can find out about them via drush help --filter=modulename.

If the command does not supply any Drush commands, the next thing to do is to open up the modulename.module and scan through the source code, and see if it has any API functions that perform the operation that you want to do.  This can sometimes seem intimidating, but it's worth a shot!  If you'd like to set the frobulation level of the module to 28, maybe, just maybe, you might find a line that reads function modulename_set_frobulation_level($value) ....  If you do, then you can call it with Drush like this:

drush ev 'modulename_set_frobulation_level(28);'

If you do this a lot, you could make a Bash function for it, or, better yet, create a custom Drush command and contribute it back to the contrib module.  Making a custom Drush function is really easy with the drushify command.

If you are unlucky, you will not find a nice set_frobulation_level function; sometimes, the code you want is only available in a form submit handler.  This is distressingly common in contrib modules.  Rather than try to figure out how to post a fake form submit, an even better option is to just factor out the code you'd like to call, and make the modulename_set_frobulation_level function yourself.  Then, it's easy to create a Drush command for it, and you can contribute the whole shebang back to the contrib module when you are done, helping out the next person who travels this same road.

This might sound like a bit of work, but it's no harder than reverse-engineering the sql commands you'd need to run, and the results are much more satisfying.


How can I allow anonymous visitors to submit content?

Create another content type, say "Event Suggestion", which contains only those fields you want anonymous users to submit suggestions for. Do not include the fields you consider as not relevant (and which you want to 'hide' for such anonymous users).

When creating such extra content type, for its fields just use the same fields as for the content type that you already have, say "Event". So the fields for this new content type (Event Suggestion) will be a subset of the fields that you already have for the content type already being used by your "small group of users" (= Event).

Related to permissions: allow anonymous users to create an Event suggestion, but do not allow Event to be created by anonymous users.

For spam reduction/prevention, use modules such as Honeypot, Mollom, Captcha, reCaptcha, etc.

Use the Rules module to finetune your workflow related to nodes of type Event suggestions being created (saved). To just mention a few options (the list is virtually unlimited):

Unpublish such nodes (so that spam submissions that are not caught by spam prevention modules, never get shown without reviewing them first).
Send an eMail msg to your small group of users who manage your site (something like "a new Event suggestion is waiting your approval".
Set some kind of "confirmation message" when an Event suggestion is beiing submitted (like "Thank you for your Event suggestion, it will be reviewed soon ...").

When your small group of users who manage your site then review such Event suggestion, they should use the Node Convert module to convert an Event Suggestion into an Event. Using the Rules module you could then automatically "publish" such event also. After such node got converted, your small group of users who manage your site could then complete what you described as "add more details later on".

Other modules like Flag and/or Content Access might further enhance the various features / functionality you might be looking for. E.g. as an alternative to working wirth "unpublished" content, you could work with content that is published, but can only be accessed by authorized users.

Bottom line: Rules and Node Convert could get you pretty close, possibly further enhanced with Flag and Content Access.

Note: Adding the View unpublished module seems like an interesting improvement also, i.e. to grant access for specific user roles (such as editors or reviewers) to view unpublished nodes of a specific type.


Get "File Upload Error" when I try to upload any images to Node

There is a long thread in the Drupal.org site surrounding this issue, I didnt locate it at first due to my error message being masked. After many hops around the net I did finally locate it, and it seems to effect quite a few people.

See this link

http://drupal.org/node/1002048

post #154 has a link to the patch for both version 7 and 8 of Drupal.


Is it possible to use tokens in a menu link in Drupal8?

No, you cannot use tokens in menus out of the box.

Here are some options:

Use Views to create the link.  This won't give you a menu, but you can make a block in Views and use that as a menu.  You may have to hard-code the rest of your "menu" in the views block, which isn't ideal but if you can't code that may be your best option for now.
Code the menu link.  See the routes documentation.
Watch the progress of the Menu Token module.  This module does what you want but it doesn't have a stable release for Drupal 8 yet.  I haven't used the D8 version so I don't know how well it works at the moment.


There can not be a permission issue in your code (because you code is very simple:) ). Just try to change your code as documentation says:

function bcompanies_menu() {
    $items = array();

    $items['company'] = array(
        'title'     => 'Company',
        'page arguments'    => array(), // I removed arguments because of callback function doesn't require in your case;
        'page callback' => 'company_page',
        'access callback'   => 'user_access', // I changed your access callback, it's a bad practice to set just TRUE as an access callback
        'access arguments' => array('access content'),
        'type'          => MENU_CALLBACK
    );
    $items['company_page2'] = array(
        'title'     => 'Company',
        'page arguments'    => array(),
        'page callback' => 'company_page',
        'access callback'   => 'user_access',
        'access arguments' => array('access content'),
        'type'          => MENU_CALLBACK
    );

    return $items; // I added this line, because I don't know you 're returning a value in your module or not..

}

function company_page()
{
      return 'hello world';
}


If you enable the settings documented in example.settings.local.php then you can easily see the cache tags that are present on a page.

What you will see then is that each rendered node has the node_view cache tag, so you only need to invalidate that.

There's also the 'rendered' cache tag which as added to any render cached item.

I don't quite understand why your cache warmer needs to invalidate the cache first, shouldn't be a problem if it's already warm? Drupal will automatically invalidate something if it is no longer valid.

The internal page cache also has no time limit by default.


getting a target_id value for for users in particular node drupal 8

Looks like this one has to be solved this way

  $members = $node->field_members;
  foreach ($members as $member) {
      $members_ids[] = $member->getValue()['target_id'];
  }


How do you get the last star to be only star shown in a rating?

I haven't used Fivestar but if you use rate it has an option to show the users vote. Rate has a fivestar widget as well.


Set value of a webform field programatically

I don't know if your problem could be solved in an easier way. A lot of our solutions at my workplace seem equally convoluted. In fact, we use WebformSubmissions to hold a lot of submitted data.

Here is how you set a value in a WebformSubmission:

Load the submission.
Get the submission's data as an associative array.
Change the submission's data however you want.
Set the submission's data to this modified array.
Save the submission.

Here is the code:

use Drupal\webform\Entity\WebformSubmission;

// $sid contains the submission id
$submission = WebformSubmission::load($sid);

$data = $submission->getData();

// you can find the machine name in the devel tab
// or just do what I do and var_dump($data);
$data["field_machine_name"] = "new value";

$submission->setData();
$submission->save();


You can use  the --source flag to provide your own xml release history file containing paths to your own gzips. (drush dl drupal defaults to http://updates.drupal.org/release-history/drupal/7.x.)

Sadly I don't think you can specify a local repo, or even a remote repo as the source of a project for dl. Drush expects a gzip file to download and unpack. You could however write your own drush command that takes a local repo path, gzips it, and passes the gzip to dl.


Yes you can

Computed Field is a very powerful field module that lets you add a custom "computed
fields" to your content types.

  These computed fields are populated with values that you
      define via PHP code.


How to change url webform entry textfiled to link in views?

Add the component value which stores the URL to your View. Configure the field and choose to 'exclude from display'. Add a new custom Global: custom text field to your view. Choose Rewrite results -> output this field as link. In the link path field choose the URL component value from the replacements values list.


How to Migrate static html files to Book - Migrate Module

A full description of this process would fill a lecture series.  However, the broad approach I would take follows. This approach also has some assumptions that need to be met.

You will need to be able to code
You will need to know, or learn (it's not hard) XPath
The files are in a structure that allows you to recognise where they live in a book (either by links from file to file or path/filename or a combination.

If these conditions are met then import_html is where I'd start.  This will require you have the ability to write a module (that will use this module) and there is a bit of a learning curve, but learning this is well worth it.  If you're already able to import the files it sounds like you're up to speed with the skillset needed.

One of the things that import_html will also allow you to do is update nodes if they're already present too.  Although my experience with this has always been with blowing away the content and rerunning the import to see how any changes went.

I've been involved with a few projects that used this and imported many content types and media from static source dumps.


Drupal has a built in "poor man's cron" which is invoked on a schedule when regular users visit pages.

Setting up a proper crontab entry (and turning off poor man's cron, i.e. set it to "Never") is usually the best thing to do.

If you set both, the poor man's (in-built) cron and also add a crontab entry to ping the cron URL, then yes the cron will run twice.


How to store information in session for anonymous user in a site without a user with uid=0?

If you "have to store some information in session for anonymous users", then you will have to make uid=0 available to Drupal. Because that's the uid that Drupal always uses for anonymous users.

So you'll have to re-create that user with uid=0 (again) if you want this to work. If you would combine this with not granting any permissions to role anonymous, there is not a lot that anybody can do in your site if they are not logged in (apart from things like performing login). Maybe an acceptable work around?

About your "for some reason we have deleted user with id=0": it might be that the user with id=0 never got created before (so that it was never deleted). E.g. if the database of your site was created via some type of database copy (backup and restore) from a dev site to a prod site (using PhpMyAdmin). Forgot the exact scenario, but I've ran in such sites before, which caused problems for anonymous users (which is how we discovered such cases). The solution we used was to simply use PhpMyAdmin, and insert the user with uid=0 in the Drupal database (using PhpMyAdmin).


More information than standard "Site Details", also to be available as tokens

I wrote a tutorial on most of this: http://www.jaypan.com/tutorial/drupal-8-extending-core-configuration-extending-core-forms-and-overriding-core-routes

I didn't get into creating tokens for the new items, but you can do it by implementing hook_token_info_alter() and declaring the new tokens as part of the site tokens, and implementing hook_tokens_alter() to set the values from the config you create following the tutorial.


You can use panel page for this.
Create a panel, set it is as front page and pull the things you want to pull like blocks, views, nodes etc.


What are "Text format" option in standard Drupal?

"Full HTML", "Plain Text" and "Filtered HTML" are default Textformats in Drupal, they determine which elements are allowed in the input and what gets filtered.

The wysiwyg editors only add UI controls to the field so user don't need to know HTML to style their output. If you don't want anonymous users to use formats like 'full html' you can turn it off in the permissions and give access to full html only to administrators or roles you trust.


How to export field's default image in Features

Try the Default image ft module looks like it is what you need.

Remember when you wanted to featurize that default image for that profile picture? Yeah, that's not possible, because the feature would save a fid in its code, and we all know it's not good to have id's in features. Plus, the website manager might want to change the default profile picture.


Change values of nested fields with entity_metadata_wrapper

Using what Clive mentioned and with the hint eikes provided, this seems to be a way to accomplish what I want:

$nid = 108501;
$node_wrapper = entity_metadata_wrapper('node', $nid);

for ($i = 0; $i < count($node_wrapper->field_image->value()); $i++) {
  $node_wrapper->field_image[$i]->file->field_source->set('NEW SOURCE');
  $node_wrapper->field_image[$i]->file->field_license->set('NEW LICENSE');
  $node_wrapper->field_image[$i]->file->save();
}

// Just for dev: Check if the values have been saved
$node_wrapper = entity_metadata_wrapper('node', $nid);
dsm($node_wrapper->field_bild->value());

Erroneously I used the save() call on the whole node wrapper, but as files are their own entities, the call needs to be on the file, as eikes suggested.

Additionally, I noticed that calling $node_wrapper = entity_metadata_wrapper('node', $nid); after the above code doesn't reflect the changes (for checking). It seems I need to reload the entity first.

Thanks a lot to both of you!


Views date exposed filter by year in checkboxes

You can construct the Exposed Year filter yourself using the Grouped filters option:

Add your Date field Filter and Expose it
Select Grouped filters under Filter type to expose
Tick Allow multiple selections
Select Radios under Widget type
Adjust the Label and Description if you need to
In the items table change all Operators to Is between and configure each year like so:

 2019   Is between   2019-01-01
                     2020-01-01

 2018   Is between   2018-01-01
                     2019-01-01

 2017   Is between   2017-01-01
                     2018-01-01

 ...

and so on for all the years. The times are assumed to be 00:00:00.

You don't have to use the Better exposed filters, they may interfere with the display of the grouped options.

BTW this issue may be relevant: Grouped exposed filter with "Allow multiple selections" ignores widget setting


Simple key => value array with QueryInterface

The only way I know to do this is similar to what @Ivan Jaros mentions in the comment above. That is to use a Database service instead of EntityQuery service. There is a handy method on the query Statement, fetchAllKeyed, that I use all of the time in Drupal 7.

$database = \Drupal::service('database');
$query = $database->select('node', 'n');
$query->join('node_field_data', 'nfd', 'n.nid = n.nfd.nid');
$query
  ->fields('n', ['nid']),
  ->fields('nfd', ['title'])
  ->condition('n.type', 'product')
  ->condition('nfd.status', 1)
  ->execute()
  ->fetchAllKeyed();

Unfortunately this has drawbacks:

Multilingual - you need to do this manually in the query above.
Probably not going to work well with non-SQL drivers.
Might run into performance issues still because the data is not cached.


How to allow users to unsubscribe from organic groups?

Use this link:
http://sitename.com/og/unsubscribe/gid/uid

gid = group id
uid = user id

====== second option =======

Go to "Manage membership" or "My membership". click on "Leave this group"


ContentEntityForm buildForm method parent out of memory

Are you sure this is a coding error? Are you loading any large quantities of content in the form by any chance? Loading a lot of nodes in a select field, for instance, can generate memory overflows.


How do I add a custom class to a field based on another field value(boolean)?

I've never used the commerce module but that sounds possible, you need to create a module for the hook to be triggered from.

Then, with the devel module installed use dpm($build, $type) within the hook to see the correct names (I've put in dummy values in CAPS) and do something like:

function MYMODULE_entity_view_alter(&$build, $type){
  if ($type =='product') {
    if (isset($build['SALE_PRICE']['VALUE'])) {
                $build['PRICE']['attributes']['class'] = array('on-sale');
            }
        }
    }


sounds like colorbox_node might be the module you want.

  Gives the user the ability to display ANY page inside a colorbox modal
  without the header and footer. Those pages include:

  Node Pages
  User Pages
  Views Pages
  Webforms (requires Webform Ajax Module)
  Integration with Views
  Integration with Context
  Integration with Panels


At this moment in my team, we have identified 3 bugs around this, and to make this works you need to apply this 3 patches:

https://www.drupal.org/project/drupal/issues/2751269#comment-12559117

https://www.drupal.org/comment/12521645#comment-12521645

https://www.drupal.org/comment/12561153#comment-12561153


Column not found: 1054 Unknown column 'revision.revision_user' in 'field list': after Update from 8.2 to 8.4

As per this comment, this could be related to Dynamic Entity Reference module as per this bug report.

The solution is to apply this patch or upgrade to the latest version of this module.

To fix the problem manually, you need to rename the field in the database from revision_user to revision_user_int.

Another suggestion from here says to add: $settings['update_free_access'] = TRUE; into your settings file and run /update.php to invoke the database updates again.


Sounds as you need Views Dynamic Fields. From the project page:

The Views Dynamic Fields module provides a filter for use with Views module. This filter allows the user to pick and choose which fields to display for a rendered instance of a view for that user. This provides a customized view instance for each user.
This module provides additional advantages when used with the Views Bonus Pack module or the Views Excel Export module to generate an xls file from a view. The xls file will only display the fields you have chosen on the rendered view instance in browser.


Commerce price attributes doesn't work when I use commerce discount for products

I found the solution of this problem. In order to avoid this error, you must set order for your discount.

for the field order (with description : Discounts will be sorted by this value to be evaluated in that order.)
set the discount on 1 (or the lowest amount in the select box)

this will fix the problem.


How to update the below action for each view bulk operations? It is for Drupal 7

If you define a VBO event in rules that triggers on every node save, then it will happen once per node saved by VBO.  VBO takes all the selected items in a view and runs them through a batch process, performing operations per item.
So, you need to change the rule event to something else.
If the goal is to run the code once per time, here is one lazy way to do it:

Set the event to be "page is viewed". (doing this from memory, actual event name is different)
Set a condition on the rule to be the path of the VBO page.
Use your execute PHP code as the action.

This will cause the code to execute whenever the VBO url is accessed.  This is not exactly what you asked for, but hopefully this gives you an idea of how to use events and conditions in rules to get what you want.


Writing PHP into views field template twig

You can write Twig directly into your view with a Custom text field.

Using Twig as an entry point, you can use all of the Twig functionality and filters that ship with Drupal, as well as expanding on these with modules like Twig Tweak and Twig Field Value. You can also write your own Twig extensions, which are written in PHP. Here are two suitable tutorials:

https://opensenselabs.com/blog/tech/twig-extension-drupal
https://medium.com/@yuseferi/how-to-write-custom-twig-filter-in-drupal-8-1c2981dbf1e3


Render a custom form in a custom template

You need to render your form in the template. Simply calling drupal_get_form won't suffice. To render the form use following:

drupal_render(drupal_get_form('form_nam'))

You also need to ensure the following:

In your custom form #theme parameter is set to appropriate theme function.

Further the hook_theme implementation is correct.

Refer this link for a working example


How to apply patch file to views module in Drupal 7

If it is a standard Drupal patch, you use a program named git (part of ambience in most Gnu/Linux configurations) to apply it.  The correct procedure is to first clone the newest released version of the project, apply the patch, then install the patched version in the views folder.  If the patch file is named views-bugfix.patch you download it, and then:

git clone --recursive --branch 7.x-3.x http://git.drupal.org/project/views.git
git apply -v views-bugfix.patch

In some cases, the patch is not for the released branch, but some other branch (this will be mentioned along with the patch).  In that case you need to clone this branch instead.

Source for this info.

If you're stuck in a Microsoft environment and don't have git here is something that may help you: Patching in Windows (haven't tested this myself - I don't do windows.)


How do I calculate the days difference between start and end date of a date range field in Views PHP?

Within Views PHP, there are 2 fields. The value code field and the output code field. The first is used to calculate the value (for filtering, sorting, etc). The second is used to display the value.

So in the first field you'll have to perform your calculations and return the final value. If your field is numeric, try to only calculate the number here. Prefixes and suffixes can be added in the output field. (So the value for this field could be 3.)

In the output field you again have to return the final value. This can be the same value as calculated in the value field (there is a token for this value). But you can also append pre- and suffixes and return a string. (Here you can for instance append days to the value to have it display 3 days.)


How to add custom field to content view?

View module doesn't have access to the custom tables by default, but you can fix it using hook_views_data function. More information you may find here http://www.sitepoint.com/exposing-tables-views-drupal-7/


Redirect taxonomy term page links to a View page's exposed filter

After some trial and error and guesswork I've got it working using Page Manger (part of the cTools module):

Under Structure > Pages, Enable and Edit the Taxonomy View page - if there isn't one, you  might need the Page Manager Existing Pages module
Create a "HTTP Response Code" variant
Select "301 Redirect"
For the default pattern, enter something like:

  pagename?%term:vocabulary:machine-name[]=%term:tid

Test this. There might be cases where the field name stub used in the exposed filter doesn't match the actual vocabulary machine-name and where editing this in Views isn't a good option. For example, I had one field named "colours" not matching its underlying vocabulary "colour". You might also have exposed filters using strings like field_fieldname_tid which you might have reasons to not change. If this happens:

Go back to "Summary" in Page Manager for this override
Click "Add new variant"
Give it a sensible admin title (e.g. the vocabulary name) else you'll hit an error later on as it'll match the default name
"HTTP response code" again, and tick "Selection rules"
Choose an appropriate selection rule (probably, "Taxonomy: Vocabulary", then tick the awkward vocabulary), continue
Choose 301 redirect again, and enter the same pattern as before but with the token %term:vocabulary:machine-name replaced with the string used by the exposed filter, for example pagename?colours[]=%term:tid


7 mysql workbench get the values of entity reference fields of a content type in a node page

Yes it is absolutely possible, and your query you posted is written correctly. If you are returning 0 rows that means there are no records inside the table field_data_field_media_file. Your query literally says to return everything in that table, and 0 things come back.

Review all of the tables in your database and make sure "field_data_field_media_file" is what the field is actually called. Either you are looking at an old/wrong field OR there is simply no nodes with this entity reference field populated.

for your reference the tables relate like this:

The parent node that has the reference

{Node}.nid => {field_data_field_media_file}.entity_id

The node that is being referenced

{field_data_field_media_file}.field_media_file_value => {node}.nid


How do I simply make the whole site use a secure connection?

If you want to redirect all of your pages to be forced to use SSL then add this to your .htaccess file.

# Redirect to HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This should be placed directly after RewriteEngine on if you have no previous rewrites.


How to keep labels displayed for all facet filters

Try to set this option

on facet settings form.


what is the difference between render() and drupal_render()?

The docs for render() explain it pretty well:

  This function renders an element using drupal_render(). The top level element is shown with show() before rendering, so it will always be rendered even if hide() had been previously used on it.

render() is basically just a wrapper for drupal_render(), except that it makes sure the element passed in is set to be shown when passed through to drupal_render().

It also makes sure the element passed in is an array (which is all drupal_render() can accept). If it isn't, the element is return back as-is. So it provides a bit of a safety net if you like.

If for any reason you have a variable you need to render, and you don't know if it's a string or a render array, you can pass it straight through render() without having to test the variable type yourself.

For some real-world examples of that sort of situation there's a list of calls to render() you can look through.


How to add new content using a content type added after taxonomy access control was installed?

Have a look at the Community documentation of the Taxonomy Access Control module. Especially what it says about the Global default (within Global and vocabulary defaults), i.e:

  The global default, at the top of the form, determines the grants the role receives for untagged nodes (including nodes with terms that are not in controlled vocabularies). Keep in mind that access is denied by default, so if you want TAC to grant a role access to untagged nodes, set the global default to allow for that grant and role.

See what happens if you adapt this default. If the issue persists, then you may want to perform TAC troubelshooting, possibly even Troubleshooting with Devel.


How to show Comments (created with entity form) only to the Admin user and logged in?

You might try updating PERMISSIONS.  By default, EntityForms only allows administrator to view, edit, or delete.  If you want a user to be able to view their own EntityForm submissions, you have to update the permission for this.  You can find it under PEOPLE->PERMISSIONS->EntityForms->View own entityform submissions-> [check] AUTHENTICATED USER.

Good Luck!

Chrisjan


How to create a views display that is not a block or a page?

May be you can create Attachments for the view.


How to examine existing field values and modify other field in hook_form_alter?

In node edit form $form_state['node'] contains full node object , from which will get the existing field values.


You can add something like this to your theme style.css file

.pretty-event-title a{
  font-size: 14px;
  color: red;
}

More info: http://www.w3schools.com/css/


Tree structure based on parent-child relationship among content types

I think there is a lot more to unpack here than it seems at first sight.
Usually when we talk about inheriting things it's actual data referencing other data (sets of data), it's not structures inheriting structures automatically.
Just because a laptop shares properties with a computer doesn't mean that a laptop node will reference a particular computer node, so it's not data referencing data.
Although you can choose to implement things in different ways, and there are usually reasons why you should go with a chosen option, I think in this case it makes the most sense to create a separate structure for each data set that is "standalone".
Without any other info about your site, assuming from your current description and my past experience building sites I would structure it this way:
Content types and their fields:
COMPUTER
- processor
- RAM
- (...)
LAPTOP
- processor
- RAM
- battery
- touchscreen?
- screen size
- (...)
TV
- screen size
- contrast ratio
- resolution
- refresh rate
- (...)
BOOK
- author
- title
- genre
- publication date
PRODUCT
- price
- weight
- URL
- !! Entity Reference Field !!

Notice the computer fields in laptop that are the same as in computers are repeated under laptop. You can reuse existing fields, I recommend you do especially if you plan to do any comparisons between different nodes that may be different category product but share the same properties/fields. But there are no field references between computer and laptop, they are independent from each other, even if they share some properties.
Different product categories have different product properties, and it makes sense to keep them separate.
When selling products they all share the same properties with regards to selling, and when selling a product you're selling one set of data, not the structure. You're selling one specific computer, not category of computers in general.
That's why it makes sense to have the saleable entity as a separate structure, and you pull specific data from a particular node that exists of some product category.
Through the Entity Reference field you can show entire node information on the Product node that references it.
Structurally you could have a specific computer node, lets say node ID 5 with all the computer fields describing it (RAM, CPU).
Then you would have another node, of the Product type, node ID 6 for example, that would list the price and reference node 5. Node 6 would show everything on its page. Node 5 can even be hidden from public, better SEO whatnot...
With the module Inline Entity Form (which was created with excommerce in mind) or some similar solution you can solve the editors problems of having to first create the "computer" node before creating the "sell computer" node. With this module you will be able to create both at the same time, in one go.
This way you're fast when entering content and maintaining your site, while your structure is still flexible enough that it's easy to create different lists you might need with Views (using Paragraphs and keeping everything in the same type can hinder you there) and you can change things in one place because it's all kept in sane compartments.
For example if in the future you need to add some sales tax field you can do it on the Product type and it will appear for all saleable products, you won't have to edit many CTs (in case you have them all separate without ER to product) and you won't have to do complex Views to gather different Paragraph interconnections just because you have everything in one Conent Type.
If you've read it, I think it will help no matter what you decide because it at least gives you some other considerations to think about. If I've been clear enough that is :þ


Webform 5.x lookup validation via data table lookup

Webform elements support unique value validation, which I should be able to address your requirement. If not, you may need to write a custom form alter hook with a custom validate callback.


How do I save the values for a custom fieldset?

One way to do it would be in hook_form_alter add a custom validate handler:

$form['#validate'][] = 'my_custom_validate_handler';

then you should be able to do (double check that with debug(), print_r() or devel):

function my_custom_validate_handler(&$form, &$form_state) {

    $form_state['values']['group_access']['und'][0]['value'] = 1;

}

Another way would be to set a '#default_value' and it should be something like that:

$form['group_access']['und'][0]['default']['#default_value'] = 1

Hope that helps!


AFAIK there's no module which does this out-of-the-box for organic groups - the User Relationships module does this for users (https://www.drupal.org/project/user_relationships).

To achieve with groups, you could set up a similar system with flags and rules, i.e. someone can flag a group as a 'friend' or whatever, when they do, a rule sends a confirmation link to the friended group and they can then say they are friends with the other group (also using a flag). But I don't see why you'd do that as every person on the site is a user so you'd need to work out who has the ability to 'friend groups'.

A general observation - if you've looked around a lot for the functionality and it's not there, and it's fairly generic functionality (like 'friending') then you may be thinking in the wrong way about the problem and the problem may be solved by thinking about it different architecturally - I've been using Drupal for 8 years now and not had issues finding modules which fit to do the stuff I want to do.

HTH

Steve


VIEWS: How can i Related (CONCATENATE) current_user to content fields?

You can create a Relation (on the right side), Here you can link to a author. Create a filter that filters on the current loged in user. This should do the trick.


On content edit, how can I check/select a bool field based on which tab is active?

You can do it with jQuery, something like this should do it:

$('.single-class').click(function () {
    $('.bool-class').prop('checked', true);
});
$('.multi-class').click(function () {
  $('.bool-class').prop('checked', false);
});


Best practice caching a variable between page loads

A) I highly recommend to measure your assumptions. Database might not be as bad as you think. The answer also depends on whether you ask for a sites that you control or whether you are writing a public module that has to play well with the whole ecosystem.

The main difference between variable_set and cache_set is how important the value is. Cache is intended for things that can be generated. Another difference is how modules interact with in. There are alternative cache backends, which won't write the value to the default database but typically some type of key-value store.

B) The $_SESSION variable from PHP can certainly be used by a Drupal 7 module. By default, PHP saves the session as a file in the local file system.

You can also use key-value stores such as Redis or APCu.

C) A class sounds much better from the perspective of testability via PHPUnit, but singletons don't play well with testing either.


If it's drupal 8, which sounds like it, your libraries folder needs to be outside of the sites folder. Where you main Drupal stuff is, like the modules folder.

ex: Needs to be drupal/libraries and not drupal/sites/libraries

The drupal/sites/libraries is only for Drupal 7.


How can I use stemmer with Search API Solr but show non-stemmed results in the autocomplete form?

This is not a "best practice" answer but it might help you get an acceptable result (at least till you figure out how to solve this):

Enable just the GreekLowerCaseFilterFactory in your schema.xml (not the stemmer).
Use the NGramFilterFactory to get partial results in your keywords. You can find information on how to do this here.


Can the Autocomplete delay be lowered in forms?

As Clive suggested in a comment major part of the delay is because of the time taken by your server to populate the dropdown list. This generally happens because Drupal has to load all the enabled modules and do a complete Drupal bootstrapping.

In special cases like Autocomplete responses that may not be necessary. Hence you can load only what is required and do a minimal Bootstrapping.

You can check out the details of how this is done on this page.

Note : This involves custom coding and will not to perform any access checks unless you manually do it.


Select and trigger popup on marker via javascript

you can select whether you want a Popup to appear on a MouseOver event or on a MouseClick event, go to Admin - Structures - Openlayers - Maps, edit the map you are using and you can change these on the 'Behaviors' tab. Hope this helps.


Programmatically set the default value for a field

Assuming that your form alter function is actually running (which you can confirm with that call to dsm()), there are actually 2 more levels of array you need to go down to in order to get to the field element:

$form["field_accounts"][LANGUAGE_NONE][0]['value']['#default_value'] = $default;

In Drupal 7 you have a an array of values for each language the field has been translated into (so that fields with multiple/unlimited cardinality can be catered for), and under each of those is in array for the various different field columns. In the majority of cases this will be 'value' but not always (for example an image field has a file id column, alt column etc)

Hope that helps


Custom submit button callback overrides default callback?

Problem seems to be custom form element. Change it to :

$form['custom'] = array(
    '#name' => 'custom',
    '#type' => 'submit',
    '#value' => t('get data'),
    '#prefix' => '
',
    '#attributes' => array('alt' => t('get data')),
    '#suffix' => '
',
    '#submit' => array('custom_callback'),
  );


Value of the input is not preserved when it is an HTML array

IMO this should work

    function mm_definition_of_the_form($form, &$form_state) {
      //other code
      $form_state['rebuild'] = TRUE;

      if (isset($form_state['check_field'])) {
        //set default value of the field
      }
    }

    function mm_definition_of_the_form_validate(&$form, &$form_state) {
      //if is error
      $form_state['check_field'] = TRUE;
    }


The #options property should be an array of key value pairs (the key is the <option>'s value attribute, the value is the content of that tag), so:

$options = array();
foreach($sxml2->NewDataSet->DepCity as $item) {
  $options[$item->Name] = $item->Name;
}

$form['from'] = array(
  '#type' => 'select',
  '#title' => t('From'),
  '#options' => $options,
);

That's just for demonstration, you may wish to use something other than a name for the option key - it's the sort of thing that would clash easily.


Display long text fields as type text input not as textarea on node forms

Drupal textfield widget can only be applied to string fields.
https://git.drupalcode.org/project/drupal/blob/8.7.4/core/lib/Drupal/Core/Field/Plugin/Field/FieldWidget/StringTextfieldWidget.php#L9

However it's not a big deal to alter its definition and make it support long strings.

/**
 * Implements hook_field_widget_info_alter().
 */
function HOOK_field_widget_info_alter(array &$info) {
  $info['string_textfield']['field_types'][] = 'string_long';
}

After having this done it should be possible to assign textfield widget to long text fields on "Manage form display" page.


drupal_get_path function for third party PHP includes files

drupal_get_path() returns the path of a module, a theme, a theme engine, or a profile. It's not for loading a generic PHP file, for which you need module_load_include() which (despite the name) can be used for a PHP file that can be loaded with require_once.

Supposing you add the soap-wsse.php file in the includes directory of the test_module module, you cal load that file using the following code.

module_load_include('php', 'test_module', 'includes/soap-wsse');


Change target type of entity reference field in update hook

I dealt with this issue a few months back in the jQuery Colorpicker module. I was converting all fields of one type (jquery_colorpicker), to fields of an entirely different type (colorapi_color). With the update of the module from 8.x-1.x to 8.x-2.x, I intended to remove the the original type/plugin (jquery_colorpicker). Then in the update script I intended to loop through each field on every entity type, and if it was jquery_colorpicker, change it to colorapi_color. However deleting the plugin led to the same issue you are running into, where I was getting an error about mistting the field type that I had removed.

In the end to get around this problem, I took a different approach altogether. I left the definition plugin file for the jquery_colorpicker field in the file system, but marked it as deprecated:

/**
 * Provides the Color field.
 *
 * @FieldType(
 *   id = "jquery_colorpicker",
 *   label = @Translation("Color (deprecated)"),
 *   default_formatter = "colorapi_color_display",
 *   default_widget = "colorapi_color_widget",
 * )
 *
 * @deprecated as of Jquery Colorpicker update 8200. Will be removed in Jquery
 *   Colorpicker 8.x-3.x, and/or 9.x-1.x. Running
 *   jquery_colorpicker_update_8200() requires the existence of this field type,
 *   however the field type is obsolete after that update has been run. As such,
 *   if the schema version is equal to or above 8200, the field type is removed
 *   from the list of field types in jquery_colorpicker_field_info_alter().
 */

Link: https://cgit.drupalcode.org/jquery_colorpicker/tree/src/Plugin/Field/FieldType/JqueryColorpickerColorItem.php#n9

Then I set the system to remove the field type from Drupal's list of field types when the current installed version of the module is 8200+:

/**
 * Implements hook_field_info_alter().
 *
 * @deprecated as of Jquery Colorpicker update 8200. Will be removed in Jquery
 *   Colorpicker 8.x-3.x, and/or 9.x-1.x.
 *
 * @see jquery_colorpicker_update_8200()
 */
function jquery_colorpicker_field_info_alter(&$info) {
  // Running jquery_colorpicker_update_8200() requires the existence of the
  // jquery_colorpicker field type, however the field type is obsolete after
  // that update has been run. As such, if the schema version is equal to or
  // above 8200, the field type is removed from the list of field types.
  if (drupal_get_installed_schema_version('jquery_colorpicker') >= 8200) {
    unset($info['jquery_colorpicker']);
  }
}

Link: https://cgit.drupalcode.org/jquery_colorpicker/tree/jquery_colorpicker.module#n45

With the above code, before the update is run, the version will be less than 8200. Any time the system builds the list of field types, the jquery_colorpicker field type is available, meaning that when the update script is run, the field type is still available, so you won't get the error about it missing.

After the update has been run, the version will be 8200 (or greater), and therefore the jquery_colorpicker field type should no longer be available. Therefore it is removed from the list of field types.

If/when version 8.x-3.x of the module is released, I will remove the jquery_colorpicker plugin file altogether. For now, it's still in the codebase, but deprecated and unused.


change node author with rules. using an array of users with specific role

Enable Views Bulk Operations

Create a view (Table format is the easiest to manage.)
Add a relationship Content: Author (not required)
Add the author field so you can see who is the current author
Add the field Bulk operations: Content
Under Selected Bulk operations choose Change the author of the content.
Save the view.

Now on the view page you will see a table of all your nodes.

Check the select box next to the rows you need to update the author of.
Under Operations at the top of your view, choose change the author of content.
Hit Execute
On the next page, choose the user and hit next
on the next page hit confirm.
Repeat / Integrate with rules...


How to hide Fivestar rating field after first comment?

In your node.tpl.php you should have the following code

hide($content['field_fivestar']);
print singlerating_print_rating($node->nid, $content['field_fivestar']);

I presume field_fivestar is the fivestar field you are using and not field_fivestar_rating


"Organic groups: Group node" equivalent?

The one I was looking for (after much trial and error) is "OG membership: Group Node from OG membership"

That relationship seems to be the same as "Organic groups: Group node" in Drupal 6


How can I programmatically add a field to a field group?

You have to put both.

$form['#group_children']['field_test'] = 'group_1';
$form['#fieldgroups']['group_1']->children[] = 'field_test';


Caching interfering with jQuery and drupal behaviors?

Just like when you add a menu item or some theme elements, you need to clear the cache when you add new javascript.

For a site in development mode you can simply turn off caching so that you don't have to remember to clear the cache every time ('drush cc all' is handy):

Drupal 6: /admin/settings/performance: Caching mode set to disabled

Drupal 7: /admin/config/development/performance: Uncheck cache pages for anonymous users

Disabling "aggregate javascript", will make it much easier to debug your js with chrome or firebug.


how to exclude PHPUnit based functional tests from runnning?

Since those tests are grouped by namespace/directory, you can just pass the respective path to phpunit, simply add tests/src/Unit to your existing path.


Where to look for a forum thread in database?

I don't know how 6 version works with forum (because I've never used 6v), but in d7 forum is actually is a node (threads are node types). I thinks you can search for forum table which holds the nids of threads and node and node_type tables for actually for that nodes and thread type...

To find the node by Title:
Open your PhpMyAdmin from browser -> select your db -> open 'node' table -> switch to SQL tab -> SELECT * FROM node WHERE title = "YOUR TITLE"

EDIT:
threads are taxonomies, not node types (based on comment of Mohammad Ali Akbari)


print views_embed_view('name_of_view','defaults');

no need of rendering also a second arguments are there  as display name

views_embed_view()

  Embed a view using a PHP snippet.

  This function is meant to be called from PHP snippets, should one wish
  to embed a view in a node or something. It's meant to provide the
  simplest solution and doesn't really offer a lot of options, but
  breaking the function apart is pretty easy, and this provides a
  worthwhile guide to doing so.


Does a twig template know in which region it is?

No, it doesn't.

With render caching, it is even possible that the same template/thing is not rendered again and put into a different region (not directly a block, but for a example a rendered entity, in a view or so).

It's easy to do targetting in CSS based on a parent region class. I know there are some recommendations to avoid that, but that's not always possible, especially when working with a complex system like Drupal, where you don't have 100% control over the HTML output in every scenario.


Drupal 7: How to insert site's Main Menu and also use my custom style on it?

In Bartik, menu is added like that:

    <?php if ($main_menu): ?>
      <div id="main-menu" class="navigation">
        <?php print theme('links__system_main_menu', array(
          'links' => $main_menu,
          'attributes' => array(
            'id' => 'main-menu-links',
            'class' => array('links', 'clearfix'),
          ),
          'heading' => array(
            'text' => t('Main menu'),
            'level' => 'h2',
            'class' => array('element-invisible'),
          ),
        )); ?>
      </div> <!-- /#main-menu -->
    <?php endif; ?>

Except the fact that $main_menu was not provided in page.tpl.php nor in template.php, apparently created by menu module, it looks like your code, just more elaborate. This indicates that either in menu_navigation_links or in theme you passed an argument that happens not to work. Except that it should be all right. Use dpr() or var_dump() to see which one fails.

If you need better control over your menus, I suggest using Menu block module to put them. This module allows you to treat menus or their parts as a blocks, so in your template all you need to do is to output proper region.

To get classes on menu items, you can simply use Menu attributes module:

  The module currently allows you to set the following attributes for each menu item:

  Id
  Name
  Target
  Rel
  Class
  Style
  Accesskey


Is there anywhere a good writeup on Drupal directory structure?

I haven't seen one, so let's start a list right here. In Drupal 5, 6 and 7 the structure looks like this:

includes - include files with php functions and classes that make up the Drupal API
misc - miscellaneous assets like javascript files and images
modules - Drupal core modules (not meant for contrib and custom modules)
profiles - installation profiles
scripts - shell scripts for developers and administrators
sites - all files that are added by a developer to create a site

sites/all/libraries - 3rd party libraries, eg. a wysiwyg editor
sites/all/modules - contributed and custom modules
sites/all/themes - contributed and custom (sub)themes
sites/default - contains the default settings.php
sites/default/files - the default directory for user-uploaded files
sites/example.com/modules - the site-specific modules directory in a multisite structure
sites/example.com/themes - the site-specific themes directory in a multisite structure
sites/example.com/files - the site-specific directory for user-uploaded files in a multisite structure

themes - Drupal core themes


Add a block in page content that use viewreference

The Block reference module may be what you are looking for.


Custom Body of Webform email handler missing text area

At jrockowitz suggestion I found the issue, in case someone else has same issue,
ckeditor could not find the plugin.js file and related files.  I moved them as below and it works.
was: ckeditor.link/ with a folder called link and plugin.js
now: ckeditor.link/ with folders dialogs, icons, images, lang and plugin.js file


Is there any security consideration with webform and Salesforce API?

PHP SOAP will not introduce any security issues in itself; it's more about how it is used. If it's used via unencrypted HTTP, for example, the data could be intercepted, like any other data. If you need the data to remain secure, then obviously this would be a consideration.


Have a look at the Drush make project:

http://drupal.org/project/drush_make

There is also a companion website at:

http://drushmake.me/

This website allows you to select the modules you want to package with Drupal, and produces a Drush-ready makefile.

There are other varieties of this functionality out there, so I advise experimenting and testing with your specific configuration.


Am I allowed to include a JQuery Plugin in my Drupal Module?

Do you intend to publish your module as a contributed module on drupal.org? In that case: Probably not. The page 3rd party libraries on Drupal.org states:

  This is the policy for 3rd party code libraries in Drupal's contribution repositories.

  In general 3rd party libraries are forbidden, so do not commit any. Document for your users how to find and install it.

After that, it mentions some exceptions.

I understand that it's tempting to include the plugin in your module, but there are some good reasons not to. For instance:

If other modules use the same plugin, having it in the libraries folder will prevent collisions.
Users will always be able to get the latest version of the plugin.
You, as module maintainer, probably do not want to be bugged about releasing a new version every time the plugin is updated.


How to make a Data Selector a negative value in a rule action?

You have two ways to do this.

Either you use PhP filter, which will add under "data selector" and "add offset" a new option, "php evaluation", which will allow you to post-treat this value. Then you'll just have to set return intval(- $value);

Or you can use whole Rules, by :

Action: Add a value, and select your [node:field-labpoints]
Action: Calculate a value, and make it negative
In your action, use this value instead of the one you selected with the selected.


HOOK_menu_alter to remove Main Menu items for specific user roles

I take you added a link to the main menu, and you want to make it appear only when the user has the right permission. In that case, hook_menu_alter() is not the right hook to implement because:

It is not used to override the links added to that menu
It is not possible to use admin/people/create?operator=1 as path for the menu link in hook_menu() or hook_menu_alter()

What you should do, after you added the link to the main menu, is to enable a module that contains the following code.

function mymodule_menu_link_alter(&$link) {
  if ($link['link_path'] == 'admin/people/create?operator=1' && $link['module'] == 'menu') {
    $link['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$link) {
  if ($link['link_path'] == 'admin/people/create?operator=1' && $link['module'] == 'menu' && user_access('use advanced user creation link')) {
    $link['hidden'] = 1;
  }
}

function mymodule_permission() {
  return array(
    'use advanced user creation link' => array(
      'title' => t('Use advanced user creation link'),
    ),
  );
}

The $link['module'] == 'menu' part allows to alter the link that you manually added in the main menu, and not other links (i.e. added from a module). In the first function, $link['options']['alter'] = TRUE tells Drupal to invoke hook_translated_menu_link_alter() for that link; in the second function, which is actually an implementation of hook_translated_menu_link_alter(), while the first function is the implementation of hook_menu_link_alter(), $link['hidden'] = 1 actually hides the menu to the currently logged-in user.
Instead of "use advanced user creation link," you can use another permission string; as long as the permission is only given to the roles that need it, and it is unique, you can use any string you want.

I didn't find one, but if there is a module that makes the links added to the main menu visible to users with specific roles, I would use that, instead.

As side note, checking for a permission is preferable to checking for the roles the logged-in user has. The reason is that when you check for permissions, the code is always similar to if (user_access('permission to check')) {} whatever roles have that permission, while when you check for roles, the code could change from if (in_array('supervisor', array_values($user->roles))) {} to if (in_array('supervisor', array_values($user->roles)) || in_array('another role', array_values($user->roles))) {}; in other words, you are hardcoding something that you could change in the future.


Is there a Drupal module that can create a content type from an SQL Query or a CSV file?

A module referred to as ECK has the functionality you're looking for.

Although, it works in the entity system to create new entity types. You might be looking for something to pragmatically create entity bundles (node content types). I would suggest researching the difference between Entity's and Bundles if you're not familiar.


Custom Save and Unpublished button for node

You can't use

 $entity->set('moderation_state', 'submitted');

if you don't have Content Moderation core module enabled

Also make sure you declare the usage of FormStateInterface somewhere in your .module file

use Drupal\Core\Form\FormStateInterface;

Also look in your error logs found in admin/reports/dblog for other possible errors


How to set individual fields permission on content type fields based on roles using field permssion

Field permissions do not add permissions, but only take permissions away.

If a user is not allowed to edit a node, giving him the permission to edit a field won't work. Instead you must give him permission to edit all nodes (of a certain type) and deny access to all field he may not edit. (and yes that can be a struggle if you add fields in the future)


how to add custom font files to template

You need to use libraries. Take a look here for a detailed explination: https://www.kinetasystems.com/blog/adding-google-fonts-to-a-drupal-8-theme


Uploading videos with the Media uploader

The video module is strictly for videos that your users upload. You need to configure the transcoding (ffmpeg on your server or use the external Zencoder service).
If you want to embed Youtube or Vimeo videos you can use video embed field module.

I've combined the two to allow video uploads and video embeds. However I really prefer the video embed field since dealing your users uploading a ton of large video files isn't trivial.


Twig template for custom entity not working

You must render the correct view mode of the entity, like this:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('ENTITY_TYPE');
$entity_view = $view_builder->view($representative);

$build = [
  '#theme' => 'representatives',
  '#representative_entity' => $entity_view,
];


Use a default parameter (for example blog_id) in your routing.yml file:

mymodule.route_name:
  path: '/blog-landing/{blog_id}'
  defaults:
    _title: 'Show blogs.'
    _controller: '\Drupal\mymodule\Controller\BlogController::viewAction'
    blog_id: 'all'

If the blog_id parameter is omitted the default value ('all') is used.

After your edit:

If you are redirecting via the RedirectResponse() class you should call the send() method in order to redirect.


How to prevent Content type from appearearing in built-in Search results

There are two modules you can check out.

Search Config

  Restrict search results by the content type. This is a role based
  restriction.

Search Restrict

  Restrict by role who can search for each content type.

  Approach of this module is to re-write the search query, so that
  content is indexed and available as search results to users in role(s)
  that have permissions to view it, but not displayed to other roles.

OR

You can write your own query alter function.

function mymodule_query_alter(&$query) {
  $is_search = FALSE;
  foreach ($query->getTables() as $table) {
    if ($table['table'] == 'search_index') {
      $is_search = TRUE;
    }
  }

  if ($is_search) {
    $query->condition('n.type', 'node-type-name', '<>');
  }
}

And yes as webkenny suggested Custom Search as well.

  Basic options

  The module adds options to select:

  which content type(s) to search,
  which specific module search to use (node, help, user or any module that implements search),
  advanced criteria

  For all these choices, there are options to switch between a select
  box, checkboxes or radio buttons, and also customize the selector
  label and the default - Any - text.


How do I set my custom module to use a template for a specific page?

Template files are associated with theme functions. To use a template, the theme function that is declared in hook_theme() must report that it is using a template file, and this is done adding the "template" property.
For example, the following definition used from the Node module says to Drupal that for the "node" theme function, it needs to use the "node.tpl.php" template file; every times a module calls theme('node', …), Drupal will know to use that template.

function node_theme() {
  return array(
    'node' => array(
      'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
      'template' => 'node',
    ),
    // …
  );
}

For a page that is visible on http://example.com/parcels, Drupal checks for a template file named "page-parcels.tpl.php" exists, and use it in that case. The template files are looked in the directory of the currently set theme, though; this mean that the template is not found if it is in the directory of a module.


How to programmatically link commerce products to taxonomy terms

You're close, but need to tweak setting the field value to:

$product->field_some_option[LANGUAGE_NONE][0]['tid'] = $tid;

For the taxonomy term reference field uses the 'tid' key there.

You could also do it with a metadata wrapper like:

$wrapper = entity_metadata_wrapper('commerce_product', $product);
// Append to existing field value
$values = $wrapper->field_some_option->raw();
$values[] = $tid;
// Set field values
$wrapper->field_some_option->set($values);
$wrapper->save();


Can you modify the settings.php file using drush?

What you really need here is different settings.php files for your production and development environments.

There are multiple ways of achieving this, some examples:

Setting various environments (development, production) based on the URL
Environment Specific settings.php Overrides

I usually include the following lines at the end of the settings.php file (in all instances):

// Override settings in this file.
if (file_exists('./' . conf_path() . '/local_settings.php')) {
  include_once './' . conf_path() . '/local_settings.php';
}

And then change the $databases array there, and any other specific environment settings.

You may also find useful the following links:

Defining variables in a site's settings.php $conf array
Set Environment module, that helps maintaining multiple environments with drush.


What is the best slideshow to CCK image field?

Well, there is of course this page in the drupal docs: http://drupal.org/node/418616

Unless you have a very specific use case which can be accommodated by a specialized module you really should go with the views slideshow module (http://drupal.org/project/views_slideshow). Very well maintained, fairly well documented (but a lot of tutorials flying around) and a lot of modules integrating with it. With this module you can do almost everything slideshow-wise but it might be a bit complicated (but again: lots of tutorials available).

You can of course check out some of the other modules if they offer something more matching to your specific needs.


REST Export Views and images alternative text

Views Format: Fields

I don't think there is a special separate field in Views UI for the Alt field. Alt text is part of the Image field data, stored with the content entity (not the file).

So what you do is add another Image field to your Views, but configure it this way:

Rewrite results
Override the output of this field with custom text
Check Replacement patterns below to find your Alt token
Enter the replacement pattern into the above Text field {{ field_image__alt }}

Now you have the image Alt text showing as the field output instead of the actual image.

Edit: The above can only help if you're using Fields under your Format settings in Views.

Views Format: Content/Entity

When showing full entities in Views you need to use Content Type/Entity View modes (not to be confused with anything Views related). On your CT add a new View mode on the Manage display page, or adjust the existing one you're using in your Views Format settings.

Custom Image field formatter

This is where you should be able to adjust your Image field Formatter, but unfortunately the Image field doesn't seem to come with the "Alt" text formatter.

Other than creating the custom Formatter yourself you can check out this Issues and module:

Add 'alt' and 'title' tokenized text options for image formatters, and a 'title' option for the generic file formatter
Custom Formatters


Not personally tested, but according this issue is a problem for already existing entities, while it should be resolved for new ones.
Also, there's a module that seems to address this issue.
So, I'd say:

try to create the node only in one step, to see if that preserve the original timestamp
if that fails, try either the patch or the module


Can a view and a content type share the same alias pattern?

Yes, you can do this. The key is in the Action to take if filter value does not validate option of your Contextual filter.

Set that option to Display contents of "No results found".

Then under No results behavior add Rendered entity - Content enter schools/{{ arguments.name }} or which ever correct token is in your case.

This will make your views work with regular terms, but if the term doesn't validate it will go to the page with the argument. In your case if the argument is school-name then it will lead to the node page with that path.

What you should additionally consider is what an argument is entered that isn't neither, a term nor the appropriate part of a node path. You'll just get a blank page with View page title.

Maybe you can solve that by adding another No results behavior for that case, maybe a block with a message that the term doesn't exist and a link back to the Views page, then hide the Block on your node pages that share the starting path string.


How do i get views field labels in the template file

As far as I see in the documentation for views-view-fields.tpl.php (I did not test it myself), the syntax seems to be something like the following:

<?php print $fields['myfield']->label; ?>

(you can also use $fields['myfield']->label_html)


How to dynamically pass a user field value to jQuery?

You can use Block Refresh module. Put the notification's content in a block and using this module refresh block in some interval of time. In block template write your own condition or logic.


Copy content from Word and use paragraph style names as classes

CKEditor Editor will not work the same way as Word so when you copy and paste some document to CKEditor. CKEditor will change the setting based on it own setting


Inline labels for exposed filter forms in Views 3

Might be worth checking out the Better Exposed Filters module, and Better Exposed Filters (the handbook). I haven't used this module.