How to Give abilty to filter content by geography, separate from language?

This is a really broad and quite opinion-based request. But what I'd suggest is you completely keep Drupal's core internationalization functionality and just add languages including their region subtag:

es-AR
es-ES
es-MX
...

You then can decide to use just the region as their label, which will then be displayed by the built-in language switcher.

A really positive side effect of this is you'd already have your content optimized for SEO pretty well (given that the region specific content actually are translations of each other).

Resources

https://www.w3.org/International/articles/language-tags/
http://www.lingoes.net/en/translator/langcode.htm

Another approach would be to just go for one Drupal language and instead introduce a new field "Region" or "Country" to the node type you need this filtering for and build your own View with filters to display nodes or teasers of nodes matching the selected country or region.


Try for the first query:

$notarr = db_select('uc_packages', 'p')
           ->fields('p', array('package_id'))
           ->condition('p.order_id', $order_id)
           ->condition('p.sid', NULL)
           ->execute()
           ->fetchCol();

That way, you'll get the array of package_id, without needing the additional foreach, and avoid the stdClass string conversion error

Presumably also query 2 should be checking package_id instead


how to insert a block within a cck input form in Drupal 7?

So you're block is created and working?  You just want to insert it as a field?  You can do that using Display Suite, or if you want to insert it within a text field you could try Insert Block (still in dev)

I think Display Suite is the way to go, it is a very comprehensive module so it takes time to take it all in, but it provides very intuitive solutions for Drupal shortcomings, such as displaying a block as if it were a field.


So generally, preprocess hooks impact the specific theme item or template, so hook_preprocess_page() impacts the page.html.twig and hook_preprocess_html() does so for html.html.twig.  You mentioned your twig template for node, to add variables to that you would need to implement hook_preprocess_node().

Your question was adding variables to all templates, I believe for that you would use just hook_preprocess() (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_preprocess/8.2.x) - though I have never tried it.  I imagine it would be called for every theme call so that could create a lot of overhead.

And don't forget to 'Clear all caches' under admin->config->development->performance when you create new preprocess hooks or template files.


If the file is correctly saved as UTF-8, it should correctly handle Unicode characters. So far, I have had a problem with the saved file just because the editor I was using added the BOM ("Byte Order Mark") used to identify the encoding of the file, but the error was a different one.

Generally speaking, the Drupal way to have a translatable site is to use t() in your code, which requires the English string that will then be translated to the language set as default, basing on the translation provided to the Language module.

The code should be rather be similar to the following one:

<?php if ($display_submitted): ?>
  <footer class="submitted"><?php t('Submitted by !username on !datetime', array('!username' => $name, '!datetime' => $date)););</footer>
<?php endif; ?>

The alternative is implementing hook_preprocess_node(&$variables) (template_preprocess_page() in a theme), and initialize the variable $variables['submitted'] to the string you want to appear ("Submitted by !username on !datetime" in the code I shown before).


Yes, By default og_group_ref field  (organic group field machine name by default  add to your content types) accept multi value, if  for you it's Number of values set 1 value, go to you content type manage fields and change it to unlimited value


Hiding a field title label of a field collections field?

After our discussion, these are the steps to clear the labels from a published node field collection field.

Head to Structure > Field Collections > Manage Display (For your collection)
Under the label column, make sure all select boxes are set to "Hidden".
Next, head to Structure > Content Types > Your Content Type > Manage Display (For your collection)
Same as before, Under the label column, make sure all select boxes are set to "Hidden".

This wont hide the labels in the admin node/add/yourcontenttype page, but when you save the node, and look at the published page, the labels will be gone.

To remove the edit, delete and add links, Structure > Content Types > Your Content Type > Manage Display and click the settings icon on your field collection field. Then simply delete the edit, delete and add text from the text fields. Click update. Then save the content type.


Why is the button to install a new module missing in the admin interface?

You need to enable the core Update Manager module:

  Checks for available updates, and can securely install or update modules and themes via a web interface.

Emphasis mine.

Also make sure the user you're logging in as has the Administer software updates permission granted. If it's user 1, you already have access.


Render view in code with the proper view mode

It was the theme. The rendering took place under cron and ran under the administration theme rather than the usual one, meaning different twigs. The solution will be to sub-theme the admin theme to make sure all the relevant twigs are present there, too.


Drupal 7: Local site URLs all point to production site

I found the issue.

If you're using the module "Domain Access", the uninstall hooks do not work properly (or at least they didn't on our site).

You'll need to go into your DB and change the domain settings after you've disabled your module.

All of the Domain module tables that have your production (or old URL) in them need to be changed. Removing those tables will likely corrupt your DB and make the site unusable.


I know you said you didn't want to use it, but this is a PERFECT use case for Panels.  I'm not a huge Panels user and will generally steer clear of it if I can, but sometimes you have to step outside of your comfort zone and just use the best tool for the job.

There's a video here that focuses on using Views and Panels for a home page layout.

  In this Drupal video tutorial we take a brief look at panels. I show
  you how to recreate a home page that relies on views content panes. As
  a result, we create a two column home page panel which pulls in recent
  content from across all content types and shows which users are
  online.

But if you are REALLY set in your ways, then go with the blocks.  You can always put the blocks into Panels at a later date.


Use a CURL to work with sites without api?

The Services module provides API endpoints, it doesn't help to make HTTP requests.

All Drupal has natively for making HTTP requests is drupal_http_request(). Personally I'd recommend using a library like Guzzle instead, it's much more pleasing to work with, and has support for submitting forms. Plus it's in core for Drupal 8 so you know it's got the seal of approval.

PHP's DOMDocument should be more than enough to help with processing the response.


Can you get the regular node title to show up? Is the node title important? I am wondering if Automatic Entity Label could help you at all. Formerly Auto Node Title. https://drupal.org/project/auto_entitylabel
You may want to look at Rules and VBO. Creating a Rules Component "Action Set" and adding it to a Views Bulk Operations could handle this use case. Make sure you set the permissions properly when you create the Action Set (there is a collapsed field set called "Settings" when you edit a Rules Component that contains permissions settings for each Component)


I have never used this, but you can try hook_feeds_after_import.  You will likely need to kpr the $source parameter to the hook.

You may also be able to something with Rules.  Feeds events don't appear in Rules (unless there is a module I don't know about), but you may be able to trigger on the node save and update events filtered to the content type(s) that you are importing to.


Edit field in contentType B when creating or editing node of contentType A

Try the following:

/**
 * Implements hook_node_presave().
 */
function yourModule_node_presave($node) {
  if ($node->type == 'your_typeA') {
    yourModule_change_value($node);
  }
}

function yourModule_change_value($node) {
  if (isset($node->field_node_referenced[LANGUAGE_NONE][0]['target_id'])) {
    //- Get referenced node id
    $referenced_node_id = $node->field_node_referenced[LANGUAGE_NONE][0]['target_id'];
    //- Load referenced node
    $wrapper = entity_metadata_wrapper('node', $referenced_node_id);
    $wrapper->field_name->set(array(
      'value' => 'test new field value'
    ));
    $wrapper->save();
  }
}


You can use the IMCE module.

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

  Features

  Basic file operations: upload, delete
  Image(jpg, png, gif) operations: resize, create thumbnails, preview
  Support for private file system
  Configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions
  Personal or shared folders for users
  Permissions per directory
  Ftp-like directory navigation
  File sorting by name, size, dimensions, date
  Tabbed interface for file operations
  Keyboard shortcuts(up, down, insert(or enter), delete, home, end, ctrl+A, R(esize), T(humbnails), U(pload)).
  Built-in support for inline image/file insertion into textareas
  Multiple file selection(using ctrl or shift)
  Ajax file operations
  Themable layout using tpl files


If you want to use the Drupal database code in a website, without bootstrapping Drupal, you need the following files:

includes/database/database.inc
includes/database/sqlite/database.inc
includes/database/mysql/database.inc
includes/database/pgsql/database.inc

The code in those files needs to be changed, as:

The code uses the DRUPAL_ROOT constant. You could remove the code using that constant, and replace it with code that automatically loads the include file containing the class. For example, the following code uses DRUPAL_ROOT because Drupal cannot use its code registry until there isn't a database connection active, as its code registry uses a database table.

// We cannot rely on the registry yet, because the registry requires an
// open database connection.
$driver_class = 'DatabaseConnection_' . $driver;
require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
$new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
$new_connection->setTarget($target);
$new_connection->setKey($key);

It could be rewritten as follows, if you register your own function with spl_autoload_register().

$driver_class = 'DatabaseConnection_' . $driver;
$new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
$new_connection->setTarget($target);
$new_connection->setKey($key);

The functions use the global $databases, which is normally defined in the settings.php file. You could replace that variable with a static property of the Database class.


Creating redirects for files (images) on Pantheon

Thanks to Sarah at Pantheon for walking me through this.

File redirects aren't really possible using the same logic used to do PHP redirects for URLs.  Requests to files are managed by the server and don't run through settings.php (Drupal) or wp-config.php (WP).  It is not possible to intercept those like a URL served by the application.

If you were running your own nginx server you could manage this in a .conf file, but on Pantheon the nginx.conf isn't editable on a per-site basis since it's set platform-wide (https://pantheon.io/docs/platform-considerations/#nginxconf)

A workaround could be to utilize a third-party CDN like Cloudflare to create nginx-like redirects before you hit the server.


How to let the user enter the price for particular product in Commerce Kickstart?

I guess you're looking for Auction

  An auction is a process of buying and selling goods or services by
  offering them up for bid, taking bids, and then selling the item to
  the highest bidder.

Check Commerce Auction module

  This module lets you create auction/reverse auction websites using
  drupal commerce.


Selecting a product attribute from a select list won't update other attribute fields

Why don't you have the clean urls enabled?
I think for the ajax to function, we might require or at least assume clean urls. That may be all the problem is.
The reason your injected fields aren't changing is because of a javascript error, and it is often not related to Drupal Commerce at all, could be a theme issue.


Buying same product simultaneously in drupal commerce

Check out Commerce Stock - https://www.drupal.org/project/commerce_stock. The module itself will expose hooks for controlling stock. Or there are sub modules it provides - Simple Stock and Simple Stock Rules - which add an integer field and use Rules to validate purchases.

This runs on Add to Cart, Can Checkout, and prior to purchase.


How to hide "Manage Fields" and "Manage Display" tabs

I know this was answered a while back, but there's a solution that doesn't require any custom or special modules.

If you disable the core fields ui module, the Manage Fields and Manage Display tabs will not show.

If this is a production site, this should be fine to do as you'll have already configured the fields how you want them. If you ever need to make a change, just enable the module again briefly.


Procedure For Cloning Commerce Collection Taxonomy View Page?

I think you need a view based on your products filtered to your taxonomy term. You should be able to do this with the views UI more easily than the way you're attempting to programatically.

I think you're misunderstand the theme folder altogether and how drupal presents the page that is rendered in the browser. The theme folder has mark up, images, and CSS that defines how your whole site is displayed, the views are generated, not stored as discrete files in your theme folder.

If you're on the kickstart demo store. Go to Product Categories, delete the defaults, add your own 'categories', and that should change the demo store to reflect your own set up. You should play with a default drupal set up to get familiar


How can I switch to an external db with Views API?

Sounds as if you need the Views Database Connector module.

From the project page:

  Views Database Connector is a powerful module that gives Views full access to external database tables found in the settings for your Drupal installation. With this module, you can setup a view around any table in any database configuration. This can be extremely useful to pull external data from a database to show to your users in a view.


Is there a way to consume external web services and show results in Views?

The advised solutions are based on getting the data into the database first, then showing it in Views.

An alternative is querying the service directly from Views, by using a custom query backend.
Checkout http://drupal.org/node/958270 for links to custom backends which you can use as an example for writing your own (it's not a lot of work)


Import REST API web Application to Drupal 7

You should use services module to create rest services in drupal 7. Simply install it and create end point by admin setting form. When will you create this then you can check your end point like this :

http://www.yoursite.com/{end-point}

If this will give success message then you successfully created end point and now you can move forward.

Services module will give some predefined service resource for user, node and comment etc. simply enable those and use them and if you want to create your own services then you should implement hook_services_resources hook, it will create a service resource. It will return an associative array which include api version, operations (create, delete, retrieve), actions etc. You can simply convert your services to drupal just follow some standard that is defined by services module and my recommendation is just look at any resource of this contrib module, for example look at user resource inside services module you will understand it.


Add class to first field in fields views

You can use preprocess field hook which is supported in drupal 8 also .
Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}


Drupal gives error while add content or edit node

One possibility to solve is to increase "max_allowed_packet" .

    Go to xampp\mysql\bin
    Open my.ini
    Change "max_allowed_packet" from "1m" to "16m"
    Save my.ini
    Now restart MySql through the XAMPP control panel.

Or

settings.php

ini_set('max_allowed_packet', '1024M');


Try Page Title module and configure the Page title for Front Page.

Download & enable https://drupal.org/project/page_title module.
Configure Page Title from admin/config/search/page-title And change
the Frontpage.


How to get specific fields in the login form

You can create a user login template. In your theme file, put this function in and replace your_themename with the machine name of your theme.

function your_themename_theme() {
  $items = array();
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'your_themename') . '/templates',
  'template' => 'user-login',
  'preprocess functions' => array(
  'your_themename_preprocess_user_login'
  ),
 );
return $items;
}

Then, you can split the individual fields of the form up in a template file called user-login.tpl.php and rearrange them however you want.

<?php
    print drupal_render($form['name']);
    print drupal_render($form['pass']);
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['actions']);
?>

Source: High Rock Media


How can I restrict external URLs in link field to allow only certain domains?

You need to write your own custom validation contraint and add this constraint to your field.
Docs: https://www.drupal.org/docs/drupal-apis/entity-api/entity-validation-api/providing-a-custom-validation-constraint
I've used that example to create a "force HTTPS" link field constraint
src/Plugin/Validation/Constraint/Https.php
<?php

namespace Drupal\MYMODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that the submitted URL is starting with https://
 *
 * @Constraint(
 *   id = "MY_CONSTRAINT_ID",
 *   label = @Translation("Https", context = "Validation"),
 *   type = "string"
 * )
 */
class Https extends Constraint {
  public $notHttps = '%uri is not a secure site (not starting with https://)';
}

src/Plugin/Validation/Constraint/HttpsValidator.php
<?php

namespace Drupal\MYMODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the Https constraint.
 */
class HttpsValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    $item = $items->first();
    if (!isset($item)) {
      return NULL;
    }

    foreach ($items as $item) {
      /* CHANGE THIS, e.g. here you can check for domain names */
      if (strpos($item->uri, 'https://') !== 0) {
        $this->context->addViolation($constraint->notHttps, ['%uri' => $item->uri]);
      }
    }
  }
}

MYMODULE.module
<?php

use Drupal\Core\Entity\EntityTypeInterface;

function MYMODULE_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($bundle === 'MY_ENTITY_BUNDLE' && $entity_type->id() == 'MY_ENTITY_TYPE') {
    if (isset($fields['MY_FIELD'])) {
      $fields['MY_FIELD']->addConstraint('MY_CONSTRAINT_ID', []);
    }
  }
}


Redirect after login through different login form

I found out how to solve this issue. I install popup module and activate popup block submodule. then go to block  and set "User login" block in "Navigation" region (I use bootstrap theme), after that open configuration of "User login" module and do it popup. I hope it  will usefull for anybody.


How to override title for exposed filter views under cache?

Is there any option to set title for cached views. I want searched field as page title.

Yes, you could use jQuery to grab the search field text and then change the title on page load. Probably, you will need to use cookies.


Why doesn't composer install drush on $HOME/bin directory?

Composer downloads things and puts them where you (read: your composer/project settings) tells them to go; or in the default location if you haven't specified. It won't assume you want to link anything from the downloaded library into /usr/bin, though this could theoretically be done through a post-install-cmd in your composer.json file.

If you install something globally you'll find it in ~/.composer/vendor/ (the Drush executable will probably be in ~/.composer/vendor/bin/drush).

You've probably missed this important step from the instructions to install Drush via Composer:

  Make sure Composer's global bin directory is on the system PATH

Once Composer's global bin path is in your system path, the drush command will start working immediately.


Can I reference a views page via an entity reference field?

Not out of the box, but you can use the Views reference field module to get that functionality:

  In Drupal 8, Views are now identified as entities and the core Entity Reference Module is able to reference Views, however not Views displays. This module leverages core entity reference module functionality to add the display ID so that a View can be rendered in a field formatter.


How can I dynamically add drupal behaviors to a form from php using ajax?

Yes you can attach Drupal Behaviors to newly added elements (DOM nodes):

You can check ahah.js (in Drupal.ahah.prototype.success):

// Attach all javascript behaviors to the new content, if it was successfully
// added to the page, this if statement allows #ahah[wrapper] to be optional.
if (new_content.parents('html').length > 0) {
  Drupal.attachBehaviors(new_content);
}

Or if your script creates the elements (answer on stackoverflow about drupal-behaviours):

var newNodes = $('Hello World').appendTo('#someDiv');
Drupal.attachBehaviors(newNodes);


How to use Rules to send an eMail containing a list of nodes with a selected value in a field?

How to get a complete list

Your Rules Events and Conditions are pretty sure OK, but you're missing a crucial Rules Action: a Rules Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

The result of your first Rules Action is actually a list, which as per the "PROVIDE" that is shown in your exported rule, is stored in a variable named entity_fetched (BTW, try to use a more meaningful variable name for such variables, eg nodes_with_status_sendmail).

As you seemed to have understood already, the entity-fetched:0, ..., entity-fetched:3, correspond to your 1st, 2nd, 3rd and 4th node in that list of fetched entities (nodes).

What you need to do to repair your Rules Actions, are these steps:

AFTER your first Rules Action (which fetch those nodes, and which is fine), use the link "Add a loop" as the next (2nd) Rules Action. When doing so, specify these options for it (note the looooong variable name for my 'List item', I bet you get its meaning just from its name ...):

Parameter: List: [entity-fetched]
List item: Single node with status sendmail (single_node_with_status_sendmail)

Within that loop you added, use the link to the right of it (in the Rules UI), to "Add an action". That way the Rules Action you add, will be performed as part of the loop. The actual Rules Action to add is similar to the (last) Rules Action you already have, with machine name "mimemail". As you will notice while creating a similar Rules Action, you'll now be able to select/specify tokens that relate to ... single_node_with_status_sendmail. However, the content of your eMail message body should now only (repeat: only!) refer to the "List item" being processed in the current iteration of the Rules loop (instead of those 4 items in your existing "mimemail" action).

As you will probably understand, since you're now processing 1 single node in each iteration, and it doesn't matter how many nodes you have in your list of nodes, there is no more restriction to 4 nodes only.
After you completed the previous step, there is no more need for the existing (last) Rules action about "mimemail", so just delete that Rules Action.

With these changes you solve your limitation of 4 nodes maximum. However, in case you don't realize yet, you may have introduced a new challenge, as detailed below ...

Solution to your problem ... might (will?) change the problem

Using the approach detailed above, the result of your adapted rule is that you will get 1 separate eMail for each node fetched via that first Rules Action (which created the list of nodes to be processed). If you typically only have a few nodes that may not be a real issue to worry about. But if you have dozens (or more?) of such nodes then you might want to consider consolidating all such eMails in a single eMail, which contains (in its eMail body) the complete list of nodes.

A possible solution to implement such consolidation, is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

Add some new Rules variable that will be used later on as part of the eMail body, before the start of your loop. Say you name the variable nodes_list_var_for_email_body.
Within your loop, for each iteration, prepend or append the value for each "list item" to that variable nodes_list_var_for_email_body.
Move your (new) "mimemail" action outside your loop, and after the loop completed. And finetune the details (configuration) of your (new) "mimemail" Rules Action. When doing so, you'll be able to select the token for nodes_list_var_for_email_body to include anywhere in your eMail body.

Summary

If you think about it, you'll end up more or less with a variation of the last Rules Action in the rule you already have, in which the body part now contains nodes-list-var-for-email-body instead of entity-fetched:0, ..., entity-fetched:3.

But for this (crucial) nodes-list-var-for-email-body token to be available, you need to (a) add the Rules Loop and (b) add 2 more Rules Actions to create the content (value) of  nodes-list-var-for-email-body.

Voilà

... That's really all it takes to get this to work.


"Allow multiple values" vs "Allow multiple filter values to work together"

Allow multiple filter values to work together is used when you want to pass multiple arguments to and match against one field.
In other words allows for 'many to one' joins

In a sense it is similar to 1, 2, 3, however if you need to pass multiple sets like 123+345 and 889+678 there need to be 2 separate joins to the same table.

(assuming sometable has multiple results for your desired value like:

|nid|yourvalue|

|1  |123      |

|1  |345      |

|2  |678      |

|3  |222      |

|1  |789      |

|1  |823      |

|1  |845      |

|2  |678      |

|3  |222      |

|1  |889      |

select node.title from node node
join sometable sometable_1 on sometable.yourvalue in (123,345)
join sometable sometable_2 on sometable.yourvalue in (889,678)

Therefore 'Allow multiple filter values to work together' is the only way to get view to return nid 1

this is useful when you need to pass arguments that come from different sources (i.e. 1 could be taxonomy terms from 2 different vocabs).

I used this only when dealing with entityreference field that references terms from different vocabularies


How do I call a controller function in a module?

If you want to define a controller, then don't use a static method:

namespace Drupal\content_statistics\Controller;

use Drupal\Core\Controller\ControllerBase;

class ContentStatisticsController extends ControllerBase {

  public function count() {
    $value = $this->t('hi');
    return $value;
  }

}

The use statement should import the class, not the namespace. But this is not the only problem.

If you want to use a controller class in a hook, create an instance of the controller and use the method of that instance:

use Drupal\content_statistics\Controller\ContentStatisticsController

$statistics = new ContentStatisticsController;
$value = $statistics->count();

Your class and method had the same name, I split the name in a controller class name and the method count().


The "more" link does not direct to the page

I guess what's been bothering you is the "preview" of you nodes.

First, by default, your new "content" ( i guess you are using articles) are promoted to the front page, but that's not where you can find all of them, especially the older ones. It's works like a "latest news" page.

Second, those articles are shown as a "preview", only the first few lines of its content can be read. The "more" link send to the full content of your article.

This link appears even if the article is short enough to be completely read in preview mode, because, only inside the page with the full content you can, for example, add comments etc... etc...

Maybe you didn't notice this because right now the articles you are writing for testing purpose are just too short


Render entity fields retrieved by EntityQuery

Fields have a view() method that accept either a view mode or an array with formatter/display settings (same format as stored in a view display config entity or passed to a base field).

$entity->get('field_date')->view('teaser').

That returns a render array that you can then display.

If you also use #type table then you can make each row a numeric child key and you can directly use the render array.


Multiple URL for one Drupal 8 website configuration

I've handled this situation very easily by setting two different Apache VirtualHost with the same DocumentRoot.

The thing you have to be very careful is the page caching of Drupal. I recommend you to read the Cache Context document on Drupal 8 who is very helpful for your situation. By passing the "url" cache context on your different render arrays, you will prevent the content of a URL to be displayed on the other.

Drupal routing system doesn't take the domain name. So there'll be no problem and a user who go on a subpage from a domain name will stay on this domain name.


This message is probably because you missed some database fields in your insert query (we do not know the field type and what exactly you are trying to achieve). Other than that, it is very odd that you attempt to insert a record directly in a Drupal field's table as this not how it is meant to be used. As per Clive's comment, this can lead to data inconsistencies, cache issues etc.

So I would strongly recommend you to take a good look at Drupal examples on how to define a custom table using Schema API, or even better take a look at this guide on using the Entity API, which you allow you to properly utilize Drupal Fields with your own custom module. Third option is to use the API of an existing module such as nodes, users etc. so that you properly save the field's value.


How can I change comment text to "DELETED" instead of actually deleting the comment?

I use module Comment Delete, rewritten for Drupal 7.
Here is the code that is responsible for what you need:

$num_replies = db_query('SELECT COUNT(cid) FROM {comment} WHERE pid = :cid AND status = :status', array(':cid' => $comment->cid, ':status' => COMMENT_PUBLISHED))->fetchField();
if ($num_replies) {
  $comment->comment_body[LANGUAGE_NONE][0]['value'] = t('[The comment subject/body has been deleted, all replies will remain]');
  comment_save($comment);
  drupal_set_message(t('The comment subject/body has been deleted, all replies will remain.'));
}
else {
  comment_delete($comment->cid);
  drupal_set_message(t('The comment has been deleted.'));
}


Contextual Filters for a Block on a Page

First create a taxonomy whose terms will be those 'contact', 'blog', 'history', 'locations'.

Then create a views page with contextual filter based on term id and set path as about/%


What should I set my Content-Security-Policy to?

The policy needs to contain every domain where assets are loaded from, which will vary depending on which services your site uses such as a CDN or third party JavaScript widgets.

For Google Analytics, it must be able to connect to www.google-analytics.com, and stats.g.doubleclick.net if Display Features tracking is enabled.
The Google Analytics module also requires the unsafe-inline policy value, since it injects the analytics snippet directly on the page.
Googalytics is an alternative built specifically for Drupal 8 that works without unsafe-inline.

Core also currently requires 'unsafe-inline' for scripts in element attributes due to its use of CKEditor 4 (see https://www.drupal.org/project/drupal/issues/2789139)

In order to test a Content Security Policy without impacting the functionality of your site, first use the Content-Security-Policy-Report-Only header instead.  This will make the browser report violations of the policy in the browser console and to the report-uri address, without blocking the content on the page.  Once you have a policy that works without violations, change the header to Content-Security-Policy.

You can also provide both headers at the same time, allowing you to test changes without the risk of breaking functionality.

Report-uri.io provides a free logging service that you can use to collect violations of both your enforced and report-only rules, and audit for any changes you may need to make.
They also have a wizard utility to help setup your policy for the first time.

Setting up a policy in Drupal 8 is also easier with the Content Security Policy module.  It integrates with Drupal 8's libraries system to automatically add script and style sources, provides an admin UI that validates your settings, provides a local handler for report violations, and will apply some optimizations to shorten the policy if possible.


Split the node edit form into multiple pages (preferably using panels variants)

Please have a look at Multistep Nodeform.

  For each step you can define which fields should be included in this
  step. "Fields" includes core-fields like "Title", "Body" or "Authoring
  information" as well as fields defined by other modules (e.g. Date).


Devel output on hooks called during cron run

You should use the function dd() to log something during cron.
Here is the doc: https://api.drupal.org/api/devel/devel.module/function/dd/7
It will log the output to a file, which later you can investigate. I think you must have private file path set.
you could use something like this, But be careful about XSS!
$export = var_export($var, TRUE) // TRUE will cause var_export to return the output not print it.
$export = nl2br($export); // Convert new lines to
 tag for display in HTML
$export = strreplace(' ', '&nbsp;'); // Again convert whitespace to HTML specific chatacter
watchdog('my_debug', $export); // That's it!

or even easier:
but again be careful about CSSF and XSS
watchdog('my_debug', '
' . var_export($variable) . '
');

dd is the safe drupal way to go.

Update
From comments so you wont miss:

... better than dd() is ddl(), from the drupal_debug_log module that enhances > the devel module... –  DrCord

Important point to developers.
If you search drupal.org modules there are many more to  make development easier. After you found and used them, it would sound impossible to go without them (devel_themer to name one). An example search.


How do you deploy a change to a main menu?

Menu items are saved in the DB, therefore you must update them using update hooks.

Something like this should work:

function MODULE_NAME_update_N() {
  $menu_link_id = 1;
  $menu_link = menu_link_load($menu_link_id);
  $menu_link['hidden'] = 0;
  menu_link_save($menu_link);
}


This answer might be helpful. In your case you could try to bubble up the attachment from the token itself:
$replacements[$original] = '<my-placeholder>';

$bubbleable_metadata->addAttachments([
  'placeholders' => [
    '<my-placeholder>' => [
      '#lazy_builder' => ['\Drupal\mytheme\MythemeLazyBuilders::replaceUid', []],
    ],
  ],
]);

You not really need the Drupal token system, you can attach placeholders almost everywhere in the rendering process, but for some cases this could be a convenient way to make a lazy builder available.


Group by parent terms from indexed node in views

You can also add the parent term to the index.

So if you have field_category as your term field you will be able to index field_product_category:parent.

Note that you may have to use the "Add related fields" section at the bottom of the fields admin page for your index to add the parent term relation before you can add the parent term tid or term name etc.

Then in your view also add the parent term name field and exclude it from display and then group by it.


How to add an existing custom field to a new content type

This has been asked before, for a brief example see Clive's answer here. The easiest thing to do is:

create your field and attach it to an entity with the UI logged in at: Admin -> Structure -> Content Types -> Manage Fields
use the code snippet in the below link, supplying your own $entity_type, $field_name and $bundle_name to get the field_create_instance() code outputted directly for you to copy/paste into your modules' hook_install().
...if you get good enough to know the Drupal Field API to build these $settings and $config arrays for fields without this code snippet -- more power to you .... I still use this code snippet myself, it saves time.


I found a workaround, but I hope someone will come up with a better solution.

If I include the Term ID as a hidden field …

… it is possible to rewrite the category image with a link generated by the router:

This works, but we are missing the hreflang attribute in the link, and the alt attribute of the category image is still English only.


You can use the example from Twig Functions:

{# Link to user entity page. #}
{{ 'View user profile'|t }}

and modify the route to point the link to the profile page:

{# Link to user profile page. #}
{{ 'View user profile'|t }}


How to use Rules to send an email to customers 1 month prior to license expiration date?

Answering my own question.

I have finally done this using hook_default_rules_configuration()
I have created a test rule with static values, then exported it and used the hook mentioned above to modify the values on run time.

This worked best for my requirements.


Apply a dynamic string to a field before validation

First You should write the these kind logic in validate function rather than the submit function.

So instead of

$form['#submit'][] = "editorhide_form_submit_handler";

you should have

$form['#validate'][] = "editorhide_form_submit_handler";

Second the first parameter passed to the function form_set_value is the form element and not the form state value so the function should look like.

form_set_value( $form['title'], $fullTitle['0'],$form_state);

I think what you are trying to achieve can be done with a custom module.

Automatic Nodetitles

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).


You cannot create a relationship from Hotel to Price. You have to go the other way.

Create a block view of Price. Configure a Relationship on the node reference to Hotel (field_hotel), and make it required. Add Content:field_price (not using relationship) and Content:Title (using the relationship) to your display, Add a sort on field_price (Ascending).

To limit the display to the Town, create a Contextual filter on field_town, have it use the relationship, and set it to Provide default value:Content ID from URL.

Configure your block to display on the Town content type, and you are done.


creating menu items with children (sub items)

How about installing Menu attributes. See if it's nofollow option works. If not, still use it by setting a class of 'no-follow' on this particular menu-item. Then add some jQuery to you pages wherein you target the anchor tag related to this class for its click event and disable the default action. I don't think there should be a conflict as Superfish opens up menus on hover, I think? But try. And also set up the menu so that it points to the first child so that Drupal menu UI will accept.

How to Disable/Inactivate Some of the Non-Leaf Menu-Items (but keep their children visible and enabled/active)


Need help on a callback function with login form

function da_form_alter (&$form, $form_state, $form_id) {
   if ($form_id == 'user_login' || $form_id == 'user_login_block' ) {
     if (isset($form_state['post']['name'])) {
       $form['#validate'][] = da_login_validate($form, $form_state);
    }
  }
}

function da_login_validate($form, $form_state) {
  // Here you should check wheather the user is valid or not..
}

Better way to do this: you should read the source code of any module. For example, read the code of Facebook Connect which does the same thing.


Drupal 7 - eRecruiter profile with Solr Fatal Errors

A lot of errors here, let's see if we can do something..

Job/Resume Search

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

When you try to invoke the action, the result does not return the query object, and for that reason you have this error, for example.

php_error.log

PHP Fatal error: Access level to SearchApiViewsHandlerField

Changing from protected to Public Field made solve this issue.

My Resume

Fatal error: Call to undefined function entity_i18n_string() in

Entity 7.x-1.x-dev released on February 28, 2012 - 08:13 no longer contains the function entity_i18n_string().


While there is a Smarty module, it has no release for Drupal 7 and I doubt there will be one.

For Drupal 4 and 5, there were various efforts made to use different template engines.  However, nearly all contributed themes for Drupal 6 and 7 are done in PHPTemplate and almost all documentation and available support are for PHPTemplate.

Even if you're already familiar with Smarty, if you're going to use Drupal seriously for more than one project I would highly recommend learning PHPTemplate.  At this point, you would have to do work to integrate Smarty into Drupal 7 on your own, which would almost certainly be harder than just learning PHPTemplate.  Going with Smarty will also limit your support options.


Can I move a webform to another drupal installation?

You didn't say what version you are using but if it is drupal 6, there is a module for that exact purpose.

http://drupal.org/project/webform_share

Edit: Since posting this, the module has been updated with a Drupal 7 branch as well.


How do I set the node title as breadcrumb?

You can use Menu Breadcrumb. It allows you to Append the page title to the breadcrumb (either as a clickable url or not) . Or you can edit your theme's page.tpl.php - simply add $title after the $breadcrumb variable.

There are also a ton of other breadcrumb modules if you want to get fancy:

Crumbs
Custom Breadcrumbs
Hansel

See an older comparison chart.


$user_ids = array(1, 2, 3, 4, 5, 6); // This will be dynamic based on your users

foreach ($user_ids as $uid) {
  // Your form element goes here
  $form['field_user_value_' . $uid ] = array(
    // form elements
  );
}

In your submit function you have above values

$values = $form_submit['values'];

foreach ($values as $key => $values) {
  if ($substr($key, 0, 17) == "field_user_value_") {
    // Push values to database
  }
}


Export Apache Solr enabled facet settings

This code resolved my need to backport production enabled-facet settings into localhost. Features are not used. tfk_search is the name of my module, substitute this for your own.

/**
 * Implement hook_form_FORM_ID_alter().
 *
 * Alter apachesolr_enabled_facets_form(), add an additional submit handler
 * that helps us export enabled facet settings via Features.
 */
function tfk_search_form_apachesolr_enabled_facets_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'tfk_search_enabled_facets_form_submit';
}

/**
 * An additional submit handler for the active facets form.
 *
 * Save current settings into default server. Allows backporting
 * production settings into localhost. No Feature revert needed.
 *
 * @see apachesolr_enabled_facets_form
 */
function tfk_search_enabled_facets_form_submit($form, &$form_state) {
  $enabled = array();
  foreach ($form_state['values']['apachesolr_enabled_facets'] as $module => $facets) {
    $enabled[$module] = array_filter($facets);
  }

  // We hardcode 'solr' here because apachesolr_default_server() resolves to something
  // else in production.
  apachesolr_save_enabled_facets('solr', $enabled);
}

After importing the database from production into local, while your default Solr instance is still the same as the one in production, go the enabled-facet settings page, and save it (even if you make no changes on it). Then switch the default Solr instance to the local one (solr). It should automatically pick up the facet settings for production.

Note that this solution is good for backporting settings, but not for exporting them á la Features. It would not work if you wanted to automatically push these settings into various sites.


The best solution here is a "dumb" migration, one that simply retains the data model of the prior system without trying to shoe horn it into the data model of the new. The reason I changed the tax data model from Ubercart to Commerce is because taxes are actually necessarily tied to the products and services that are being taxes. When we had all taxes added up and stored in a single line item, it's then impossible to do things like refund the taxes collected for one particular product on an order if it's returned. You also cannot generate a very meaningful tax report, though nowadays I'd look to third party systems to do that anyways.

You're going to need to define your own line item type via hook_commerce_line_item_type_info() and then setup your migration to create the line item on migration. I'd call it "Ubercart tax record" or something similar. New taxes going forward should actually become part of the relevant line items when they're calculated.

When you create these tax line items, make sure that you both set the unit price amount / currency code values and update the unit price's components array to match. Look to commerce_product_line_item_populate() around line 1376 where you see the comment about adding the base price to the components array. In your case, you wouldn't use the 'base_price' price component for taxes - you'd either want to define a generic price component type via hook_commerce_price_component_type_info() or if you know the types of the taxes map to price components for tax rates you've defined on the new site, you can use those.


To resolve current issue we need to create RouteSubscriber
my_custom/src/EventSubscriber/MyCustomRouteSubscriber.php :

<?php

namespace Drupal\my_custom\EventSubscriber;

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

    /**
     * MyCustom Route subscriber.
     */
    class MyCustomRouteSubscriber extends RouteSubscriberBase {

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = parent::getSubscribedEvents();
        $events[RoutingEvents::ALTER] = ['onAlterRoutes', -300];
        return $events;
      }

      /**
       * {@inheritdoc}
       */
      protected function alterRoutes(RouteCollection $collection) {
        if ($route = $collection->get('user.logout')) {
          $route->setDefaults([
            '_controller' => '\Drupal\my_custom\Controller\MyCustomUserLogoutController::logout',
          ]);
        }
      }

    }

Then add entry into my_custom.services.yml:

  my_custom.route_subscriber:
    class: Drupal\my_custom\EventSubscriber\MyCustomRouteSubscriber
    tags:
      - { name: event_subscriber }

Then create actual controller which will replace users module logout method.
my_custom/src/Controller/MyCustomUserLogoutController.php

<?php

namespace Drupal\my_custom\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Class MyCustomUserLogoutController.
 */
class MyCustomUserLogoutController extends ControllerBase {

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    $logout_url = 'https://google.com'
    return new TrustedRedirectResponse($logout_url);
  }

}

Hope it will save your time.

Thanks


Validate username field in user registration form, drupal 7

You can do this by using hook_form_FORM_ID_alter() and adding an extra validation function to the user register form:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MYMODULE_validate_register_form';
}

function MYMODULE_validate_register_form(&$form, &$form_state) {
  if ($form_state['values']['mail'] != $form_state['values']['name']) {
    form_set_error('name', t('Name and email must be the same.'));
  }
}

I'm not 100% positive those $form_state['values'] keys are the right ones so you'll need to inspect the form to make sure; but the logic is the same either way.


Edit a form retrieved using FormBuilder::getForm()

I see two approaches here:

You will have to use "hook_form_alter", or a more strict form alter (for example: hook_form_FORM_ID_alter()). You can remove any elements there (calling from you .module file).
When you get back your form object ($node_create_form) which will be rendered later on, you could make changes on that specific object witt it's public methods! Just dpm, or kint the object (with devel module enabled), and you will able the find the right method to alter the form elements you are about to render.

Side note: I highly discourage you from using "\Drupal::..." static service calls. FormBase classes are implementing the ContainerInjectionInterface, which means, in public static create function you can pass the services you need. Read more on this here!


Error when I edit a block: Notice: Undefined index: und in eval()

You must pay attention to the node's language. 'und' is for nodes which don't have a language set. If you set one, then the values will be in 'en' or 'de' or whatever the node's language code is.


In my example I will assume that you have a color field called color (machine name: field_color) already set to user fields admin/config/people/accounts/fields

By following these steps you'll be able to achieve what are you looking for.

Create Drupal custom module. Ref Creating modules.
Implement hook_init to your custom module
In the hook_init you need to implement drupal_add_css
Set HTML elements you need to let users to change; according to current user color selection.
The final code should look like the following:

function MODULE_NAME_init() {
  global $user;
  $account = user_load($user->uid);

  if(isset($account->field_color['und'])) {
    $color = $account->field_color['und'][0]['value'];

    drupal_add_css(t('#menu { background-color: #@color; }', array('@color' => $color)), array(
      'type' => 'inline',
      'media' => 'screen',
      'weight' => '10000',
    ));
  }
}

Note: change MODULE_NAME to your desirable module name.


Create a simple module to retrieve record from database?

The Creating modules tutorial covers block creation: implementation of hook_block_info() to declare your block, implementation of hook_block_view() to generate the block content, usage of theme() to format retrieved records and usage of user_access() to check user permission before giving him/her access to the information

The only missing information is the menu_get_object() function which you can use to retrieve the currently displayed node (if any).

function myModule_block_view($delta) {
  if (($node = menu_get_object()) && ($node->type === 'product')) {
    $results = db_query("SELECT * FROM {uc_auction_bids} WHERE nid = :nid", array(':nid' => $node->nid));
    $records = $results->fetchAllAssoc('bid');

    $content = ... // Format records here...

    return array(
      'subject' => t('Bids'),
      'content' => $content
    );
  }
}

A more complex solution, but a flexier one, would be to expose the uc_auction_bids table to views using a hook_views_data() implementation. You could then create a block display using a contextual filter to retrieve the current node ID.


Allow a node to have many dates attached to it

Just answering this myself so it doesn't count towards the unanswered total.

Turns out the answer is relatively simple - as long as you don't choose a Widget for the Date field that handles repeating dates, the 'Number of Values' field appears and you can choose 'Unlimited'.

So choosing either of the following Widget types:

Select List with Repeat options; or
Text Field with Date Pop-up and Repeat options

will not allow you to have multiple values. Any other options should be OK.


Looking through the WYSIWYG modules' code when saving the form, it implements:

db_merge('wysiwyg')
  ->key(array('format' => 'full_html'))
  ->fields(array(
    'editor' => 'tinymce',
  ))
  ->execute();

So that's what I suspect you'll need to put into your install profile


How do I use an external data source in a view?

Check Views JSON Query.

  JSON Query is a Views 3 plugin that adds native JSON query generation.
  It allows you to parse JSON using Views' graphical query builder. It
  works much like Views XML Backend but with JSON.


Try below code in your template.php

<?php
  function YOURTHEME_preprocess_search_result(&$variables) {
  $variables['info'] = '';
  }
?>

Or create a template file for search results if not there  named "search-result.tpl.php" and add this

<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
 <h3 class="title"<?php print $title_attributes; ?>>
   <a href="<?php print $url; ?>"><?php print $title; ?>

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

  <?php if ($snippet): ?>
    <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

<?php endif; ?>
<?php if ($info): ?>

<?php print $info; ?>

<?php endif; ?>

and To remove the author, date and comments count remove or comment out the following lines:

<?php if ($info): ?>

<?php print $info; ?>

<?php endif; ?>

and in css

.search-info {
display: none;
}

Taken answer from this link


Yes, the update is manual. (As someone new to Drupal, you may not know about the command line tool drush, which is as close as we get to being a one-click affair. Drush is awesome, and once you get more familiar with Drupal, you should learn it. It makes your work much more efficient.)

Re the previous answer, 'Download these updates' only works for contributed modules and not for core.

The instructions on drupal.org are excellent.  But before you start, here are a couple of pieces of useful information.

Do not get confused by the instructions at the top of the page sending you to upGRADE instructions.  An upGRADE means moving from one version of Drupal to another, e.g., Drupal 6 to Drupal 7, and is a much bigger deal. An upDATE moves you up by minor versions, e.g., Drupal 7.2.1 to 7.28.
Because you are new to Drupal, it would probably be a good idea to make sure the previous developer did not make the classic error of putting contributed modules and themes in with core modules.  When you do the update you will delete all files EXCEPT [drupal root]/sites, which is where contributed modules, and site-specific files live. On your site, go to admin/reports/updates/list. Open another window in whatever file browser you use, and look at the Drupal file structure.  The list of modules in the update list should match up to folders in [drupal root]/sites/all/modules.  If instead you find those folders in [drupal root]/modules, you have bigger problems than can be answered here.  (Same goes for themes.)
If you have a development and/or staging site in addition to the live site, do the updates there first.  If you don't have non-live sites, you should create them.  You can do updates on a live site, but it's much preferable to test them first.

Sorry, long answer.  There's a lot more good stuff on drupal.org, but it can be hard to find.  I usually use Google to search drupal.org.


(How) can I implement a points system to track club member attendance/participation?

If it were me, I would first create a role for members. I would have each member register and then have an officer assign them the role member.

I would then use the views module to display a list of members by using a filter by role. That would allow a list of members to be shown.

Then, I would create an attendance table and a meeting table in the database. (You can do this through the next step if you want to learn how to create drupal db schema. I would probably have the fields:

meetingId
meetingDate
meetingDescription

The attendance table would have:

meetingId
userId

When a user attends, you create a reference to the meetingId from the meeting table and create an enter with the drupal user id. When you want to know who selected a given meeting, you select all userId's from the attendance table matching the meetingId.

I would then write a simple module that uses the forms api to create a meeting. Then, you would have another page that lists all of the users by selecting all the ones with the member role and again using the forms api you would add an entry for the attendance table for each person that was there.

So there would be one link and two coded pages now... one link to "view meetings" which would show all of the meetings. If you click on a meeting, you would be taken to the page which displays users. If the meeting was in the past (meaning some historical data exists), it should have historical attendance data. You can handle that in one of two ways... either show them the historical data and do not allow edits, or you show your original form but  populate the check boxes of people that attended. Otherwise, it is a new meeting and should just display the form. If it were me, I would allow edits and it simplifies the page because it is the same form, just populated with check-boxes if there is any data.

This is an excellent opportunity to learn how to write a module. It is very simple yet complex enough to show you the ins an outs of creating a Drupal module. Also, it has a clear and definable end result which will either work or won't.

You can check out the schema module for help creating the database tables through the module. This is a good thing to learn.

If you want to go one step further, you can expose your tables to views and use the views module to create the display portions of your data. Although you will still need to create the forms on your own.

Update: Thought, you could also add a notes column to the meetings so people could enter and save notes. Also, your imagination is the limit here. All sorts of other things could be done. However, I would keep it as simple as you can stand for your first module.


How to load the required modules only on Drupal site?

No, there's no such way. Or may be answer is: Yes, it's done automatically. Keep in mind that Drupal loads only the .module file always, and other files (includes, classes, etc) are only loaded when needed. Is true that that 'when needed' may be always for some of the files, but not all.


How to show paragraph bundles of different types in a view of content containing paragraphs?

You need to create a brand new view. Go to /admin/structure/views/add

For Show: select Paragraph Items

Once in the View, add fields, and you should be able to add Paragraphs item: [Name]

  but I want to see the content that has these paragraphs, not just the
  paragraphs

Then you will need to use Views Fields View to embed this view as a field in your other (node) view.

You will need to add a contextual filter of nid (to this paragraphs view).

Now in our other view (Node view) add views embed view as a field.

I think there is an option (checkbox) to automatically pass the contextual filter of your current node view to the embed view.

If not, simply add nid as a field in your node view, then when you add the view embed view field, use the replacement pattern of the nid as contextual filter.


Add html5 input types using drupal form api

Try Element module. it adds advance html5 elements to your form.

Similar question is asked here


Import RSS Feed to a specific taxonomy term

To use the feeds module you should have a content type set up in which you'll import these items.  I believe the tutorial is just saying that you should set up this new vocabulary and then add a term reference to it in your new content type.

In Drupal 7, to make sure you can set up your vocabulary, verify the following

When you go to /admin/modules on your site, is the Taxonomy module enabled?  If not, check it and save the page
Once that's done, you should be able to go to admin/structure/taxonomy to add your new vocabulary.

Don't forget that you should then add a term_reference field in your content type, so you can tag it with those new terms...

Hope that makes sense!  Let us know if it worked.


If oyu want to get and submit a form programatically you must use the function drupal_form_submit

  Retrieves, populates, and processes a form.

  This function allows you to supply values for form elements and submit
  a form for processing. Compare to drupal_get_form(), which also builds
  and processes a form, but does not allow you to supply values.

Check this function's documentation page and its comments for some examples.


How to change order of custom module theme output?

If you add the #weight property to the arrays in $build() then that will allow you to order them e.g.:

$build['acts_table_rows'] = array(
        '#theme' => 'table',
        '#rows' => $rows,
        '#empty' => t('Currently there are no active content'),
        '#weight' => 99,
);


Access to install.php on existing installation

The issue is caused by a module that's enabled with the installation profile using the drupal_goto function on hook_user_login.

This function ends the request, therefore the profile doesn't go to the page showing 'Visit your new site'.
It goes to the URL provided in drupal_goto instead and variables are not set because the function install_finished() was never called.


Making custom fields available to views module

If you want to add custom database tables in a view, you need to let views know about it by invoking hook_views_data() http://blog.menhir.be/2008/10/22/expose-database-fields-to-views-in-a-custom-drupal-module/

There is also documentation for this within the views module.

It looks like you are on the right track but your function name is _tables() instead of _data().


Pass Variable to Custom Block template file

Your return array doesn't contain a #theme key. So at the moment you aren't using a template file at all.

And you  probably have a mix up between the outer block and theming the content inside of the block. Your template inside has the name tcdev, because that is the name you defined at the top of the array in *_theme(), and tcdev.html.twig is where your variables will end up.

Your code would look like the following one.

function tcdev_theme($existing, $type, $theme, $path) {
  return array('tcdev' =>                  // this is the name of the template
           array(
            'variables' => array(
                'title' => 'Default title',
                'description' => null
            ),
        )
    );
}

SliderBlock.php

namespace  Drupal\tcdev\Plugin\Block;
use Drupal\Core\block\BlockBase;

/**
 * Provides a 'SliderBlock' block.
 *
 * @Block(
 * id = "slider_block",
 * admin_label = @Translation("Slider Block"),
 * )
 */

class SliderBlock extends BlockBase{
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#theme' => 'tcdev',
            '#title' => 'my title ',
            '#description' => 'my custom desc'
        );
   }
}

tcdev.html.twig

My Custom Block{{ title }}-{{ description }}

You wrote that you saw some tutorials about it. Probably this was about two different topics, and you are trying to apply them at the same time.

Create custom twig templates from custom module
Override Twig Templates

The custom template in the first link is tcdev.html.twig. What you are trying to do with the method in the second link is for block--sliderblock.html.twig.


Implementing IP recognition and price conversion (2 parts)

I don't think there is any module provides this functionality.. The best way is to use some third party services to get data and display it..

I'd do such things to acheive this:

get user ip by ip_address()`
get user info by this service: http://www.geoplugin.net.

here is an example:

$countryInfo = drupal_http_request('http://www.geoplugin.net/json.gp?ip=' . $user_ip);
$countryInfoData = json_decode($countryInfo->data);
$userCurrencyCode = $countryInfoData->geoplugin_currencyCode;

and use google converter to get result:

some sample code:

  $amount = urlencode($amount);
  $from_Currency = urlencode($from_Currency);
  $to_Currency = urlencode($userCurrencyCode);
  $get = file_get_contents('https://www.google.com/finance/converter?a=' . $amount . '&from=' . $from_Currency . '&to=' . $to_Currency);
  $get = explode("",$get);
  $get = explode("",$get[1]);
  $converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);

this piece of code's gotten from this post :)

and, so, it's up to you to display the results...

I don't think this is a real solution to your problem and also I can't guarantee this will work:) .. but you can play around it to find better solution..


Regarding the "... other forum software ..." near the end of your question: how about using the Flag module and its Rules integration?

Consider "somebody subscribing to some node" as the equivalent of "somebody flagging that node". And if your current technique to "send them notifications" is not flexible enough to do so in combination with the Rules and Flag module, then you may want to consider the Message module (which goes together with Rules and Flag very well also, and which is also used in some of the popular distributions).


Why do you need a javascript way explicitly? Drupal can do these Filters and make the glossary view, an index by letters, at top for you already in the views administration area.


To generate an internal url in Twig you can follow these steps:

Install the module Devel.
Go to Routes Info (/devel/routes) and search in the browser for the path :

Add the route name and the route parameter to url():

Edit Menu


How do I effect the page that a menu item redirects to?

hook_menu serves, among other things, to map paths onto callback functions.  Whatever function is marked as the page callback for that path will be responsible for returning a either a rendered string of HTML or a Drupal render array.  So, for your very simple use-case, you could do the following (assuming your module's name is bh_vendor):

function bh_vendor_menu() {
 $items['admin/vendor/auth-stripe'] = array(
        'title' => 'Authenticate Stripe Account',
        'description' => 'In order to receive payments, you must authenticate your Stripe Account.',
        'page callback' => '_bh_vendor_auth_stripe',
        'access arguments' => array('vendor administration'),
        'type' => MENU_NORMAL_ITEM,
 );
 return $items;
}

function _bh_vendor_auth_stripe() {
 return l('My link', 'my/path');
}

You could, in fact, define a block using hook_block_info() and hook_block_view(), then embed that block on your page by calling module_invoke('bh_vendor', 'block_view', 'yourblockdeltahere') but that really only makes sense if the stuff you're embedding is re-used elsewhere.  If it's only meant for this one page then you should stick the code to generate that markup in your page callback directly.

Another option, if this isn't for a module that's to be widely distributed and is only configuration for a specific site: use the Panels module.  You can create a panels page at a specific url (admin/vendor/auth-stripe) and embed whatever blocks/content you wish.  If you want it in code it is exportable and/or can integrate with Features.


Placeholders must have a trailing [] if they are to be expanded with an array of values

That issue got resolved. It was regarding passing array in to the db. Added serialise function resloved the issue.

$query->values([
$ob->machine_name,
$ob->name,
serialize($ob->settings),
]);
$query->execute();


As reported on drupalcommerce.org, the trick is to clear the form and form state caches in your AJAX callback.

The following is a working code example taken from that post:

function ajax_cart_form_alter(&$form, &$form_state, $form_id) {
  // Add ajax property to Add to Cart button
  if (strstr($form_id, 'commerce_cart_add_to_cart_form')) {
    $form['submit'] = array(
      '#value' => t('Add to Cart'),
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => 'ajax_cart_form',
        'wrapper' => 'block-commerce-cart-cart',
        'effect' => 'fade',
        'progress' => array('type' => 'throbber', 'message' => ''),
      ),
    );
  }
}

function ajax_cart_form($form, &$form_state){
  global $user;
  $order_id = commerce_cart_order_id($user->uid);
  $cart =  commerce_embed_view('commerce_cart_block', 'default', array($order_id));
  $commands = array();

  // The next line allows different quantities
  // to be submitted each time
  unset($form['quantity']['#value']);

  // Clear form and form state cache
  $form_state = form_state_defaults();
  $form_build_id = $_POST['form_build_id'];
  form_set_cache($form_build_id, $form, $form_state);

  $commands[] = ajax_command_replace('#block-commerce-cart-cart .view-commerce-cart-block', $cart);
  $commands[] = ajax_command_replace('#block-commerce-cart-cart .cart-empty-block', $cart);
  return array('#type' => 'ajax', '#commands' => $commands);
}


Ternary operator not evaluating checkbox values

Solved it!

I redefined the keys for my checkboxes as values rather than strings. Like so:

$hometypes = array(
        1 => t('Elderly'),
        2 => t('Disabled'),
        3 => t('Council tenant'),
        4 => t('Home owner')
        );

remembering to change this:

$elderly = $form_state['values']['survey'][1];

which means that this:

($elderly == 1 ? 'Elderly

 	 ' : '')

works perfectly.


What's wrong with the way I use variables in my function?

For a variable to be available in the scope of a function, it needs to have been initialised (or it needs to have been initialised in the global scope and imported into the local function using global).

At the moment there's nothing declaring or passing the $vars variable in...it hasn't been initialised, thus you get the warning.

You're passing a variable to the function called $message, which suggests your code should be:

$uid = $message->author->uid;

The confusion with $vars/$variables might be caused by the fact that it's sort of the standard name for the only argument passed to theme functions, e.g.

function MYTHEME_preprocess_node(&$vars) {
  // Use $vars


Multilingual multisite problem after changing standard language

Here is a hint (as in your question), that might help: make sure the URL of the homepage is defined as a "multilingual" variable. The relative URL to display as the front page is specified within admin/config/system/site-information.

If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable." in the description of that variable on that page).

For more details about how to get this done, refer to my answer to "How to make content translation available for front page?".


How to display content type name on related image?

1) In FIELDS add Content Type as a field and check mark exclude from display.

2) Make sure Content Type is ABOVE Body field, other wise you will not get Content Type token as a replacement pattern.

3) Click on your Body field and in REWRITE RESULTS, checkmark override output of this field.

Then use the replacement patterns.

The above is for Drupal 8, in Drupal 7 it would be [type_1] [body__summary]

You can add html if you need ex:
[type_1]
 [body__summary]

  Bonus: You could remove the image from Summary Part and instead add an image field to your content type. Then add your image as a
  field to your view. Then when you REWRITE RESULTS you can add the image there
  [type_1][field_image][body__summary]

PS: Next time tell us which Drupal version you are using!


New custom content type not showing up in 'Create content' menu

I think you are facing the same problem I've experienced. Probably you disabled the navigation menu link "Add Content" and its respective sub-menu items. Then, they won't show up at the path node/add.

See this Q/A: No content type problem


Views event listing by date with up/down infinite scroll

You can achieve your requirement by following below steps.

Install Views Field View module.
Create first view of Event content type with 2 events which are previous to the current date
Create second view of Event content type with 2 events which are greater than current date.
Now create on third view with current date and into its header part add first view and into footer part add second view using Views Field View. Follow screenshot attached below

Regarding scroll down functionality install Views Load More module.

I don't know how to achieve scroll up functionality. It something like you have to write custom thing.


APC is PHP's op code cache. If you enable it then it works for any PHP code. All of your Joomla/Wordpress or Drupal sites will execute faster provided you have high value of Hit/Miss ratio( or increase APC RAM if it's less).

If you want further optimization then Drupal can use APC for caching( instead of storing in mysql tables) using Drupal's APC module. I'm not sure about this sentence though.

I too was confused in the same way :)


First verify that the $taxonomy variable is available and populated in your node.tpl.php file. ...

EDIT:

Your accessing the values in your $item variable like it is an object but your casting to an array. Try accessing as an array:

 <a href="<?php print base_path() . "taxonomy/term/" . $item['tid']; ?> "class='tags'><?php print $item['name'] ?>,


How to redirect anonymous user to 404 instead of 403?

I have had some odd experiences with user_is_anonymous(). Try using negation with user_is_logged_in(). For example:

if (!user_is_logged_in()) {
    // Do stuff
}


Can no longer access administration pages - Warning/Error

go to your settings.php and add this code below

error_reporting(-1);  // Have PHP complain about absolutely everything
$conf['error_level'] = 2;  // Show all messages on your screen, 2 = ERROR_REPORTING_DISPLAY_ALL.
ini_set('display_errors', TRUE);  // These lines just give you content on WSOD pages.
ini_set('display_startup_errors', TRUE);

follow these steps Blank pages or "white screen of death" (WSOD)


Google will only index one version of the same page. It sounds like you have multiple URL's showing the same page. This is called dublicated content. Google will just choose one of the URL's, in your case, the wrong one.

When you enter mysite.com/node/6574 are you redirected to the friendly url? If not, then the GlobalRedirect module is not active or there is no aliases for the URL.

So make sure it's active and in admin/config/system/globalredirect check Deslash and Non-clean to Clean to further minimize dublicated content.

Also make sure that all internal and external links are pointing to your clean url's.

If the above is done, you just need to wait. Be patience - it can take weeks/months.

And forget about the sitemap. The important part is your internal links.


can't find how to use Backup and Migrate module

In Drupal 7 it is mysite.com/admin/config/system/backup_migrate


How does entity_metadata_wrapper work with array?

The function theme_image will output the value as an img-tag. Is that what you are looking for?

$photo_field = $wrapper->field_library_photo->value();
$image = theme('image_style',
  array(
    'style_name' => 'large',
    'path' => $photo_field['uri'],
  )
);


Made a Product Type: Donation
After that I created Products of: 2 USD, 10 USD etc.
Created a donation page of form: /donation/*
When I reference the donation page from the node page the links look like this: /donation/%nid
On the donation page I create a custom form and there I modify the submit function.


Search & replace serialized data after moving the files directory

The scanner module scans all CCK fields - Since this is a CCK field, it should correct this kind of problem, if this is a small database. But for large database it may suffer from performance issues.

You can also do it with PHP or SQL.


Dependent multiple selection drop down in drupal form - illegal choice error

To try take your second $form['field_policy_categories']['und']['#options'] to individual function instead of inside hook_form_alter().

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

  if ($form_id == 'policy_node_form') {
    $form['field_department']['und']['#ajax'] = array(
      'wrapper' => 'policy_category_list',
      'callback' => 'ajax_policy_category_callback',
      'method' => 'replace',
  );

  $form['field_policy_categories']['#validated'] = TRUE;
  $form['field_file_upload']['#validated'] = TRUE;

  $form['field_policy_categories']['und']['#options'] = categories_options($form_state);

  $form['field_policy_categories']['#prefix'] = '
';
  $form['field_policy_categories']['#suffix'] = '
';

  $form['#validate'][] = 'form_validate_policy_add';
}

function categories_options($form_state) {
  // option go to here
}

.


How fix an inverted execution order problem?

Posted this answer in the issue @attiks mentioned as well:

The easiest thing to do is to add the states in hook_form_alter() or in hook_form_FORM_ID_alter().

I got Clientside Validation to work on fields within a group, within a field collection.

Here's my code:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function fgtest_form_article_node_form_alter(&$form, $form_state) {
  $group = 'group_customgroup';
  $collection_bundle = 'field_my_collection';
  $fields = array_keys($form[$collection_bundle]['und'][0]['#group_children'], $group);
  foreach (element_children($form[$collection_bundle]['und']) as $delta) {
    $collection = &$form[$collection_bundle]['und'][$delta];
    foreach ($fields as $field) {
      $collection[$field]['und'][0]['value']['#states'] = array(
        'required' => array(
          "#edit-field-my-collection-und-{$delta}-field-make-required-und" => array('checked' => TRUE),
        ),
      );
    }
  }
}

And here's my setup:

Node Article:

Field Collection field_my_collection:


How to display contact form module in a block using drupal 7

Check this answer which recommends to use Form Block module.
This could also be useful.


Interesting question. The way I see it there are actually two parts to this. This first is, of course, your actual question and that can be easily solved:

// Your code in ajax_select_callback().
unset($form['answer']['answer1']['#attributes']['disabled']);
$form['answer']['answer1']['#disabled'] = 0;
// More of your code in ajax_select_callback().

When you set the #disabled property of a form element to TRUE, what Drupal does is simply add the disabled attribute to the element and allows the renderer (i.e. drupal_render()) to do its job. In your AJAX callback, the $form array passed is that of the rendered form. This means that the your dropdown element already has the disabled attribute on it. Therefore, when it is rendered again, it still shows up disabled. So, to prevent this, we simply remove the attribute.

However, you'd notice that when you submit your form after this, the value of the disabled dropdown (in $form_state['values']) may not be the value you chose after "enabling" it. This is because your form is not being re-built on the server which means that Drupal still thinks your dropdown is disabled and will refuse to process your input, simply ignoring it and using the default. If you are able to reproduce this, comment on this answer and I'll update this post with a solution for that problem.


How to get a text field with each radio input in cck

It seems you are looking for the Double field module

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

  For the moment it includes the following sub-widget types:

  Textfield
  Select list
  Single checkbox
  Textarea

  Consequently, in all there are 4 x 4 = 16 widget types.

You can also achieve that using Field collection module.

  This module Provides a field-collection field, to which any number of fields can be attached.

But this module requires the Entity API module. Also note that this field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


put the contents of one field into another field upon form submit

I think it'll work if you implement hook_form_submit() hook for this form, and in that function set the value of one field to another.

E.g.,

FORM_ID_form_submit($form, &$form_state) {
  $form_state['values']['email'] = $form_state['values']['mail'];
}

If your fields are fields of a content then replace the above line with this:

$form_state['values']['email']['und'][0]['value'] = $form_state['values']['mail']['und'][0]['value'];


Not getting along with the form API tutorial

Use hook_menu().

function YourModuleName_menu() {

 $items['testform'] = array(
   'title' => 'Test form',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('your_form_function'),
   'access arguments' => array('access content'),
   'type' => MENU_CALLBACK
 );

 return $items;
}

Access the page from example.com/testform, where example.com is your site address.

You can also create a block from your form to access it.


Content Access exclusive permissions per node

you can use Content Access Module.

A quick view :

  "This module allows you to manage permissions for content types by
  role and author. It allows you to specifiy custom view, edit and
  delete permissions for each content type. Optionally you can enable
  per content access settings, so you can customize the access for each
  content node."

I hope it works for you


How remove DIV elements in rendered search form in theme designing

There are two theme functions you need to override:

theme_form(), in which the wrapping
 is hard-coded with this line:

return '<form' . drupal_attributes($element['#attributes']) . '>
' . $element['#children'] . '
</form>';

theme_form_element() which contains all of the extra
s you're trying to get rid of.

The latter is quite a long function so there may well be some duplication, but I don't know how else you would do this.


Show latest changes in node "View" tab while using Content Moderation

Finally after spending huge amount of time on this, I am able to figure it out. Thanks to shawn-conn's answer here - Take over display of a content type node route
I have created a custom module and have added below files and code to achieve this,
First created mymodule.services.yml and added below code,
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Then created Routing folder under src.
Added file named RouteSubscriber.php with below code,
<?php

namespace Drupal\mymodule\Routing;

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

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Alter the canonical node route to our custom route
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\NodeRedirectController::view');
    }
  }
}

Then added NodeRedirectController.php under src/Controller directory with below code,
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * Custom node redirect controller
 */
class NodeRedirectController extends NodeViewController {

  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    // Display latest revision content in view mode
    if ($node->bundle() === 'my_content_type' && $view_mode == 'full') {
      $vid = \Drupal::entityTypeManager()->getStorage('node')->getLatestRevisionId($node->id());
      $node_new = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
      return parent::view($node_new, $view_mode, $langcode);
    }
    // Otherwise, display as per Drupal's default behaviour
    else {
      return parent::view($node, $view_mode, $langcode);
    }
  }
}

This might help someone.


Use Checkboxes with Drupal Better Exposed filter

This also tripped me up. The settings weren't where I expected them to be and there were a couple of prerequisites. Maybe this is your issue too?

Create a View and expose a filter
Under Advanced > Exposed form > Exposed form style select Better Exposed Filters
Under BEF Settings roll down to the bottom where there are the Exposed Filter settings and select Checkboxes/Radio Buttons from the drop down menu.

Note: You can't select these settings for filters that don't have a limited number of options. (A title won't work, but a term will.) The documentation says:

  BEF only operates on fields that have a limited number of options such as Node:Type or Taxonomy:TermID. Open-ended fields, such as Node:Title, do not work with BEF. Entity References do work, however, if you Enable Render Views filters as select list (a checkbox) in the Entity's entityreference field.

I had utilized the entity reference field pattern. You need to edit the field you are referencing in the Content types > [content type] > manage fields > [field name] > edit. field settings. There, at the bottom of the page under Additional Behaviours you will find a checkbox for Render Views filters. That will allow the aforementioned select box (in BEF settings) to properly display the Checkbox/Radio option.


How do I shorten the length of all form input text fields?

There are a couple of things you can do depending on whether you want to do this on a theme level or site-wide level (i.e. independent of theme).

On the theme level you can override theme_textfield() and set the size there:

function MYTHEME_textfield($variables) {
  $new_size = 40;
  $variables['element']['#attributes']['size'] = $new_size;

  // EDITED per kiamlaluno's comment regarding infinite loops
  return theme_textfield(array('element' => $variables['element']));
}

On a site-wide level you can write a small module and implement hook_element_info_alter() to change the default that's provided by system_element_info():

function MYMODULE_element_info_alter(&$type) {
  $new_size = 40;
  $type['textfield']['#size'] = $new_size;
}

You'll want to clear Drupal's cache once you've implemented either of these methods to clear the relevant registry.

It's worth noting that if you use the first method any specific sizes for textfields set by other modules (e.g. size 10 for numeric fields) will be overwritten with your new size. If you use the second method that will become the default but other modules will still be able to provide a specific size for specific textfields.

EDIT

I've just had another thought on this, probably the best way is to do it is in your theme function and check the existing length. That would match your statement "I want all the forms on my site to be no wider than 40" a bit better:

function MYTHEME_textfield($variables) {
  $new_size = 40;
  if (isset($variables['element']['#attributes']['size']) && $variables['element']['#attributes']['size'] > $new_size) {
    $variables['element']['#attributes']['size'] = $new_size;
  }

  // EDITED per kiamlaluno's comment regarding infinite loops
  return theme_textfield(array('element' => $variables['element']));
}


Which Rules Event should I use to change the value of a Select List field?

Add event entity has a value or data comparison
Add condition according to your select list
Add action set data value against changed value


I think the simpliest way is to use Panels, and override the Node page. Add a variant and put your view in it, and send the node's nid argument to it, using node:nid contextual argument.

(install page manager)
Enable node view page (node/%node)
Add a variant, set a validation criteria selecting your concerned node type
Use simple one-column display
Add your view in your column
It asks for an argument, send the node:nid, (or entity_id, or whatever)
In your view, use node:nid contextual filter

All is done.


Logo doesn't appear on the Seven theme on a fresh installation

The logo for the theme selected is added to a php serialized array in the system table under the info column. It is advisable to not use FTP to upload the image but instead of the Admin UI under the themes section to do so.

Click Appearence > Seven 7.8 > Settings

Then scroll to "Logo image settings" and uncheck "Use the default logo".

Click "Choose File" and pick the logo image file.

Click "Save configuration" and your logo should show up in the site. If caching is enabled, the caches might have to be cleared.

Edit: The page.tpl.php file for the seven theme does not have a section to display the logo. Not sure if this is a bug or just a design decision. Either way, there is no way to show a logo in the seven theme at this time.


I have figured this out.

The solution is to use approach 2 (in my opening post). However, in the template.php file, you have to remove all the dashes from the form ID (edit-profile-user-profile-form) and replace them with underscores.

So the code in template.php would be as follows:

function THENAME_theme(&$existing, $type, $theme, $path) {

    return array(
        'edit_profile_user_profile_form' => array(
            'arguments' => array('form' => NULL),
            'template' => 'templates/edit/user-profile',
            'render element' => 'form',
            ),
    );

}

Next create a file called user-profile.tpl.php and save it in templates/edit.

In the user-profile.tpl.php file, use the following code to print out the fields:

<?php print drupal_render($form['field_NAME_OF_FIELD']); ?>


The last item in comments is the pager, which you have to remove first to get to the last comment. Then you can build a new render array with the single comment and the pre-render callback:

{% set last_comment = comments|without('pager')|last %}
{% set pre_render = comments['#pre_render'] %}
{% set last_comment_build = { '#pre_render': pre_render, '0': last_comment } %}
{{ last_comment_build }}


I don't know about 'best' (although @Berdir might have something to say on the matter ;) ), but Privatemsg would probably be perfect for this:

  Privatemsg allows your site's visitors to send private messages to each other.

It also provides e-mail notifications of new messages.


Single sign on between different Drupal versions

With the drupal-6 site override hook_login_validate() and write your own authentication mechanism. Simpler than it sounds, as any function that returns TRUE or FALSE based on success will work. It could directly access the database or connect via a JSON web service to the drupal-7 server. I described how to implement authentication via JSON on stackoverflow.

function mymodule_login_validate($form, &$form_state) {
   $username = $form_state['values']['name'];

   // do if condition to see if your authentication is required.
   // e.g. you might want to keep the drupal administration users.
   if (_mymodule_use_webservice_login($username)) {
     // We are logging in using service.
     if (_mymodule_validate_password($username, $form_state['values']['pass']) {
       user_external_login_register($username, 'mymodule');
       user_authenticate_finalize($form_state['values'];
    } // else drop through to the end and return nothing - Drupal will handle the rejection for us
   }
} else {
    // Username is not an member number, so use standard Drupal authentication function
    user_login_authenticate_validate($form, &$form_state);
}

_mymodule_validate_password() is where the authentication occurs and the only other function you need to implement. See the stackoverflow site for calling a JSON web service. Try to use SSL as passing passwords over SSL is not great, although your main site may not be SSL anyway.

Implementing the web service is a function return TRUE or FALSE - drupal_json_output. You need to set up a menu, with a function callback. The function callback would call user_authenticate().

You could also try one of the SSO modules. http://groups.drupal.org/node/182004. It is usually good policy to not implement your own security code so that the code gets tried as much as possible.


URL to catch post data from off-site payment gateway in Drupal commerce

You can catch it wherever you want. It's up to you to define the menu item and ensure it gets communicated properly to the gateway. See Commerce PayPal for examples - it uses an IPN listener that is always accessible (even in maintenance mode) and dispatches it to the appropriate payment method for processing.


Setting up a staging server workflow (for a relative beginner)

If I understand what you are asking for, that being your production server being remote, you might want to consider installing a devdesktop from acquia.com if you're using a Windoze or mac development system.  Then you can use features and/or deploy to move you changes to the production system via ftp.

If you're using a *nix development box I'd install Drupal directly and still use features and/or deploy to move things.

Worth a try -


@MPD was correct. I had neglected to use the node override panel page correctly. Thank you!


How to print fields value in views-view.html.twig in drupal 8

To get a field value of the first result row view.result[0] use the method EntityField::getValue of the view field:

{{ view.field.field_example.getvalue(view.result[0]) }}


How to filter for a Field Collection in a View

I answered over in How to filter groups of paired values in Views which appears to be essentially the same question.


How can I display an entire page at a specific path/url in a block?

If you do something like this...

D6:

$foo=menu_execute_active_handler('path/to/the/homebox/page');

D7:

$foo=menu_execute_active_handler('path/to/the/homebox/page', FALSE);

...$foo should include either all of the html or a renderable array of the path/page content in question so in theory you could then stuff that in a block, either via a custom module or (ick) using the standard block interface and the (double ick) php input filter.

MORE THOUGHTS:

My basic thought above was to try to get to the menu handler for the page/path in question with as little custom code as possible.  But, if you look in the HomeBox module, all it is doing for each page/path is calling homebox_build() along with a page argument that is easily crafted up.  So, if you are comfortable with coding, you could write a custom module that uses that function within its block hooks to create the content.

Also, not sure about any css/js that would be needed but that could be hand crafted I suppose if necessary.


What is the relationship between the node and the node revision table in Drupal 7?

I believe this is what you're looking for:

function MYMODULE_get_node_title($nid) {
  // Using Drupal's DB API.
  $query = db_select('node_revision', 'r')
    ->fields('r', array('title'))
    ->addTag('node_access');
  $query->leftJoin('node', 'n', 'n.vid = r.vid');
  $query->condition('n.nid', $nid);
  $title = $query
    ->execute()
    ->fetchField();

  // Using a custom query. This might help you understand better what's the
  // exact relationship. This approach is a bit faster as well.
  $title = db_query("SELECT r.title
                     FROM
                      {node} n,
                      {node_revision} r
                     WHERE
                      n.nid = :nid AND
                      n.vid = r.vid", array(':nid' => $nid))->fetchField();

  return $title;
}

To understand the relationship look at the second approach, using a custom raw query.
vid stands for version ID and if you look at the node table you will see that there is a column named vid.
This is the active version of that node and is the ID you should use to get all field values and other attributes of that piece of content.

Hope this helps.


Something like this should help.

(function($) {
  $('.form-radio[value=_none]').parent().hide();
})(jQuery);

http://drupal.org/node/1623360


How to add a menu tab programmatically to a views page?

Path hierarchy is based on string matching; so entity/%eid/edit doesn't come under entity/% (because '%' != '%eid')

There are a couple of other issues, reading between the lines I reckon this is what you're going for:

function MY_MOODULE_menu() {
  $items['entity/%/edit'] = array(
    'title' => 'Edit',
    'page callback'   => 'MY_MODULE_entity_edit_callback',
    'access callback' => true,
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );
  return $items;
}

function MY_MODULE_entity_edit_callback($eid) {
  // ...
}


Sending HTML email replies using Webform in Drupal 7

You should download Mimemail to do this.

Then, in the webform options, you can create your template with the field you want using %value[machine_field_name] to get just the value or %email[machine_field_name] to get the label and value.