How can I hide specific user from dropdown list of users

One possible solution is to add a new field show/hide Checkbox in account settings and then in drop down show only those whose show/hide field set to show.

This way if your client wants to hide another user go and edit the user and hide it


How to use the dsm( ) Devel function to print the $form array of my form?

Start a custom module, insert this code:

/**
* Implements hook_form_alter().
*/
function foo_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_theme_form') {
    dpm($form);
  }
}

Also, you might want to use dpm() over dsm() since the latter is a legacy function.


Does get_defined_vars() show variables defined in variable_set()?

get_defined_vars is a PHP function, not a Drupal function.  It basically shows you all variables that are in scope.

Drupal variables set by variable_set are not automatically within scope.

Variables are stored in global $conf; but I don't recall if non-variables are also stored here.

If you install the Devel Module there is a page for viewing and editing variables.

EDIT:

Curiosity got to me.  The variable editor in the Devel Module queries the {variable} table and not global $conf; to build the form of all available variables, so that suggests that is the proper way to do it.


Addind a meta noindex tag within template.php

You could use the following code.

function mytheme_preprocess_node(&$variables, $hook) {
  $node = $variables['node'] ;
  if ($node->nid == '123') {
    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
    drupal_add_html_head($element, 'mytheme_noindex');
  }
}

In Drupal 6, you just use drupal_set_html_head('<meta name="robots" content="noindex" />'), instead of drupal_add_html_head().

I would rather use the code in a module, as a theme should not know details such as the existence of a node with a specific ID. Plus, if the site has more than one theme enabled, or it is possible that a different theme is enabled in future, the code should be copied in each enabled themes, while a module will always be executed, independently from the theme being used.


Why can't you assert the response status in a FunctionalJavascript test?

This has a little history behind it.

Mink is the library that build on top of phpunit for functional testing:

  One of the most important parts in the web is a browser. A browser is the window through which web users interact with web applications and other users. Users are always talking with web applications through browsers.

  So, in order to test that our web application behaves correctly, we need a way to simulate this interaction between the browser and the web application in our tests. We need Mink.

Mike supports several ways to simulate a browser, through drivers.

Normal functional tests use BrowserTestBase, which uses the Goutte driver.

Javascript tests used to use the PhantomJS driver, but that is an abandoned project now.  This has been migrated to WebDriverTestBase, which uses the Selenium2 driver.

Selenium2 essentially does a remote control of a headless browser, through the WebDriver protocol.  This allows you to run the same driver against multiple browsers (Chrome, Firefox, and I think Safari).

The problem is that Selenium2 gives you the advantage of a real browser, but has limitations.  It is slow.  The other is that there isn't full parity between the other drivers, and getting the response code is one of these limitations.

So, this is a Mink/Selenium2 problem and not a genral Drupal testing framework problem.


how do I return a count of items returned from an entityfieldquery

if you just want the count then you could set the query to count.

something like

$count = $query->count()->execute()

See here for more detail


Which Drupal 6 theme framework is good for creating a responsive web design?

Omega offers good responsive features.
"Fully Responsive Grid layouts based on 960.gs standards."

I have used this for many 7 projects but not tried 6, if this is a new project you are starting I would recommending starting with 7.


7 Ubercart hook_order for PayPal Paments Pro payment received

IMHO the easiest way is to use Rules. There's a default rule you can clone and tune for your needs: uc_payment_received.

I would clone that rule, add the condition to ensure it's a payment coming from PayPal, then replace the action with "Send an order email". The you should be able to customize the email.

Writing a custom module for this task is a bit overkill.


Using contrib modules will certainly help for this. There are at least two I can think of:

Form Block (https://www.drupal.org/project/formblock)
Advanced From Block (https://www.drupal.org/project/afb)

To answer your question, however, you need to instantiate a new (or existing) node object to set as your form_state (Assuming the machine readable name of your content type is "newsletter").

global $user;
$node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'newsletter', 'language' => LANGUAGE_NONE);
$form_state['build_info']['args'] = array($node);
form_load_include($form_state, 'inc', 'node', 'node.pages');
$form = drupal_build_form('newsletter_node_form', $form_state);

If you want the form to edit an existing node, the you can replace the $node = (object) part with a node_load([nid]) function.


As you mentioned, there's no loop, so you can't do this in the template file (well you could, but it wouldn't be worth the effort).

Instead, you could maintain a static variable in a preprocess function:

function MYTHEME_preprocess_views_view_fields__view_machine_name(&$vars) {
  static $counter = 0;
  $vars['counter'] = $counter++;
}

And refer to it in the template as normal:

{{ fields.field_picture.content }}

You might need to tweak that, for example if the View is rendered twice on the same page.


In your custom module implement hook_form_alter, this will let you add your custom validation handler to the form, something like

  my_module_name_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'your_form_id') {
      // Add one more validation.
      $form['#validate'][] = '_my_module_name_custom_form_valition';
    }
  }

  function _my_module_name_custom_form_valition($form, $form_state) {
   // $form_state holds value for submitted fields.
   if(!in_array($allowed_values,$form_state['values']['your_form_field']) {
      form_set_error('your_form_field',t('Entered value is not allowed.'));
   }
  }


Multiple file upload controls on same form via FAPI not possible?

I will recommend you to use:

print_r($_FILES);

This placed inside the form function submit will let you know if the files are been upload it into the temp directory and what are their names. Also check the file upload field name as sometimes when you copy and paste code you might be re-using the same name and this is creating the overwriting.

Last, but not least in your custom module try adding a single upload file field and test it if it work, then add a second and try it and so on.


How Generate Configure button ? (Module Page)

test.info file

    name = configure test
    description = configure test.
    core = 7.x
    ; NEW LINE
    configure = admin/config/test

test.module file

<?php
/**
 * Implements hook_menu().
 */
function test_menu() {
  $items = array();
  $items['admin/config/test'] = array(
    'title' => 'Test',
    'description' => 'Configuration for test module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
?>


Views: displaying a field from a vocabulary based on the name

If I understand question aright, you need to use a Relationship in your View.

Under the Advanced section (just below contextual filters) click 'Add' to add a Relationship
Select the field in your node for the relevant term reference, e.g. a field labelled 'Tags' and with a machine name 'field_tags' would appear as Content: Tags (field_tags) in the list that is shown when you select 'Add'
The default configuration should be fine for the use case at hand, so in the next dialog box it should be OK to simply select 'Apply'. (In some cases you do want to tick Require this relationship.)
Go to Add fields and add a new field. Find the image field in your taxonomy. If the taxonomy is called Tags and the field labelled 'Image', it'll look like: Taxonomy term: Image Appears in: taxonomy_term:tags. Select this and click on 'Apply', Then click on 'Add and configure fields'
When you are in the configure dialog you'll see an indication that a relationship is being used. It'll look something like this:

Configure as required and apply. In your fields list it'll look something like this:

What these steps do is say that you want to use the field in the node that contains the taxonomy term to bridge to the fields in the particular taxonomy vocabulary item. Having added the relationship you can now add fields that call upon it. That, if I understand the question, is what is needed here. And, again, if I've understood aright, no need for contextual filters - at least not to get the image from the taxonomy into your view.

These steps apply to Views 7.x-3.5. (In pre 3.5 versions, or perhaps bit further back,  the relationship set up was a bit more complex, but it's now more streamlined.)


How does the view filter: Search: Search Terms works? Can I improve it?

If you want to search nodes based on title alone, you can try with Node:title instead of Search:search terms in filter section and select the operator as "Contains any word"


Show block on all 404 / 403 pages only via context

A better way to do this is create a panel page for 403 and 404 page. Add whatever you want to in the panes.

Set the 403 and 404 page path under :

Admin > Configuration > System > Site Information

There is a section called ERROR PAGES. Add both the path there.

Edit :

For context use Context Error module.


Simple answer is YES. What you are trying to do can be achieved by using one of these modules:

The Multi Site installation module (It requires separate database for each site or common database with table prefix.)
The Domain Access module

These are just general suggestions, as there are several ways to achieve your goal. You have to choose the right method suited for your needs. This is a screen-cast which would be helpful for you.


How to distinguish between drush and HTTP request

From drush.php:

function_exists('drush_main') may be used by modules to detect whether
they are being called from drush.  See http://drupal.org/node/1181308
and http://drupal.org/node/827478


Views exposed filter with selected tags/terms

I found the answer by myself: Sometimes it is so easy and obvious and you too are blind to see it:

Choose selection type dropdown
select terms
check "Limit list to selected"


Retrieve a list of values from a lookup table using db_select

Add more fields to your query from the other tables that you have joined to:

$query->fields('js');
$query->fields('s');

Use hook_menu() to create your page if you want a custom one, then render it in PHP (I'm guessing at your result variable):

       ....

      <?php>$result['job_number']<?>
      .....


How can I suggest a template file specific for a content type?

You can do this with a theme suggestions alter hook:

/**
 * Implements THEME_theme_suggestions_html_alter().
 */
function MYTHEME_theme_suggestions_html_alter(&$suggestions, $vars, $hook) {

  // Check to see if you are on a node.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

    // Get the node type.
    $type = $node->getType();

    // Create the theme hook suggestions.
    $suggestions[] = 'html__' . $type;
    $suggestions[] = 'html__node_' . $type;
  }
}

Of course, change "MYTHEME to your theme name. I tested this on a blog content type for example and the new template suggestions printed out after creating this hook and clearing cache.

<!-- THEME HOOK: 'html' -->
<!-- FILE NAME SUGGESTIONS:
   * html--node-blog.html.twig
   * html--blog.html.twig
   * html--node--15.html.twig
   * html--node--%.html.twig
   * html--node.html.twig
   x html.html.twig
-->

The new theme hooks here are:

  * html--node-blog.html.twig
  * html--blog.html.twig

The content type name will change accordingly in the naming suggestion.

To test, I copied html.html.twig and named as html--node-blog.html.twig and it worked great.


How to pass a custom object from a page to another page through a route or other means?

You are passing the object, but you need to pass the object ID. So you will change this:

Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model));

To this:

Url::fromRoute('custom.page')->setRouteParameters(array('model' => $model->id()));

Note that your model object will need to have a public id() method that returns the ID for this to work. This will send the ID that is passed in place of {model} to the callback.

If you want the callback function (the controller) to receive a loaded object rather than just the ID, you'll need to do a few things. The first is to add options to your route:

custom.page:
  path: '/custom/{model}'
  defaults:
    _controller: '\Drupal\custom\Controller\CustomController::page'
    model: ''
  requirements:
    _permission: 'administer site configuration'
  options:
    parameters:
      model:
        type: model

Then you'll need to set up a new route in services.yml:

services:
  model:
    class: Drupal\mymodule\ParamConverter\MyModuleParamConverter
    tags:
      - { name: paramconverter }

And you'll need to create the class (Drupal\mymodule\ParamConverter\MyModuleParamConverter) that does the conversion from ID to object. This class needs to implement ParamConverterInterface:

namespace Drupal\mymodule\ParamConverter;

use Drupal\Core\ParamConverter\ParamConverterInterface;
use Symfony\Component\Routing\Route;

class MyModuleParamConverter implements ParamConverterInterface {
  public function convert($value, $definition, $name, array $defaults) {
    // Create your Model object here (not shown) then return it:
    return $model;
  }

  public function applies($definition, $name, Route $route) {
    return (!empty($definition['type']) && $definition['type'] == 'model');
  }

}

You can read more about parameter upcasting here: https://www.drupal.org/docs/8/api/routing-system/parameter-upcasting-in-routes


How to configure ckeditor for different toolbars?

Found the solution to first add the bullitsformat and then edit the profile, so this profile is shown in the profile of the ckeditor.


Add $conf['https'] = TRUE; to settings.php.

from here:
http://drupal.org/node/1037542
and
http://drupal.org/https-information

however, why not just run the whole site securely?


How to create sub-directory based multi-site?

You can modify the site names in the file sites/site.php

$sites = array(
  'site1.your-multisite.local' => 'website1',
  'your-multisite.local.site2' => 'website2',
);

Also update the settings.php file of each subdomain with the credentials of respective sites.

Also need to update the site url from the host settings.

 ServerAlias    *.your-multisite.local your-multisite.local.*


I think your problem lies in the fact that you are using the same URL for both a view and a node - this is a really bad idea in most circumstances.

If you always want the view to show - what does it matter if the taxonomy itself is at /category/tag/[term:name]?

You might find Page Manager useful for what you're trying to do, there's a fantastic free tutorial and familiarisation set of videos that have helped me immensely of late.


When using hook_form_alter() and additional submit functions, can one reference a php file for the submit callback?

Why not do something like

require_once('bleh_community_submit.php');

then call the callback function as per normal?


After some more searching I found a patch for this issue here: https://www.drupal.org/node/2781103

Seems to be working for me in Drupal 8.2.6. I did have to restart apache before it started to work, maybe a cache clear was all I needed for it though.

Not sure if I should accept this answer since it may become quickly outdated.


I ended up using this

if ($form_state['storage']['file'] != '0') {
  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_is_image' => array(),
  ));

  // If the file passed validation:
  if (isset($file->filename)) {
    // Move the file, into the Drupal file system
    if (file_move($file, $file->filename)) {
      // Update the new file location in the database.
      drupal_write_record('files', $file, 'fid');
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }

  $file = $form_state['storage']['file'];
  // We are done with the file, remove it from storage.
  unset($form_state['storage']['file']);
  // Make the storage of the file permanent
  file_set_status($file, FILE_STATUS_PERMANENT);
}

$fid = $file->fid;
$icon = $file->filename;

if (!isset($fid)) {
  $fid = $form['fid']['#value'];
}

if (!isset($icon)) {
  $icon = $form['icon']['#value'];
}

$id = $form['id']['#value'];
$url = $form['url']['#value'];
$title = $form['title']['#value'];


Is Node a superclass of all content type?

From drupal.org: An Introduction to Entities

  If you come from an OOD/P background and are trying to better
  understand what these key D7 concepts are, the following suggested
  mapping might help (albeit not strictly true from a purist’s
  perspective) :-

An entity type is a base class
A bundle is an extended class
A field is a class member, property, variable or field instance
    (depending on your naming preference)
An entity is an object or instance of a base or extended class

  All these four OOD/P concepts are special in that they are
  serialisable (stored - e.g. to a database or file). Serialisation
  takes place via the Entity API.


Image-link to content works only on preview

Views preview does not use templates from your theme. Expand Advanced on the right, and in Other section click Theme: Information. Find .tpl.php files that are bolded and may apply to your fields (are applied to them directly, or to their parents). Look for them in your theme's directory and search them for errors.

If that will not help, offending template comes from Panels, not Views themselves.


Import translation file only for specific core module

Nope, you cannot.

Translations are stored per project, not per module, and core is one project. Of course there is experimental Contact project on Drupal.org, but it's translation stays pretty empty as it's not needed.

Worse, in exported files (at least in my language) there is no metadata, no comments about modules these strings originated. So manually cutting this file to your needs would be pretty hard, too.


Menu list links of different languages of a Localized Menu are shown in all languages?

I'm assuming you already have the i18n Menu Translation sub-module is enabled (it is one of the Internationalization sub-modules).

Edit the menu to be translated, by navigating to admin/structure/menu/manage/main-menu/edit (for the "main menu"). From there you can select the translation mode you want, e.g. Translate and Localize (from your question it seems you also did that already).

With what's above you should be in pretty good shape to complete the finishing touch: when editing a menu link, there should be a new link Translate to actually translate the menu entry. After you entered a translation for the "original" (eg English) menu item in another language (eg Spanish), Drupal will ensure that whenever you switch to another language, the corresponding menu item will be switched also (to the matching language).

Should you have some other menu item in your original menu in that "other" language, you can safely delete that menu item. After you delete such item, that'll be 1 menu item less that is shown "in both languages" (as in your question). Repeat the above (= translate menu item and delete original duplicate item) for each of your duplicate (in both languages) menu items.

Refer to the Multilingual Guide for (way) more details.

Miltilingual sites are really fun in D7 (way better then it was in D6, and D8 promises to become more easy to configure). Typical variations (with similar solutions) of this "menu" topic are:

translations of blocks, which requires the Block Languages (i18n_block) submodule to be enabled.
translations of taxonomies, which requires the Taxonomy Translation (i18n_taxonomy) submodule to be enabled.


How to render entity reference data in field template?

Paste the below code template.php;

function mytheme_preprocess_node(&$variables) {
  if(isset($variables['node']))   {
    switch ($variables['node']->type) {
      case "value":
        $var_abc = $variables['node']->field_abc;

        foreach ($var_abc['und'] as $key => $value) {
          $variables['abc_fields'][] = $value;
        }
      break;
    }
  }
}

Paste the below code to create separate node tpl for that specific content type;

<?php
foreach($variables['abc_fields'] as $key => $value) {

  $var_authorvalue = $value['node']->field_author;
  //echo "
";
  //print_r($var_authorvalue['und'][0]['value']);
  $var_fields = $value['node'];
  print render($var_fields->title)."
";
  print render($var_authorvalue['und'][0]['value'])."
";

}
?>

OR

Check How can I print a field from a referenced entity in my theme?


Media Browser in WYSIWYG editor doesn't allow uploads for non-admins

There are two things need to be configured for WYSIWYG editor.

First settings can be found on admin/config/media/browser. Either you check all available plugins like you have done in screenshot or leave all unchecked for allowing all. That's already done by you.

Next is to check permissions, where you have to give Add and upload new files, view own files etc permissions (like my screenshot below)

Another permission to check is Use media browser, which you must have done & so that it's appearing. Once these are in place, it should work for the role you are checking.


use drupal_add_js for file outside drupal dir

In D6, no dice, but in D7, you could fudge it with setting $options to external and then using the full sitename and path to the file.


Change Profile2 Profile Type after registration

It's not currently possible with this module. The project page advertises a hook_simple_fb_connect_register_alter() hook to take action on registration, but looking at the current 7.1.15 version & the 7.2.x branch reveals only a placeholder hook. You'll have to wait for the maintainer to implement it, or to use another module that allows hooks following FB authentication.


Use Views to display tabs such as, "Add User Relationship," "Send message," etc

I didn't understand your question clearly, where are you getting those tabs from? If its a View you could use the Views Display Tabs module, unfortunately the D7 port still hasn't been started it seems: http://drupal.org/node/985960 - Its a good time to write a patch for it or hire someone to do it for you.


There is a module for that.  Its called TB Mega Menu.  It allows you to add markup and stuff to a menu.  It's pretty robust, if this is not what you are looking for then you will need to look into a custom solution such as a module or using views.


From the filter criteria choose the age field tick the exposed filter.
Choose grouped filters from the filter type to expose.
Choose the widget type. Then add values after changing the operator to 'is between'


Views: How to list nodes that are referencing to nodes, pointing to the current node

Create a view that filters C nodes. Go to view advanced options and add a relationship with the field in B which references A and choose Referencing entity. Give a name name "children" to this relationship. Then create another relationship based on the field in A that references B. For this relationship use the previous relationship. Name this one grandchildren. Last add fields you need from the A nodes and dont forget to use relationship grandchildren for each one.

Alternatively use node A as base table and use the referring entity relationship type. Now you want to check require relationship to emulate an inner sql join and thus filter out B and C nodes with no references


You can do the following.

Add Taxonomy ID field too your view
In your template or rewrite use the following as your url {{url('entity.taxonomy_term.canonical', {'taxonomy_term': tid})}} or {{path('entity.taxonomy_term.canonical', {'taxonomy_term': tid})}}


Any valid SQL expression is allowed, and that includes placeholders (like in that code), literal values, or SQL functions calls (including aggregate functions, such as COUNT(*)).

$query2->addExpression(':the_group_type', 'Type', array(':the_group_type' => 'Group')) is equivalent, in plain SQL, to 'Group' AS Type.
It is an expression that is widely used in the Views module. For example, if you enable the "Add Views signature to all SQL queries" option, the query executed by the Views module will be similar to the following one. (This is the query I get for the front page view.)

SELECT node.sticky AS node_sticky, node.created AS node_created, node.nid AS nid, 'frontpage:default' AS view_name
FROM
{node} node
WHERE (( (node.promote <> '0') AND (node.status = '1') ))
ORDER BY node_sticky DESC, node_created DESC
LIMIT 10 OFFSET 0

The 'frontpage:default' AS view_name part is added using SelectQuery::addExpression() in a way similar to what the code you show does.


How do you join a custom table to a node from a field with hook_views_data()

When you have a field you have a table for it with stored values, so you just add the fields table to your query
Like

/**
 * Implements hook_views_query_alter().
 */
function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
   $query->addTable('my_fields_table');
   $query->addWhere(<condition group id>, '<table_column>', <value>, '<operator>');
   // These you can use to alter the behaviour for your condition group.
   //$query->setWhereGroup('OR/AND', <condition group id>);
   // This one is for the global group behavior.
   //$query->setGroupOperator('<OR/AND>');
  }
}


You're overwriting the form elements that are already there, some of which are fields and so need to have their array structured very specifically (Why is hook_form_alter so messy in d7? has some background for that).

You can alter existing elements in the form without overwriting the whole thing like so:

$form['comment_body']['#prefix'] = '
Comment';
$form['comment_body']['#suffix'] = '
',


how to adjust size of an existing field through api in hook_update?

If you want to get around the restrictions imposed by the FieldAPI, and you're positive the change won't cause any data loss, you could just do it manually:

$field_name = 'spelersfiche_va_antwoord';

// Get the current settings
$result = db_query('SELECT data FROM {field_config} WHERE field_name = :name', array(':name' => $field_name))->fetchField();

// Change the settings
$data = unserialize($result);
$data['settings']['max_length'] = '511';

// Write settings back to the database.
db_update('field_config')
  ->fields(array('data' => serialize($data)))
  ->condition('field_name', $field_name)
  ->execute();

// Update the value column in both the _data and _revision tables for the field
$new_field = array('type' => 'varchar', 'length' => 511);
$col_name = $field_name . '_value';

db_change_field("field_data_$field_name", $col_name, $col_name, $new_field);
db_change_field("field_revision_$field_name", $col_name, $col_name, $new_field);

// Flush the caches
drupal_flush_all_caches();


How to disable a file upload button for anonymous users?

The Field permissions module should help you achieve this.

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

  Enable field permissions on any entity, not just nodes.

  Role-based field permissions allowing different viewing patterned
  based on what access the user has.

  Author-level permissions allow viewing and editing of fields based on
  who the entity owner is.

  Permissions for each field are not enabled by default. Instead,
  administrators can enable these permissions explicitly for the fields
  where this feature is needed.


How can I lock out non-authenticated users from a whole taxonomy

I ended up using Rabbit Hole, it seams to do everything I was looking for.  More details from the module's project page:

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


How do you create a view in which users can assign tasks to themselves?

Please go through the following modules,

To do list for Drupal 6 only

  Offers a content-type for a simple To do list. It can be used for anything that needs to be done: getting milk at the store, reminding yourself to update a profile, telling your users to vote on a poll by a certain date...

and myTinyTodo - Available for D6 & D7

  A simple way to manage your todo list. This module is based on myTinyTodo.

Otherwise you can do the same system with your current approach


How to render a region in custom module twig template

I'd recommend to install the Twig Tweak module: It provides (amongst others) an operator for that:
{{ drupal_region('my_region_name') }}


Solution: The way to do this is to add an address Field in the View as Content datasource: address in the Admin GUI.

And select Use entity field rendering.

Under REWRITE RESULTS
 Select: Override the output of this field with custom text

And in the textbox I added in my case:

{{ title }}
{{ field_address }}


Profile pictures not displaying in forum

I had also posted my question to my university drupal help list and managed to find an answer.  I don't know how much of this applies to the general community (it may only apply to my specific Drupal install at my university because they include automated configuration adjustments), but here is the solution that worked for me:

My main folder is called simply drupal.  In the file

/drupal/.htaccess

I had changed the line

Options +FollowSymLinks

to instead read

Options +SymLinksIfOwnerMatch

The problem was that I had not changed a second copy of this file in another location:

/drupal/sites/default/files/.htaccess

I made the same changes to this file and now the images show.  I did not simple copy one file to the other location, because the files contain different options and only the one line needed a change.  Again, my drupal install might be unique to my university, but these edits are so minor that I think someone else could try them without getting into too much trouble.  Maybe someone else could lend more insight if needed.


In Fields add Path and _Exclude from display. In your title, uncheckmark Link to the Content.

In rewrite results, checkmark Override the output of this field with custom text and put Custom Text. Alternatively, in rewrite results, checkmark Output this field as a custom link, for the path put {{ path }} and scroll down a bit to Title text and write your title here.


How to display add node form below the view in Drupal 6?

You should check Form Block module. This block can be placed in any region beside your view.


You simply need to run array_filter on $items - this will remove the empty entries.

Whether this should be handled by theme_item_list or not is debatable. It doesn't make semantic sense to theme empty list items - however in most cases the filtering would not be necessary, so from a performance point of view it doesn't make sense for theme_item_list to do it.


What you're asking is not necessarily Drupal related (although there is the Color module which also shows a color value in a select list, you could look into using the Color module to use its select widget or colorpicker instead of a taxonomy listing of colors by English name).

Anyways, if you want to stick with using a taxonomy select with like "blue" being the 3rd option in the select list -- you could reference this StackOverflow example using Jquery to style select items. You could make a call to drupal_add_js() in a theme function whenever your view and its filters are shown on the page to add the necessary jquery.

I would recommend looking into the Color module in the long run.


Looking at webform_submission_access, prior to getting the PDF url, try:

// Where $sid is the webform submission id
$_SESSION['webform_submission'][$sid] = TRUE;

If that works for the anonymous user, it may grant access to view that submission.


Applying Patches to Drupal modules - How to deal with error messages?

Thanks for all the help. I worked this out!

When I was applying the patch, I placed the patch file in the root module directory. But it actually has to go inside in the directory of the actual module. Whoops!

E.g.

The patch goes inside of sites>all>modules>views_calc
and not inside of sites>all>modules.


Array to string conversion in DrupalDefaultEntityController->cacheGet()

There's a very quick fix already, posted several weeks later after IntegrityFirst's answer.

See https://drupal.org/comment/7812787#comment-7812787 and this patch: https://drupal.org/files/drupal7.entity-system.1525176-104.patch (thanks to Molot for link to core bug thread).

It turns out that there is a function in Drupal core that supports multidimensional array diff causing this bug, but it's just not used there.

So, fix is to replace array_diff_assoc (not recursive) with drupal_array_diff_assoc_recursive (recursive, as it comes from its name) at line 364 of includes/entity.inc (see DrupalDefaultEntityController::cacheGet if line number differs or if patch fails).


How and where do I programmatically add a menu to the Navigation menu?

I'd suggest checking out hook_menu(). For example, the following implementation of hook_menu() placed in either a module or template.php should insert a menu item into the navigation menu for anonymous users. Take a look at the User module for some good examples of how to implement hook_menu() for different user roles.

function MODULE_menu() {
   $items = array();
   $items['the/menu/path'] = array(
   'access callback' => 'user_is_anonymous',  //or 'user_is_logged_in' to check if logged in
   'type' => MENU_NORMAL_ITEM,
   'menu_name' => 'navigation',
   'title' => t('Title of Menu Item'),
  );
  return $items;
}


When you select the filter 'Has taxonomy terms (with depth)' under your 'Filter Criteria' section, make sure you select the correct vocabulary on the first screen of your setup.  There is a section for you to determine which vocabulary's terms you are trying to select from.

On the second screen, make sure you check the 'Expose this filter to visitors, to allow them to change it' checkbox.  It is actually unchecked by default.

It should then show up at the top of your view in the preview window.


Fresh Drupal Install, UnmetDependenciesException

I did another LAMP install and it worked. So IDK why it didn't before.

Although accidentally I managed to break it when using a bad php.ini file, so I guess that's one possibility.


How Do i implement an alternative for the Privatemsg Bulkmail module?

Looks like there are currently no plans for a D7 version of the Privatemsg Bulkmail module you are referring to. However, I'd use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the VBO module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

Introducing Views Bulk Operations.
More details about VBO settings.
Using Rules componens with more than one parameter.
Using VBO to load list of objects into Rules.

In this specific case;

use Views bulk operations to create the list of your users to be targeted.
use Rules action "Send a message" (provided by Privatemsg module).

PS: yet another great usage of the Rules module, in this case in combination with the Privatemsg module. So I wouldn't worry too much about the Privatemsg Bulkmail module not being available for D7.


Firstly, your $base_url should be fully qualified: http://www.example.com.

Secondly, you should configure your $base_url to be 'dynamic' - different for development, staging and production.  Detect the 'environment' and then set the $base_url accordingly.

As for the broken styling, I have seen broken theme problems related to file system rights.  It may be that your site is using CSS/JS aggregation / compression.  These compressed files are created on the fly by Drupal (check admin/config/development/performance).  If there are file/folder rights issues on the production, the files will not be created.

May be useful to check the error log (/admin/reports/dblog) - could just point you in the right direction.


What are the advantages of using Apache Solr over the core search module?

This article gives a thorough and straight-forward answer to your question.

  Performance improvements with Apache Solr

  High traffic sites running search queries against the database can start to degrade the site’s overall performance if the database becomes the bottleneck. This is also true for lower traffic sites with lots of content. Complex search queries can be slow to run.

  Requirements for features such as faceted search (see below) are becoming increasingly common. This can be delivered in conjunction with Drupal core search using the Faceted Search module but the inherent scalability and performance implications are well documented by the module’s maintainers.

   Other useful Apache Solr features

  Apache Solr also supports indexing and searching multiple sites (imagine internal intranet site and external corporate site), indexing attachments (eg PDFs, Excel documents) and recommended content blocks driven by a node’s taxonomy. The module page and the Acquia Search overview both have a good overview of the Apache Solr features that Drupal supports.


Setting my lightbox setting to Display: Single lightbox: large => large fixed the problem. thanks. :)


Get term name for page title from term id passed in the contextual filter?

Answers Updated:
try this hook, hook_view_pre_render()

  This hook is called right before the render process. The query has
  been executed, and the pre_render() phase has already happened for
  handlers, so all data should be available.

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
     $term = taxonomy_term_load(arg('arg_position_in_url'));
     $title = $term->name;
     $view->build_info['title'] = $title;
  }
}


*.routing.yml is used to define custom endpoints and their receiving controllers. It's the config version for hook_menu in D8. If the module does not introduce custom paths, then it will not need one.


How do I get navigation menu on top with narrow viewport?

@media width queries in CSS
http://css-tricks.com/css-media-queries/
At a certain width, you could use a different positioning tactic, forcing it up top.
Via Javascript, checking against: window.innerWidth or body .clientWidth
Many things you could do here, from changing CSS rules, to actually moving it in the DOM.
Using a Drupal module for responsive menus like:
https://www.drupal.org/project/responsive_navigation
or https://www.drupal.org/project/responsive_menus


Your question is 2-fold. 1 part of your question is drupal based, the other is (MySQL) SQL based ...

That line of code is as follows:

$query->orderby[0]: adds an ORDER BY clause fragment to the SQL query string. More could be tacked onto using php such as $query->orderby[1] or $query->orderby[123] ... these just build up an ordered php array of orderby sql clauses ...
The SQL expression FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') is used by MySQL within the ORDER BY clause and takes an additional value of DESC or ASC. That function uses the cardinality of the passed in parameters as a weighted list of values for orderby. You are correct in how FIELD() is ordering the results ....

You may order by any selected field in SQL or by an aggregate function in MySQL. Not all DBMS have the same functionality, for example as seen here the above FIELD() function in MySQL has to be emulated in Postgres:
https://stackoverflow.com/questions/1309624/simulating-mysqls-order-by-field-in-postgresql

So far as I'm aware there is no list of all the functions or values one could order by ...


Drupal 7 add ajax listener directly to node form

This interceptor_dvd_listener_callback() should return value, in documentation:

  After form processing is complete, ajax_form_callback() calls the
  function named by #ajax['callback'], which returns the form element
  that has been updated and needs to be returned to the browser, or
  alternatively, an array of custom Ajax commands.

Why don't you use this:
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states

It is drupal 7 standard feature to hide or show some fields when some elements has some states.


Webform api - using the included hooks to change email destination?

Was not sure wether to delete original question or not, but decided on leaving it here since it is listed by google when searching for webform api help.

Turns out the code above does execute the hook. I went for lunch, came back, retried and suddenly the hook is invoked as expected.

To anyone needing to change form values or email info on submission of a webform, this hook is the real deal.

Cheers!


How can I display a view title with 'No Results Behaviour'?

i believe this is your problem

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

solution is here

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

If you have a view and you want to be able to programmatically change the title of, you can do it by implementing hook_views_pre_render in your custom module:
alter it when particular view or field is not having any result

<?php
function mymodule_views_pre_render(&$view) {
  if ($view->name == 'my_view_name' && $view->current_display == 'my_display_id') {
    // Here you can do any php you want to get the title you need for your view.
    $view->build_info['title'] = "My custom title!";
  }
}
?>

If you are altering the query and you have argument substitutions affecting the title, you can change these in hook_views_query_alter:

<?php
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view_name' && $view->current_display == 'my_display_id') {
      // First substitution - you may want !1 or %2, etc
      $view->build_info['substitutions']['%1'] = $new_substitution;
    }
}
?>

Views Displayed as Pages

Use this:

drupal_set_title('My custom title!');

Instead of:

$view->build_info['title'] = "My custom title!";

or some thing like this in views 3

<?php
/**
 * Implements hook_views_pre_view().
 */
function MODULENAME_views_pre_render($view) {
  if ($view->name == 'my_view_name') {
    if ($view->current_display == 'my_display_name') {
      $view->set_title('my new title');
    }
  }
}
?>


How to replace large, original images used for image caching?

hook the image while finishing the upload process, then compress the size is a good Drupal approach much better than another batch job since the project can be managed in a good scope.

If it is a once-off task, script batch job is fast and efficiency but regarding the daily normal usage, a module is more preferable.

There is a module ImageAPI Optimize (or Image Optimize)

BTW, the theory could be:

Something like the following may be what you need:

function MYMODULE_node_insert($node) {

// See if a file has been added
  if ($file_items = field_get_items('node', $node, 'field_file')) {
    // Get the first file item
    $file_item = array_shift($file_items);

// Load the file object from the cache/database
$file = file_load($file_item['fid']);

// The path to the file is in $file->uri
do_something_with($file->uri);

}
}

REF: https://api.drupal.org/api/drupal/includes%21file.inc/group/file/7


You can use hook_form_alter to add a custom submit handler where you can set the redirection path.

See the FAPI for more details about form redirection.


hook_user_login, hook_user_logout not firing

If you are directly editing the code of a module that is already enabled, then the problem is that the list of hooks implemented by modules are cached by Drupal. Drupal doesn't have a setting for disabling this cache; the only cache you can disable/enable on Drupal is for the content served to the anonymous users.

Both the hooks you are referring are invoked by functions that, directly or indirectly, call module_implements(), which contains the following code:

  if ($reset) {
    $implementations = array();
    cache_set('module_implements', array(), 'cache_bootstrap');
    drupal_static_reset('module_hook_info');
    drupal_static_reset('drupal_alter');
    cache_clear_all('hook_info', 'cache_bootstrap');
    return;
  }

  // Fetch implementations from cache.
  if (empty($implementations)) {
    $implementations = cache_get('module_implements', 'cache_bootstrap');
    if ($implementations === FALSE) {
      $implementations = array();
    }
    else {
      $implementations = $implementations->data;
    }
  }

The cache containing the list of the implemented hooks is cleared when a module is updated, enabled, or disabled. Actually, it is enough you visit the page showing the list of the modules, click on the button to save the configuration, and the cache should be automatically reset; if that doesn't work, then you can disable and then re-enable a module.

I see the code is using variables that are not defined, nor set, by the code you are showing; I take you didn't show all the code, but if you are effectively showing all the code, then the $user, $password, and $data variables are not initialized.

As side note, you should use drupal_http_request(), instead of using the cURL functions.


Drupal views grouping: amount by grouping

The Views Grouping Row Limit module allows you to specify how many rows you want to display in each group, maybe it can help you.


ubercart - Add sku to a product catalog title via tokenizing it or adding it to a view?

I can see SKU in views, see the screenshot below, so not sure if I'm missing something obvious about the question.


How to create checkbox instead of radio for just 1 allowed value?

Since checkboxes are multi-value options by nature. It would be detrimental to usability to override this default and expected behavior. You could change the validation as jimajamma suggests, but this would definitely lead to mass confusion amongst your users, as checkboxes are specifically intended for use for multi-value selections.

A slightly better, but still sub-optimal, option would be to use javascript to make sure that only one checkbox option is selected. Using javascript would at least mean that  users have immediate feedback rather than finding out after submitting the form (and it failing validation) that the completely expected behavior of multiple values for checkbox form items is no acceptable in this situation.

Since the Drupal core issue that you linked to specifically refers to sets of radio options that are not set as required, why not re-phrase the radio options so that you can make the form item be required?

For example, instead of the three options

beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

create a forth option,

none|No preference
beef|I prefer beef
chicken|I prefer chicken
veggie|I am a vegetarian

and set that fourth option as the default. In this way, you can successfully work-around the existing Drupal bug without confusing your users with non-standard behavior of form items and without creating any additional work for them. Not only is this better for users, but it requires no code customizations and is more easily maintainable (and easier to change once the bug is fixed).

In a situation with a yes/no question, you could use checkboxes and only provide one option, "Yes." Then you could evaluate "Yes" in its unchecked state the same way you would have evaluated "No" in its checked state.


Drupal 7 views: Get NID in views using contextual filters

If you are loading and displaying your view in the node.tpl or node--<content-type>.tpl file, you could supply the current node nid as an argument to your block view, then you can setup a contextual filter for Content: Nid. I would do something like this:

// get view
$view = views_get_view('YOUR_VIEW_NAME');
// set display for view
$view->set_display('YOUR_VIEW_BLOCK_NAME');
// set current node nid as argument to view
$view->set_arguments(array($node->nid));
// execute view
$view->execute();
// render view
print $view->render();


How can I disable or hide warnings and errors shown in the backend?

You actually should fix the error.

And since it's not a very good idea to globally disable all errors and warnings for all roles, please use Disable Messages to disable error messages based on configurable conditions.

  Gives a site owner options to disable specific messages shown to end
  users. The core Drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all Drupal site owners are keen to show all the messages
  sent out by Drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.

  Features

  Filter out messages that match a full text string exactly
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.


You could do it by implementing hook_url_outbound_alter(), and hook_url_inbound_alter().

With the first hook, you alter the links that are being output from Drupal; you would increase the value of $options['query']['page'].
With the second hook, you alter the links being received from Drupal; you should find the '?page=' string in the URL, and decrease the number after that string.

Keep in mind that $_GET['page'] can be a string like '1,2,4,5,6' if the page has more than one pager. See the code of pager_find_page().

Also, hook_url_outbound_alter() receive the query parameters in $options, while hook_url_inbound_alter() receives just a string for the URL, which also contains the query part.


Do not repeat the field name for sub columns: Instead of e.g. field_location/field_location_lat use only field_location/lat, in the process:  section.

There also is no need to manually set interal keys like entity_id or revision_id: Only set the destination plugin and the field values, and Migrate module will fill all other internal columns for you.

destination:
  plugin: entity:node

process:
  title: title
  type:
    plugin: default_value
    value: NODE_BUNDLE_NAME
  langcode:
    plugin: default_value
    value: 'en'
  field_location/lat: latitude
  field_location/lng: longitude


Some CSS and JS is not loading for anonymous users

First of all you should find where the CSS or JS is being added, this being Drupal, there are tons of ways that this could happen.

if they're added using drupal_add_js and drupal_add_css (which they should be) you have to make sure that possible template differences beetween roles and permissions both print out the $styles and $scripts variables.

If the theme follows D7 standards there should be an html.tpl.php file somewhere (most likely the root) in the theme, that would be the best place to start looking. If that does not exist, try page.tpl.php.

Post your findings and it'll be easier for us to help you.


How to add a class to vertical tabs created using Form API?

You are right vartical tabs don't have #attributes element.
But you can:

1) place vertical tabs in #container element with class. There you can use #attributes

2) you can add #prefix, #suffix into tabs:

$tabs['#prefix'] = '
';

$tabs['#suffix'] = '
';


Drush 8 should work just fine with remote sites running Drush 7.

To get around the error message you are seeing, run composer install from the Drush directory.

If you want to install multiple versions of Drush to run locally, the easiest way to do it is to manage your Drupal site with Composer, and add a 'require drush' line in your composer.json.  If your global Drush is at least version 7, then you will find that Drush automatically dispatches to the site-local Drush whenever you target it.

One really good use-case for doing this would be to run Drush 7 stable as your global Drush, but use Drush 8 with any Drupal 8 site.

See also:

https://github.com/drupal-composer/drupal-project
https://github.com/pantheon-systems/example-drupal7-composer


You should use the jQuery provided by Drupal and try to work with what Drupal provides (JavaScript, Form API, Theme system, etc.) instead of trying to work without it or, worse, against it. The jQuery update module allow you to use updated jQuery releases in Drupal. That would be 1.6.2 for Drupal 7 and 1.3.2 for Drupal 6. Drupal 7 also provides jQuery UI while for Drupal 6, the jQuery UI module should be used to provide it. This way you can avoid compatibility issues between different version of the same library, unnecessary workarounds and fixes over fixes.

Also, you shouldn't use $(document).ready() in Drupal, but add your function to Drupal.behaviors as explained in the Drupal JavaScript API guide (also available for Drupal 6). And off course, for the form generation, validation and submission server-side code, you should use the Form API.

Keep in mind that your are trying to add a form to a Drupal site, not to a stand alone simple PHP script that doesn't already provides all the (server-side) API your need.


Your file would need to be fieldable. i.e. - using something like the File Entity module.

More complete media solutions exists also, like Media, Scald, or Asset exist which would provide this and more.


How to use node field tokens as a value in Metatags module?

This from Mario Steinitz (in comments) answered the question:

"I'm not at my desk anymore for today, but I'm pretty sure you have the [node] token available for content meta tags and can access field content as well. We're using these tokens regularly for all D8 sites we're working on. Where did you try to add them?"


Can't correctly reference bundle in EntityFieldQuery, field_get_items

A couple of things...first one is you haven't loaded the nodes. If you change

$stories = $result['node'];

to

$stories = node_load_multiple(array_keys($result['node']));

You'll have the fully loaded node objects available.

The other two things are both related; field_view_field() and field_view_value() both accept a single entity; currently you're trying to pass an array, which it won't like.

A simple loop will fix that:

foreach ($stories as $story) {
  $output[] = field_view_field('node', $story, 'field_date');
}

And similar for field_get_items().


Drush pm-download removing the destination folder

This sort of request is best made in the issue queue, since what you are requesting is a change in behavior in Drush.  The default behavior for pm-download is to always provide a clean unaltered copy of the module; I for one would be reluctant to alter this behavior, but I could potentially get behind a new option that introduced 'merge' behavior.

A better option, I think, would be for you to download Drupal to a temporary folder, and do the merge yourself in your script as a secondary step.


How to show the author as entity reference of a file used in a node?

Yes, ultimately a query needs the file ID. There are a few ways you can get the file ID considered. You should pick the mode most consistent with the rest of your site build:

If you are using the Panels suite you then have a ton of options both within the "Views content panes" module (that comes as a part of CTools) and within Panels itself for setting up the passing of arguments. My main recommendation under this approach would be to use the "context" concept within panels to go from the node object to the file object that can then be passed to a contextual filter.
You've tried Entity Views Attach. This works well if it is appropriate to show the author of the file within the View Mode of the file.
You've also tried the "Provide default value" option under contextual filter handing but there isn't a suboption for "value from field X on current node". These are "default argument handlers" and here is the code for the one you are using: http://cgit.drupalcode.org/views/tree/modules/node/views_handler_argument_node_nid.inc and the generic API page for them: https://api.drupal.org/api/views/plugins!views_plugin_argument_default.inc/group/views_argument_default_plugins/7 If you are comfortable with PHP you can write one custom to your use case.
Views Field View (https://www.drupal.org/project/views_field_view) is maybe the ugliest (but perhaps the easiest) option. It would allow you to construct a View that takes the argument of the NID (which you already have working) and using that to get the FID as field which would then be passed to another View. A View inside a View.


The buildForm method needs to return $form. Not $test. You're missing key items by ignoring the $form variable. Properly set the form items (not as their own variable) and remove the custom theme hook you're trying to do. Cut this down to its simplest pieces first just to get it working and go from there.

Get rid of $a $b $c variables as that doesn't make any sense, just use $form. Your submit info is not making it into the form itself, which is why it isn't working.


How to display a field before node title?

This is really quite simple with Drupal 7.

With render and hide you know have the posibility to control the placement of a single element in $content without having to print out all the items yourself like was needed in Drupal 6.

A simplified node template looks like this:

<?php print $title; ?>

    <?php print render($content); ?>

A little modification would handle your needs:

  <?php print render($content['field_name_of_image']); ?>

<?php print $title; ?>

    <?php print render($content); ?>

Using render, you can output an element. This is more clever than simply printing stuff, as Drupal will keep track of what has been rendered, to avoid the same thing being printed twice on the place. When rendering the field above the title you are also removing for what's rendered when $content is rendered.


How to make one view with different taxonomy terms in different rows?

I wanted to post this as a comment but my rep is not high enough. I had asked a similar question and received an answer here: Separate grid rows by field value


Contextual filter on taxonomy view using URL

Create a view, Create a page display and set it's path to features/%

Then add a contextual filter: Taxonomy term: name.

That's it! when you visit the page /features/blubbles page, if there is a taxonomy term named blubbles, the views will display the fields you have added. You may add a validation criteria (while adding the contextual filter) to limit terms to an specific vocabulary.

However you might want to consider using panels too. After enabling panels, page manager and views content panes modules, you can create a page and set it's path as features/%term (notice the arg is %term not %) set it's type as String.

Add a display to your view of type content pane
Add the contextual filter, taxonomy term: name.
In configuration section of the views display there is a 'argument input', open it and set type of argument from panels argumen
In the opened configuration popup, select second argument as the name is second parameter in your path. you may select from panels context too if you can configure the panels accordingly.
Go to panels configuration page, add content to one of regions, select views panes not regular views!
Visit the panels page, done.

This way you have more control over your page. you can create another views, such as a view directly showing nodes, filtered by a taxonomy. you can send the term name just like you sent in the views above.
In the first view it's not a good idea to show nodes if you are only planning to display the term fields only once.

This question : Contextual filter with a block view is about views blocks and contextual filters. I still suggest using pages. views content pane will play role if a block for you.


Rules is not designed to work with client side events. They way Rules is designed, it won't make any sense to try to make it aware of client side events.

Your best course of action would be to write some custom JavaScript.

If you want to add some javascript code to a page using rules, that would be possible if you created a custom action that added the JavaSript you wanted to the site.


Treat bonuses as fields, and use Computed Field to manage calculations:

  Computed Field is a very powerful CCK 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. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of CCK fields. So start cooking up your PHP based values!

In user's profile, keep an Entity Reference to all users that registered from his links or gave his name at registration. Use simple recursion or deep scan to make actual computation, and you're there.


As jQuery UI is part of Drupal 8 core for the calendar functionality you can simply do this:

modulename.libraries.yml

modulename.id:
 version: VERSION
 js:
  js/custom.js: {}
 dependencies:
  - core/jquery
  - core/jquery.ui.datepicker

custom.js

function ($, Drupal) {
  "use strict";
  Drupal.behaviors.mymodule = {
    attach: function(context) {
      $('#views-exposed-form-id
       input:text').datepicker();
     }
   };
})(jQuery, Drupal);

To query for data between event starts & end date you can use hook_view_query_alter();

modulename.module

use \Drupal\views\Plugin\views\query\QueryPluginBase;
use \Drupal\views\ViewExecutable;

function modulename_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ( $view->id() !== "view_id" ) { return; }
 foreach ($query->where as &$condition_group) {
  foreach ($condition_group['conditions'] as $index => &$condition) {
   if (!empty($view->exposed_raw_input['start']['min']) && !empty($view->exposed_raw_input['start']['max'])) {
$query->addWhereExpression(0,'FROM_UNIXTIME(tablename.created, :format ) BETWEEN :min AND :max ',
array(':min' => $view->exposed_raw_input['start']['min'],':max' => $view->exposed_raw_input['start']['max'],':format' => '%m/%e/%Y'));
   }
  }
 }
}

Idea is to use BETWEEN :min AND :max in your query. Maybe there are other ways to solve this problem, but this is how I would approach this issue.


Seeking module/technique for giving site visitors a download "gift" in exchage for their email

I would use Webform Rules Module. On submit and validation of an email address have a Rule that redirects the user to a download page. Of course, since it's Rules you might be able to conjure up all kinds of wonderful complicated things. I also found these lovely tutorials on Rules at NodeOne. However, you might be able to write a module faster than it would take to work through all those videos.


hook function not deleting nodes when calling node_delete

A scheduled cron runs as uid 0, the anonymous user, and therefore probably can't delete anything.  When you run cron from the admin menu, it uses your current session, so you can delete things.

If you google for "drupal run cron as uid 1" you will see some workarounds.  Most involve switching users inside your hook_cron and then restoring the session when you are done.

What should be possible is to invoke drush -u XXX cron from your crontab instead of the the typical wget method.  Some searching will dig up the proper way to call it (you need to get the environment and Drupal basedir set right).  I would not run as uid 1, though.  Pick (or create) a user with sufficient permissions to do what you need.

What would also be possible is to create a script that bootstraps, loads the proper user, and then does your task.  Lock this down in your .htaccess and call it from your crontab.


How to programatically change a user image field to match the user's latest completed goal?

I finally found the answer thanks to the Devel module and the user_save API page! After investigating a random goal with dpm(goals_load(GOAL_ID));, I wrote the following code:

 function top_goals_completed_goal($goal_id, $uid) {
    $user = user_load($uid);
    $goal = goals_load($goal_id);
    $fid = $goal->goal_img['und'][0]['fid'];
    $img_title = $goal->goal_img['und'][0]['filename'];

    $edit = array();
    $edit['field_last_goal']['und']['0']['fid'] = $fid;

    user_save($user, $edit);
}


$primary = menu_local_tasks(0);

$secondary = menu_local_tasks(1);

See: http://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_local_tasks/7

It's actually not a hook, it's just a function that gathers the items while in context.

There is a hook to alter the items: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_local_tasks_alter/7


How to setup Drush core development environment?

a) Start by reading the following material (if you haven't already):

https://github.com/drush-ops/drush/tree/master/tests/README.md
https://github.com/drush-ops/drush/blob/master/CONTRIBUTING.md

b) Fork the drush-ops/drush repository, so that you can track your work (and eventually start a PR from your fork back to the original repo).

c) Install the local dev environment provided using docker-compose:

git clone https://github.com/stefanospetrakis/drush.git
cd drush
git checkout -b YOUR_BRANCH
docker-compose up -d
docker-compose exec drupal composer install

At this point you have the source code of drush, equiped with tests. You can do your changes and additions to it and commit/push to your fork, as your project evolves.

d) You can test your changes at any time, against the official drush test suite to make sure you didn't break something:

docker-compose exec drupal composer test

e) Additionally, you can test your work in progress inside your own drupal projects, by replacing the standard drush in composer with your own fork, that would need three things:

Adding an extra repository in your Drupal's composer.json, e.g.:

"type": "git",
"url": "https://github.com/stefanospetrakis/drush"

Aliasing the "drush/drush" package, in order to pull from your current working branch in your repo, based on the exact version number found in composer.lock, e.g.:

require "drush/drush": "dev-YOUR_BRANCH as 9.5.2",

Use source (git) for your drush package, e.g.

{
"config": {
    "preferred-install": {
        "drush/drush": "source",
        "*": "dist"
    }
}

}
Possibly do manual pulls inside the vendor/drush/drush folder in order to get your latest work.

And as @greg_1_anderson mentioned in a separate answer, you will find Drupal Core under the sut directory of drush's source code.

Good luck!

P.S.: Replace https://github.com/stefanospetrakis/drush.git with the URL of your fork of drush-ops/drush repository, this is just an example.


Passing values from text field to a javascript function in Drupal 8

You do not need to use Drupal Behaviours for this, this can be done with States API which ultimately uses javascript.

e.g.

$form['calculate'] = array(
  '#type' => 'submit',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="weight"]' => array(
        'filled' => TRUE,
      ':input[name="number"]' => array(
        'filled' => TRUE,
      ),
    ),
  ),
);

You can change the fields name as per your requirement. Hope this will help.

Thanks


Implementing a custom Field API field is quite simply, there are already many tutorials and example modules available. One of the advantages is that it provides all the storage handling for you and it can provide handling for multiple values and so on.

Note that Field API provides the framework for field level access permissions but it doesn't implement it. Just like node_access. So that's not a reason against using it.

See http://drupal.org/project/field_permissions for a project that provides an implementation for that.


On your theme's template.php override the theme_pager function as below.You need to do some HTML customization as per your need.Hope this helps.

function themename_pager(&$variables){

$element = $variables['element'];
global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;

$pager_current = $pager_page_array[$element] + 1;
$pager_max = $pager_total[$element];
$total_items = $pager_total_items[$element];
$limit = ($pager_limits[$element])?$pager_limits[$element]:10;

$start = ($pager_current-1)*$limit+1;
$end = ($pager_max != $pager_current)?$pager_current*$limit:$total_items;

$text = "$start to $end of $total_items Records";
return $text.theme_pager($variables);
}


How to implement admin verification for selected user profile fields?

Step 1: Create a designated role

Create a role like (say) "Member", and use this role within Drupal's Permission system to disallow access to anything on your website for users who do not (yet) have access to this "Member" role. Make sure that for profiles that did not go live yet, you do not grant access to this role.

Step 2: Activate user accounts after registration

When a new registration request arrives, check if it satisfies some minimal requirements to have the account's status be changed to "active" (you don't want to do so for e.g. spammers).

If the request does satisfy your requirements, the administrator just grants the Member role (and is finished with this registration request review).

But if it doesn't satisfy your requirements yet, then the administrator should NOT (repeat NOT) grant the designated role from Step 1. To allow the admin to indicate "I reject", use the Flag module so that the admin can flag such user. Since flags are entities (fieldable), you could also add a (text?) field to have the admin add some kind of "reject reasons". Such flagging could then result in sending an eMail to the registered (not approved yet) user to ask for appropriate changes by the registered user.

Step 3: Wait for the user to apply account updates

After the user (who does not yet have the "Member" role applied new updates to relevant profile fields, send an appropriate eMail to the administrator to request a new profile review. To do so, use the Rules module with a custom rule that looks similar to this one (in Rules export format):

{ "rules_notify_admin_about_selected_profile_updates" : {
    "LABEL" : "Notify admin about selected profile updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "site:current-user" ], "type" : "user" } },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "data_is" : { "data" : [ "account:uid" ], "value" : [ "site:current-user:uid" ] } },
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-to-be-approved" ],
          "value" : [ "account:field-to-be-approved" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Thanks for updating your account, the site administrator will soon review your updates." } },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "Updated profile needs your review",
          "message" : "Please review the updates to the profile of user [account:name], located at [account:url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about the magic in the above rule (use the Rules UI to import it in your own site, after you applied relevant changes like the field name):

Rules Event: After updating an account
Rules Conditions:

An entity of type "user" is updated.
The account being updated is from the currently logged in user.
The user does NOT have the role with ID=4 (which is assumed to match the Member role, adapt this ID to fit your needs).
The actual profile field is "some" field you want to monitor / review / approve. In this case I used a field with machine name field_to_be_approved (adapt to fit your own needs, and add similar conditions if you want to check other fields also).

Rules Actions:

Show an informational message to the user who performed these updates (though only if all Rules Conditions are satisfied).
Send an appropriate eMail to the site admin (adapt the content of it to fit your needs).

Step 4:

You may want to add an extra Rules Action in the previous step to unflag the user again. So that the administrator can fag the user again if after updating the profile the administrator still rejects (by repeating from Step 2). However I recommend to NOT add such extra step, so that the administrator can still see the "reject reason" (from Step 2). And if a 2nd reject is needed, all it takes for the admin is to (a) unflag the user and (b) right away flags the user again, but now possibly with a new reject reason. True, an extra click for the administrator, but the advantage is that the prior reject reason (if used) did not automatically get deleted.

At the point where the updates are OK, just have your admin grant access to this role for any registered user as soon as "the profile goes live". A possible way to further automate this is to create another rule which automagically grants the Member role after the admin "unflags" the user (= removes the flag set in Step 2). If you wonder how to do so, use this link ...

Bonus:

The above approach, with some minor variations, could also be used to catch users who after their account got verified, update their profiles in a way that would not have been allowed when they first registered.


How to add jQuery Datepicker option which accepts a function as an argument

You have to ommit the 'option' parameter, the following modified version of your code worked for me:

(function ($) {

  Drupal.behaviors.ios2 = {
    attach: function (context, settings) {
      $('#edit-arrival-date-datepicker-popup-1').datepicker({
        onClose: function (date) {
          // date will have the new date or empty string if no date
          // has been selected.
          alert(date);
          // Do something
        }
      });
    }
  };

})(jQuery);


How to translate Select List options used in exposed filters of a view?

I can confirm this issue. While working with BEF, me too faced the same translation problem. Probably this is a bug in BEF module which do not handle translations properly. Meanwhile, to solve this issue I explicitly used a hook_form_views_exposed_form_alter() to wrap the non-translatable string in t().

May this helps you.


If you are just trying to create links to pages within your Drupal site you can use relative paths and when Drupal renders the link it will show as a complete URL.  You only need to have the domain name in the path when you are linking to an external site (not the same domain)

Example, to link to the Site Configuration admin page:

Use admin/settings instead of http://localhost/admin/settings and it will still show up in your menu as a full URL.


Change from email id when admin approved user account

I don't have enough reputation to comment, so I am expanding user1081275's answer -

The message id for the confirmation message you want to alter is 'status_activated'.

You can intercept outgoing mail with hook_mail_alter() in a custom module as described at https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7

function mycustommodule_mail_alter(&$message) {
  if ($message['id'] == 'status_activated') {
    $message['from'] = "mail@whatever.com";
  }
}

Per user.module, the ids for other messages defined by the User module in _user_mail_notify() are:

 *   - 'register_admin_created': Welcome message for user created by the admin.
 *   - 'register_no_approval_required': Welcome message when user
 *     self-registers.
 *   - 'register_pending_approval': Welcome message, user pending admin
 *     approval.
 *   - 'password_reset': Password recovery request.
 *   - 'status_activated': Account activated.
 *   - 'status_blocked': Account blocked.
 *   - 'cancel_confirm': Account cancellation request.
 *   - 'status_canceled': Account canceled.


Hide whole edit content link column to users

Set up multiple page views displays with the same path.

You can clone your page views display to accomplish this.

Keep their path settings the same.

In the regular user one, remove the Edit field. Be careful that you are only editing "This page (override)" and NOT "All displays."

In the admin views display, under Page Settings > Access, restrict your admin view to role=admin.

Re-order the views displays so the most restrictive (admin) views display is first.

To reorder the displays, look for the item "edit view name/description" in the upper-right corner of the screen and expand it to select "reorder displays" - this will take you to a screen where you can drag and drop the views displays. After you put yours in the right order, click "Apply" then save your view.

Hope this helps.


$content['field_name'] is always set.
You can check if it's empty.

if (isset($content['field_name']) && !empty($content['field_name']):
  print render($content['field_name']);
endif;


How to translate a custom module template file?

The .po file must be located in custom_module/translations directory - see locale_batch_by_component function. Translation file though is only imported once module gets installed, so in case you want to reimport the file you would have to run some "hacky" drush command, such as drush php-eval "locale_system_update(array('custom_module'));drush_backend_batch_process();"

You can also upload .po file manually using Drupal's admin UI.


Programmatically get all names of an entity reference field

The easiest way to get what you want is something like this:

$names = [];
foreach ($node->field_tags as $item) {
  if ($item->entity) {
    $names[$item->entity->id()] = $item->entity->label();
  }
}

->entity is a so called computed property, it doesn't show up in getValues(). All reference fields have it.

And yes, forget about print_r() on entity or other complex objects. They contain objects that reference each other, and print_r() can't handle that. If you have an entity, always use print_r($entity->toArray()), then you get the field values only. You could install devel module or use a debugger, but that will give you the internal structure of an entity, which is not really want you want to see.


You would need to create a custom module for this as you want to create X number of orders for X number of users. Reason why you need a custom module is because each order is its own node with a bunch of references to other data on the site. Doing this in bulk would require you to know all the tables data that are updated and inserted when an order is created.


Sandbox module doesn't show any download link

Sandbox projects may not have releases.

There is a "Has project releases" checkbox, in the "Releases" vertical tab when you edit your sandbox, but it will be automatically cleared.

Thus it is not possible, but if you wish, you can apply for full project access.


How do you add an incrementing primary key to an existing table?

This actually seems to be an issue in Drupal Core where creating a serial field on an existing table is not possible in MySQL 5.7+ without first creating an int field and converting that to autoincrement (this issue does not show up in MySQL 5.6 and below). Please see https://www.drupal.org/node/2615496 for a patch that fixes this issue for new releases of MySQL. It might be worthwhile to update that patch to be rolled into 8.x so it will allow us to patch 7.x.


OPTION 1

Use hook_form_alter to add a Clear or Cancel button/anchor tag(blank)
Add simple JS code to clear the fields

OPTION 2

Use hook_form_alter to add a Clear or Cancel button/anchor tag(blank)
Use Drupal AJAX Framework

UPDATE

You can use the hook_form_alter() inside your template.php file which is better based on your comment being more on the front-end side.

Next is you just need to get the ID of the form you want to alter/update by its form id value and just converting the dashes to underscores. An example would be:

<form id="leo-form">
  // form elements here
</form>

then you need to target it in your hook_form_alter() like so:

// Implements hook_form_alter.
function themename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'leo_form') {
    // place your code to add the clear button here
  }
}


It's pretty easy if you're able to install the Administration Views module.

It replaces the default admin/people page with a view, which you can easily customise to add the user id as another column in the table.

If you're not able to use that module there are ways to do it in code, but it's a bit fiddly. I did roughly the same thing a couple of months ago (before I'd come across Admin Views) so let me know if you want me to dig the code out and post it here.


D7 auto nodetitle, title with pattern node:nid and rules php node_save($node)

You are on the right track. I have been doing this for a while now with the following code snippet in rules.

auto_nodetitle_operations_update(array($node->nid));


variables was definitely the key here. In my hook_language_types_info_alter hook, simply updating the variable with my callback did the trick:

/**
 * Implements hook_language_types_info_alter()
 */
function MODULE_language_types_info_alter(array &$language_types) {
  $config = variable_get("language_negotiation_" . LANGUAGE_TYPE_URL);

  // put my callback first, since the first one to return a language wins.
  $newconfig['MODULE_provider']['callbacks']['language'] = 'MODULE_language_provider_callback';
  $newconfig['MODULE_provider']['file'] = drupal_get_path('module', 'MODULE') . '/MODULE.module';
  $newconfig += $config;

  variable_set("language_negotiation_" . LANGUAGE_TYPE_URL, $newconfig);
}


If I understand you correctly then you just need to break out of the foreach loop after you got 6 thumbnails saved in the $output variable. With that addition the end of your loop would look like this:

if ($i == 1) break;
$i--;
endforeach;


You don't need to use a form items markup attribute just to print some HTML.
Instead,  change your menu item to a simple page function, not a drupal_get_form eg

$items['live_amplified/hello_world'] = array(
  'title' => 'Live Amplified',
  'description' => 'Simple custom hook_menu() implementation.',
  'page callback' => 'hello_world_page',
  'page arguments' => array('static_page_form'),
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
);

and add a simple function to return some markup

function hello_world_page() {
  return "Hello World";
}

But as @Adam Balsam described, if you have a lot of content and want to parse another PHP file, you would do it using file_get_contents() but Drupal already has a way of dealing with this that uses it (although it may be convoluted)

You would use hook_theme.

First you need to declare your implementation, this does two things: tells Drupal to look for a template file (the file you want to render) at some location, and it exposes your template to prerocessing for adding variables.

Declare your theme

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'helloworld' => array(
      'template'  => 'hello-world',
      'path'      => drupal_get_path('module', 'mymodule') . '/templates',
      'arguments' => array('node' => NULL),
    ),
  );
}

Create a preprocess function to give it some variables

function mymodule_preprocess_helloworld(&$vars) {
  $vars['who'] = "World";
}

Create a template file hello-world.tpl.php in /mymodule/templates/ with the content

<h2>Hello <?php print $who; ?> </h2>

Call it from where ever you like, in this case a menu page.

function hello_world_page() {
  return theme('helloworld');
}

At first it may seem a bit convoluted but it allows you to create templates with variables and exposes theme to themeing so other modules and themes can change both the variables and the markup.


new content type with fields for username and password

Under Configuration->People->Account settings->Manage fields in the menu (admin/config/people/accounts/fields) you can add fields to the User entity, such as name and address.

Fields added to the User entity has a settings whether they should be displayed on user registration form.


Why do I get this exception when running a query?

DEFAULT is a reserved MySQL keyword. Try:

db_insert('prod_conf_procuct_parameter')
  ->fields(array(
    'prod_id'=> $arg,
    'price'=> $price,
    'key1' => $key1,
    'key2' => $key2,
    '`default`' => $default
    )
  )
  ->execute();

phpmyadmin does a lot of hand-holding and error squashing for you - it's not advisable to use it as a canonical source of truth for a particular query string's validity.


How to retrieve image URL from Media Bundle field in Twig Template

Image URL Formatter

This module adds a url formatter for image field. Then you can output
image url directly.

Enable the module, edit your image field, change the formatter to url.
Now {{ content.field_image }} will print the url instead of rendering the image.


Removing main content block on frontpage

Sorry, but that's not the way to do it.

Instead of creating a block display in Views, create a page display. Choose a path for your views page, for instance "home", and save the view. Next you go to /admin/config/system/site-information and change the value for 'Default front page' (it probably says "node" now) to the path you chose for your view ("home").

When you follow this approach, the main content on your front page will be the view.


How to exclude fields from print page version (html, pdf)?

A quick peek in the code shows that the Print module utilizes "View Modes", which is a good thing. More info in Entity view mode and Drupal 7 custom node view modes.

You should create a new suitable view mode or re-use one you already have. This allows you to control the settings with the Field UI, while still allowing you custom templates if you need to.


redirect to another page on webform submit using [current-page:query:?] token

I've found that no token is required for this...

You can select Confirmation page as the redirect location, then the ?destination= parameter will just work. Not sure that this is a documented feature, though.

See also https://drupal.stackexchange.com/questions/120466/webform-redirect-to-referring-page-on-submit-not-showing-message which highlights a downside to this method.


How can I use xx time ago in Drupal 8 comments?

Have a look at what is mentioned on "Formatting the way the date/time is displayed in Drupal 8". Here is a quote from it:

  You can change the date format for comment using template_preprocess_comment(). For example, normally in comments the comment created time is displayed like Thu, 12/17/2015 - 23:04. We can change the format to look like 3 weeks 5 Days ago.

And this is the sample code mentioned below it:

/**
* Implements hook_preprocess_comment
*/
function THEME_NAME_preprocess_comment(&$variables) {
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@username commented !datetime', array('@username' => $variables['author'], '!datetime' => '<span class="comments-ago">' . $variables['created'] . ' ago </span>'));
}

I haven't tested this code (yet), but it looks pretty close to what you're asking for ...


The Menu API is fairly extensive.  It is likely there is already a function available to return what you need.

For example, you can return an entire menu tree using the menu_tree_all_data().

$navigation_tree = menu_tree_all_data('navigation');

You could also return everything known to the menu router with menu_get_router();

$everything = menu_get_router();


How to auto redirect link with node/id to /name?

You are probably looking for Global Redirect. That module does what you want it to do, it checks to see if there is a path alias for things like node/1 and if there is it will redirect to that URL.

GlobalRedirect is a simple module which…

Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.

Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect_admin module. In Drupal 6, the settings page is bundled into the module.

Note: That is straight from the module page, they haven't updated that Drupal 5-6 statement to include D7 I don't guess but I use this module in D7 and it works also.


Views: Page by view-group where multiple results are loaded under each group from a relationship

One possible solution would be to use the Views Field View module.

You can make a view that displays course instances as an unordered list, with a contextual filter that is the parent course nid.

Then create a view of courses, limited to 10, and add a view field to the view, using the first view you made. You can pass in the course nid as the contextual filter, so that field just displays the result of the first view for that particular course.


How to change the field label on my registration form? Drupal 7

Just tested on a D7 site and it should work fine for you if you name the alter function "mytheme_form_alter" instead of "mymodule_form_alter"?

See this answer for more detail on module options: Changing the registration form


Implement  hook_taxonomy_term_presave  in a custom module and alter the terms according using PHP's string manipulation functions.


Token Content Access blocks access for author too

I briefly looked at the module. I think you will need to make some serious code changes, I could not find an easy tweak.


Check if the entity is new from the entity insert hook

hook_entity_insert() is invoked only when an entity is created, not updated. That is evident from the method invoking it, EntityStorageBase::doPostSave().

  // Allow code to run after saving.
  $entity->postSave($this, $update);
  $this->invokeHook($update ? 'update' : 'insert', $entity);

hook_entity_update() is invoked for an entity being updated; otherwise hook_entity_insert() is invoked.

See also the description for the $update parameter passed to EntityStorageBase::doPostSave().

  bool $update: Specifies whether the entity is being updated or created.


What's the "Drupal" way of creating image links?

l() allows for HTML too, you just need to pass it as one of the options:

$link = l($image_html, $path, array('html' => TRUE));

That'll stop the first parameter being passed through check_plain(), so the the full HTML you pass in will be wrapped in the <a> tag.

I'd advise using this method if the alternative is writing the link out manually, you get the benefit of automatic alias-translation and it's less prone to small errors in the HTML (of which I for one always make loads).


Path (URL) to call custom module function

The best way to do this is to build a custom module and implement the hook hook_menu().

You'll need to implement:

a .info file with metadata about your
module
a .module file containing
hook_menu() and your callback

foo.module should look like this:

function foo_menu() {
  $items = array();
  $items['foo/myurl'] = array( // change 'foo/myurl' to the url you want
    'title' => 'Callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  return $items;
}

function custom_callback () {
  // Parse $_REQUEST parameters
  return 'success';
}


How to display the input box next to the label in a form?

you can do this with css float

A more difficult ways that render the items via php preprocessing before css adjusts the layout) would be to create a php template file and use theme functions for the form in your theme

Here is tutorial that uses both methods http://www.jaypan.com/tutorial/themeing-drupal-7-forms-including-css-and-js

also, it depends on what kind of form you are theming. Here is another example for webforms https://drupal.org/node/1157306


Webform - Show/Hide fields based on day of the week selected from Datepicker

I think the easiest solution is to do this with jQuery.

To get the value from the datepicker field and convert it to a weekday you might do something like this.

Add this function to your JS file:

// Accepts a Date object or date string that is recognized by the Date.parse() method
function getDayOfWeek(date) {
  var dayOfWeek = new Date(date).getDay();
  return isNaN(dayOfWeek) ? null : [0, 1, 2, 3, 4, 5, 6][dayOfWeek];
}

Use this code to get the value from the datepicker:

var datepicker = $('#your_datepicker_id').datepicker("getDate");

Then do like this:

var today = new Date();
if (!today.getDay() == getDayOfWeek(datepicker)) {
  $('.field-names-to-hide').hide();
}

I think that something like this will do it.


how can i access a node variable inside of theme_preprocess_page function?

Have you tried field_view_values() and field_get_items()

function mytheme_preprocess_page(&$variables) {
    if (!empty($variables['node'])) {
      $output = '';
      $node = $variables['node'];
      $items = field_get_items('node', $node, 'field name');
      foreach ($items as $item) {
        $field_output = field_view_value('node', $node, 'field name', $item);
        $output .= render($field_output);
      }
      // Set $variables with the value you need.
    }
  }

Explained in here how to access node variables in region preprocess function?

I think you should also be able to use entity_metadata_wrapper as follow

$node = $variables['node'];
$wrapper = entity_metadata_wrapper('node',$node);
$libStatus = $wrapper->field_feature_library_status->value();


Update the settings of a View Display programmatically

Answering my own question:
The settings are not made on the display, but on the handler.

$view = Views::getView('existing_view');
$display = $view->newDisplay('page', 'New page', 'page_2');

// ViewExecutable::setHandlerOption($display_id, $type, $id, $option, $value)
$view->setHandlerOption('page_2', 'argument', 'nid', 'admin_label', 'Foo');
$view->save();

Options and values correspond to the values in a View YAML config file, under display_options.

Important is that you find out the correct $type argument.

I had a look at the array keys returned from ViewExecutable::getHandlers.

"field"
"argument"
"sort"
"filter"
"relationship"
"header"
"footer"
"empty"


The 'Publish' button isn't determined by the state of the node according to your workflow.  Actually, whether the 'Publish' button appears is determined by the permissions you have as a user.

So if you look at the content in the s1 state, you may see the 'Publish' button, because you're an admin.  An author looking at that same piece of content in the s1 state, however, shouldn't see that button based on the workflow moderation permissions you've given them.  Does that make sense?  It's not the workflow state, but the individual's permissions that determine whether that button is available.

So test it out by logging in as an author to see what they would see.  If you can still see the 'Publish' button when you're logged in as an author, that may mean that you've inadvertently given that role a permission you didn't intend, such as 'Administer content', so double-check the permissions again.  :0)

My authors definitely can't publish in some of my workflow states!


Users can spam votes and users will get userpoints

One simple way to avoid this is to add a rule that removes points whenever a downvote happens. Same rule, different condition (if the value is -1) and different action: Decrease points.


Here's a solution for exactly that setup. (The fields you can control under display/rss are only the CCK fields, not the XML element you want to remove from the feed).


How can I send a Privatemsg using Rules and have the name of the site as the sender?

You could create an account for sending the messages and in rules, use direct input and enter its user id. That way, you could also see replies to welcome message.


Rebuild in Features tripping HTTP 500 Error

This Drupal install was on a local environment using MAMP. The problem was solved when I increased the max_execution_time in MAMP's php.ini from 30 to 100.