Performance (or other) benefit to adding CSS and JS files in a .info file rather than tpl?

Yes, the JavaScript cannot be aggregated meaning that instead of asking for a single (few) css/js files, the browser will have to ask for more files which is slower and required more work of your web server.

Depeding on how many JS and CSS files you add in your page.tpl.php you can get a noticeable performance improvement using the .info file method. It's also a lot better should you need to use your theme as a base theme, since it allows for better alters of the JS/CSS files.


Custom login form with signin button -- POSTing registration

It's not working because the login form validate handler is executed, and fails, before the function you call with the #submit attribute.

You can use #validate like a workaround probably, but there's a cleaner way to achieve what you are after.

I wouldn't create a button element at all. Make it a link to user/register instead and style it to look like a button if needed.


This will be a lot easier for you, if you use the taxonomy system.

Create a vocabulary for your keywords, then add the different keywords as terms.

The select2 module has a field widget for entity reference fields which allows you to get the autocomplete widget where you can remove the selected terms with an X.

Then you only need to add a little bit of styling, to get it to look like your design.

Hope it makes sense.


Not the admin role, no. But user 1 does have access to everything, yes.

This is the function responsible, User::hasPermission, you can see the unconditional access check at the top:

public function hasPermission($permission) {
    // User #1 has all privileges.
    if ((int) $this->id() === 1) {
      return TRUE;
    }

    return $this->getRoleStorage()->isPermissionInRoles($permission, $this->getRoles());
  }


Adding two contextual filters (Content : nid)

When you add two contextual filters, views expects to receive two contextual filters. Currently in your preview area you are only supplying one (you need to add the second contextual filter (article filter: content nid) as well and separate them with a /). If you use the Provide nid from url filters it might work on the page, but in the preview you still need to provide both values.

However this is not the correct way to proceed, you should be doing something like this:

Since your block should only show on the industry page, you need to obtain the nid of the industry you are looking at. Use one contextual filter, and fill if with the default value: content id from url. This will load the industry nid you are looking at.

Then, since this industry has two different content types attached, you need to add relations to both of them. If the content relates to the industry (likely scenario) you should be using the reversed relationship as you currently do. If the industry links to the content, you should use the non-reversed relationship. I guess you did this step right.

The biggest problem here is that you do not use your relationships for the filters. So Your content > -365 days is not filtering the articles or news, but applies to the industry. The same happens with your content type. You want to display nodes of articles or news, but instead you filter the node you are looking at to be of those types (which fails as it an industry).

So edit your filters and set them to use the related content's fields.
You can only set one relation for each filter, so you'd have to create each filter twice (once for articles and once for news). Then use the drop down button above the Filters section to create an And / or group and drag the items in a way so the type is of article or news.


Presenting a menu within page content with associated descriptions and images

I'm not positive I entirely understand what you envision, but one possibility might be to use the Menu Trails Module to handle the submenu.

For the section of blocks you are currently toggling on and off contextually, I might consider instead authoring a block in Views that is queried off a default argument passed through the url.  This argument would be the same value from the Main Menu which is configuring the Menu Trails and could be configured to display the node teaser (or a cck/field value called Overview) for the active Main Menu Item.

Or what you may be describing is something more like a list of submenu items as teasers,:

[Some Photo] | [Some Photo] | [Some Photo]
[Menu Title] | [Menu Title] | [Menu Title]
 [Overview]  |  [Overview]  |  [Overview]

In that case, I'd still use Menus to organize the content hierarchy, but don't check expand in the menu options.  Instead, use the method described above to construct a block in Views that displays all the submenu items. You won't need Menu Trails for this type of display.


The /node/{node}/edit path is defined by the entity.node.edit_form route. This route uses the _entity_access requirement to lookup access. When that route's requested the entity API will execute EntityAccessCheck::access() and NodeAccessControlHandler::access() to lookup the account permssions for the relevant node.


Form redirects haven't changed between Drupal 7 and 8; you still need to use $form_state['redirect'] (incidentally drupal_goto() shouldn't be used within form submissions in Drupal 7, it can mess things up).

Within your form class's submitForm() method, you can use

$form_state['redirect'] = 'node';

Or

$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

Full info can be found in the FormBuilder::redirectForm() docs


You've tagged the question with Views. Are you asking whether it's possible to build a View to do that? If so, then the answer is no (unless there's some module or plug-in out there which would add that capability).

Views queries the database, but node access permissions can be set in code via hook_node_access(). It's totally possible, for example to write some code that grants a user access to a specific node only if they have the letter 'x' in their name and today is Monday.

You can of course do it with some PHP code, and you could hook that into a View using Views hooks. I'm not sure what the most efficient approach would be, but basically:

Use hook_views_post_execute to process the list of nodes returned by your View.
For each node in your View result, you would need to loop through all users, calling node_access() to test if that user (uid) had access to the node or not.
From the results, build a list of users who had access, and have Views display that list by modifying  the $view object that was passed to your hook function.


How to create an Entity reference with taxonomy term selection?

Here, start with creating a new view and be sure to select taxonomy terms.

In short:
- Add new view
- Select: Show Taxonomy Terms
-> Save & Continue
- Fields: Entity Reference View Widget Checkbox: Taxonomy term
- And ofcourse Taxonomy Term

Go back to your contenttype page and be sure to select the right view with your entity referece field.

Cheers,


How Can i control the way the tabels in the admin panel build?

If you just want to style the D7 administrative theme (called "seven") differently, you can create a sub-theme of that theme and then customize. Docs are here: https://drupal.org/node/225125

Once you have a sub-theme, you can add you own css, templates, etc to change the way things look.

Because of the inheritance you get when sub-theming, you only have to add what you need to the new theme. For example, you could just have an .info file and custom css file.


drupal image field the image doesn't show?

Download raw drupal form drupal.org  website, then copy .htaccess file from it to your root directory.


Converting a page created with panel into PDF

Yes, you can, dowload Printer, email and PDF versions, patch module with Can Panel pages be sent to PDF for rendering?, download wkhtmltopdf libary, place it under /sites/all/libraries, and configure your module like: , and inside panels add print PDF widget like:, done!.
EDIT: today 7/7/2020 panles 7 had an upgrade, be carefull, i think patch apply to an older version in panels.


Teasers/summaries don't show when body begins with picture

Try this How to Add a WYSIWYG Editor to a "Text with Summary" Field if it works for you.


Add a single image field to a view (not its nodes, the view itself)

Views are all about rows of data. To achieve what you want, you have two options:

Create .tpl file for your view, put <img> tag in it
Attach view to a node using, for example, Viewfield module. In that node create image field you want.

First option is faster, second one allows easier image changes.


Disable email updates alert on expired domain

If you still have access to the FTP folders where you uploaded Drupal just remove the folder where you previously installed Drupal. If you can't access it anymore, there's not much you can do. You can setup a filter in your mailbox though.


RESTful Web Services : How to simply post a paragraph entity

Finally, seems it comes from Paragraph module, file ParagraphAccessControlHandler.php function checkCreateAccess :

  protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// Allow paragraph entities to be created in the context of entity forms.
if (\Drupal::requestStack()->getCurrentRequest()->getRequestFormat() === 'html') {
  return AccessResult::allowed()->addCacheContexts(['request_format']);
}
return AccessResult::neutral()->addCacheContexts(['request_format']);

}

Code goes in the second return as request format is not html but json. If I force the return to be AccessResult::allowed(), the paragraph is created. Why this restriction to forms ? How to overwrite this without patching ?


This is actually pretty easy.

Edit your content type (or clone to a new type).  Add in a noderefernce CCK field as needed.  Configure it for not mandatory, but limited to one value.
Edit the fields for the type so that they are all hidden.
Add a preprocess_node for your content type in template.php to read in the node relationship, theme the node, and then add it as a theme variable.
Create a node template for your type.
Edit the node template, to add in your div in the markup.
Print out this theme variable in the node template.

This should get you down the right path.


How to alter a form depending how it was accessed

Inside your form_alter() hook, you can always check what page a form is on by looking at $_GET['q'], eg:

if ($form_id=='user_login' && $_GET['q']=='different/link') {
  // do form alters here
}

so if you are at www.yourhost.com/different/link, it will do whatever you tell it to do.


Programatically change user field (entity reference) in drupalgap with user_save()?

It depends largely on what Widget you have selected for your entity reference field on your Manage Display page. The easiest widget to work with is the Autocomplete widget, at which point you'd send up this JSON:

"field_checked_in_chargingstation": {
 "und": [
  {
   "target_id": "... (29088)"
  }
 ]
},

The Services module is coupled with the forms system in Drupal, so as you change the widget on a field, the JSON data you need to send to Drupal may change.


Understanding theme hooks and template preprocessors

I'd suggest you read everything you can in the Theming guide.  It looks like you're specifically looking for this part of it though.


How to do dependency injection on complex classes like when extending WidgetBase

You will need to implement ContainerFactoryPluginInterface in order to use dependency injection in your class.

Include use Drupal\Core\Plugin\ContainerFactoryPluginInterface; and implement the interface so it looks like:

class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {

    ....

}

You will also need to make sure your __construct() and create() methods contain the correct parameters.

If you look at ContainerFactoryPluginInterface.php, you will see the parameters the create() method takes in:

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition);

Thus, your final code should look like:

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;

class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {
  /**
   * SICs service.
   *
   * @var \Drupal\xois\SicsService
   */
  protected $sicsService;

  /**
   * {@inheritdoc}
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->sicsService = $sicsService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('xois.sics')
    );
  }
}


== Updated. Rewrite the answer, provide step by step screenshot ==

P.S. you also need References, I apologize that didn't mention it.

Create a Content Type called Restaurant, everything by default, save.

Create a Content Type called Product

Add Node Reference field for Product Content Type.

Create an instance of Restaurant content.

Create an instance of Product content, set the node reference field to the resturant just created.

Next, create a new EVA view.

Add filter => Content type => Product

Set Entity to node, Bundle to Restaurant

Add Contextual filter, select the node reference field created.

Provide default value => Content ID from URL

So you overall EVA view set up should be something like this:

Next, an important step: clear the cache, then refresh the restaurant node page to see the change:

You can see the Product One has been attached to the Restaurant.

You will get it. :)


I think you are searching for URL alias for different language.

Go to /admin/config/search/path/add where you can add alias for different language.


Why my site is blocked by too many connection errors?

MySQL blocks clients which error made while connecting to protect MySQL from malformed client.

So first, you need to find what sort of error it is.

In example by checking MySQL error log in data directory (typically hostname.err) or if you've drush installed, by drush watchdog-show.

You may also increase max_connect_errors (what is current value?) maximum value depends on architecture (check Manual).

But this is not real solution if error is frequently occurred.

FLUSH HOSTS can help you to eliminate blocked host. E.g.

mysql> FLUSH HOSTS;

Source: Why MySQL connection is blocked of many connection errors?

Please note that to use mysqladmin properly, you need to have access to root account. If you don't have it, use FLUSH HOSTS command as above.


Just edit the page.tpl.php file and wrap all text in t() function.

For example:

This is a sample string.

Turns into:

<?php print t('This is a sample string.'); ?>

EDIT: this will make those strings translatable. After that, use the translation interface to find those strings and translate them in other languages.
If your original question was about where you can translate those strings in the admin, let me know and I'll update the answer.


that's not much to go on, so I'll assume that the module generates one button per slide in the slideshow, and you want them centered underneath the image area ?

It's hard to know without the markup, but a couple of css selectors should do the trick.

for the containing div, if it has an id, or a uniquely addressable class, try something like this:

#container {
    width: 100%;
    text-align: center;
}

and if the button divs or whatever have no convenient id or class, address them something like this:

#container > div {
    display: inline-block;
}

I think you may be better off sticking to css. Post the relevant rendered html, and perhaps we can help.


Custom user registration email - Drupal 6

you can create and send system html emails using mimemail module and a wysiwyg editor http://drupal.org/project/mimemail (or even http://drupal.org/project/htmlmail )


How to solve the strange behavior of content node in view

Saving is perceived slower because after saving (with or without overlay) it automatically redirects you to the last page you were at. Since your view takes longer to load than a single node page, saving is perceived slower.

In conclusion, the actual saving takes the same amount of time, the difference is the view page load versus the node page load.


ok, I got it to work, I think .

Accomplishing the goal requires two steps. First, find the "taxonomy vocabulary" for forums.  Then query the tree for that "taxonomy vocabulary".

Step 1:

curl -i -X GET \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 'http://myserver/rest/taxonomy_vocabulary?parameters\[machine_name\]=forums'

Result:

[{
  "vid": "1",
  "name": "Forums",
  "machine_name": "forums",
  "description": "Forum navigation vocabulary",
  "hierarchy": "0",
  "module": "forum",
  "weight": "-10",
  "uri": "http://myserver/rest/taxonomy_vocabulary/1"
}]

Step 2: Using that vid, Query the tree (via POST!!)

curl -i -X POST \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 -H Accept:application/json \
 -H content-type:application/json \
 'http://myserver/rest/taxonomy_vocabulary/getTree' \
 -d '{ "vid" :"1" }'

Result:

[{
  "tid": "1",
  "vid": "1",
  "name": "General discussion",
  "description": "",
  "format": null,
  "weight": "0",
  "uuid": "dbf914e7-42c2-45f6-b77a-e66a0da72310",
  "depth": 0,
  "parents": ["0"]
}, {
  "tid": "4",
  "vid": "1",
  "name": "Security and Privacy Issues",
  "description": "",
  "format": null,
  "weight": "1",
  "uuid": "7496bfd7-2cb8-4f87-a1e4-f45b1956a01e",
  "depth": 0,
  "parents": ["0"]
}, {
  "tid": "5",
  "vid": "1",
  "name": "etc....",
  "description": null,
  "format": null,
  "weight": "2",
  "uuid": "9fde5519-16b2-453d-852b-a8c416189e30",
  "depth": 0,
  "parents": ["0"]
}, ...]

Or, you can do a parameterized GET:

curl -i -X GET \
 -H Cookie:SESSe6a353351dfbaaadbeef=B0ZkiW3-TNZ34dfe-uywhw3-UIWJJww \
 -H Accept:application/json \
 'http://myserver/rest/taxonomy_term?parameters\[vid\]=1'

The same data is returned.

My next challenge will be to retrieve the list of posts for each particular forum.

Editorial comment: I saw this documented NO WHERE. I really don't understand how developers who use Drupal manage to use the Services module.


How to use profile2 profile type in custom form?

i Suggest to use hook_form_alter or hook_FORM_ID_form_alter to perform specific task of existing form of profile2.

function mymodule_form_alter(&$form, $form_state, $form_id)  {
    switch ($form_id)  {
        case 'comment_form_id':
            $form['your_comment_form_name'] = array (
              '#type' => 'checkbox',
              '#title' => t ('Subscribe to replies to this comment'),
            );
            break;
        case 'user_register_form' :
           $form['actions']['submit']['#value'] = t('Submit');
           break;
     }
  }


Which are the steps to make Locale language switcher block appear at selected area?

You need to set the language negotiation.


Examining the default Node bundles

The Node module does not create the "Article" and "Basic page" Bundles itself.  After some digging I found the definitions for these bundles in the standard install profile's install file.

/profiles/standard/standard.install

  // Insert default pre-defined node types into the database. For a complete
  // list of available node type attributes, refer to the node type API
  // documentation at: http://api.drupal.org/api/HEAD/function/hook_node_info.
  $types = array(
    array(
      'type' => 'page',
      'name' => st('Basic page'),
      'base' => 'node_content',
      'description' => st("Use basic pages for your static content, such as an 'About us' page."),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
    array(
      'type' => 'article',
      'name' => st('Article'),
      'base' => 'node_content',
      'description' => st('Use articles for time-sensitive content like news, press releases or blog posts.'),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
  );

  foreach ($types as $type) {
    $type = node_type_set_defaults($type);
    node_type_save($type);
    node_add_body_field($type);
  }

  // clear the site cache

A few notes about this code

It doesn't use Entity API
st() function should only be used during a Drupal installation process
Node contains a lot of non Field API fields that it handles in node_type_save
Node calls field_attach_create_bundle to tell Field modules about the new bundle

Creating a bundle with the Entity API

I'm not sure how you've defined your entities, but if you've used Entity API then your bundle-creation code might look something like this:

$bundle = new stdClass();
$bundle->type = 'project_hr';
$bundle->label = t('HR Project');
$bundle->is_new = true;
$bundle->description = t("A super cool project");

$controller = new ProjectTypeController('project_type'); //assuming you defined this extension of EntityAPIController
$controller->save($bundle);

A note about Entities

An entity type is an abstract base class
A bundle is an extended entity type class
A field is a class member, property, variable or field instance
An entity is an object or instance of a base or extended class

More about entities


What is the right way of installing Drush?

You do not necessarily have to run composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction to create a new Drupal 8 site using the drupal-project composer package.

You can also just download the composer.json of that project and place it into your future Drupal 8 base folder. Then you can alter the installer paths within that composer.json to your liking. So if you prefer public over web as your Drupal root, then rename that part of the installer paths. You may also wish to alter the project name or other details of the composer.json file.

After your customization, you can then run composer update to generate an according composer.lock file. Assuming you did so on a local development environment, you can then use composer install --no-dev on your production system after uploading your composer and custom files/checking them out if you use a code versioning system.

Coming to the folder structure: It is advisable to keep the folder above the Drupal 8 root as base folder of your root package (project), location for the composer dependencies (vendor folder), Drush site settings, and auxillary files that should not be directly accessible from your web URLs (e.g. exported configuration files, private files, temporary files, Node.js packages, ...).

Therefore you should consider pointing your virtual hosts' root directories for example to /home/username/public_html/web (or /home/username/public_html/public, if you customized your composer.json like that) while using the regular root directories of your hosting panel /home/username/public_html as composer root package folder.

Depending on your hosting panel, you may have the ability to alter the vhost root directory by overriding the web server settings (e.g. defining a DocumentRoot for Apache, or a root for Nginx). How to do this depends heavily on your used hosting solution and is therefore off-topic in Drupal Answers.

And yes, you will have this folder structure on every of your projects. As every project may require a different version of dependencies, different modules (which may add dependencies with certain version restrictions to the vendor folder as well), binary tools for the shell, probably applied patches and so on. These dependencies and their version requirements are project specific, even when you use a global Composer installation.


Yup its possible, PHP is specifically a web based language -- which Drupal is built upon.

For a REST based consuming service client for instance look at the Guzzle drupal community project. There is also the Services Client drupal community module to consume remote web services and uses UUIDs to map/sync fetched data. Your mileage may vary but all the pieces exist within Drupal and PHP. For instance even D7's core drupal_http_request can be used to craft your own HTTP requests, or your underlying PHP's installation CuRL library if you find drupals http function hindered by defaults.

There is also an issue and related sandbox project to add SOAP support to the Feeds drupal community module.

You say SOAP but thats only 1 piece of what can go over the wire. I've had to consume WS-* + SOAP based APIs from Drupal/PHP and I ended up creating XML by hand with CuRL to do it all. There are also libraries such as:

http://wso2.com/products/web-services-framework/php/

or this library to extend php5 ext/SOAP:

https://code.google.com/p/wse-php/

Ultimately understanding the remote API specs, and inter-operating with them from Drupal is on you the developer.


If the code posted above is correct, the indentation is off. It should look something like this:

search:
  version: VERSION
  js:
    extras/js/drupal/search/sort.js: {}
    extras/js/drupal/search/filter.js: {}

See how js is not indented under version?

The second part of it is you have to tell Drupal to load it either sitewide, or on demand:

Sitewide, you need to declare this in your theme info yaml:

libraries:
  - mytheme/search

If you want to do it on demand, something like:

/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(array &$attachments) {
  $current_path = \Drupal::service('path.current')->getPath();

  // We really want to minimize the loading of these two libraries
  // for anonymous users. so far, we only need it on any /search* path.
  if (preg_match('/\/search+/', $current_path)) {
    $attachments['#attached']['library'][] = 'core/drupal';
    $attachments['#attached']['library'][] = 'core/jquery';
    $attachments['#attached']['library'][] = 'mytheme/search';
  }
}

Or you can put it in a specific twig template i.e. node.html.twig like this

{{ attach_library('mytheme/search') }}


How to add a field default to bulk user records

Check out the answers to this question: Bulk field update? In particular the answer suggesting "Execute Arbitrary PHP Script".

(Looks like a duplicate.)


Out of the box (w/ core modules only) default account emails (and any other emails) that Drupal generates do not support HTML. Drupal converts all html emails to plain text before sending. You can install and configure MimeMail module and its dependencies. Then you'll be able to insert html markup into the account email body field at 'admin/config/people/accounts' and have those emails sent properly in html.


How to add a sub-theme for mobile version?

Create another subtheme (lets call it mobiletheme ) and with mobile theme module set your mobile version of site use mobiletheme.

  Adds the ability to choose a mobile theme in
  admin/build/themes/settings which is used for serving users on mobile
  devices.

another solution is detect and set theme for mobile with themekey module (Check  tutorial here: http://mustardseedmedia.com/podcast/episode52 )

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules. In combination with Drupal's
  theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server
...

  And unlike other theme switching modules, ThemeKey should play well
  with internal and external page caches, like Boost or Varnish, even
  for anonymous users.

but really it is heavy module and if you want only want switch to another theme when user surf site with mobile I strongly recommend you to use   mobile theme module.


Second Product variant image in fb share is not coming

[node:field-product:1:field_images]

You'd add that in your metatag image field together with the first token that you mentioned, separated by comma.

If fb is still not picking it up, after your fetch new scrape info, try adding :file:url to your tokens.

[node:field-product:0:field_images:file:url],[node:field-product:1:field_images:file:url]


Adding a query string to menu items determined by the current node?

The menu is cached. You could disable caching and add the query string to the options of the url in hook_link_alter, but this is not good for performance. So this would be better solved in javascript. You can prepare the link in php by setting an attribute, so that you can easily find the link later in the client and attach the query string.


how to add javascript with #attached and hook_page_alter

The code that finally got it included an important change with regard to @AyeshK 's answer. The [attached] is not put at the top level if $page , but inside ['content'] or ['header'].

The adapted code from the Format#1 is now:

function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['content']['#attached']['js'][] = array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'
  );
}


Get the current ProductVariation from the formElement of a custom widget in the "Add to cart" form

At the moment i ended by getting the value directly from the $_POST, sounds a bit hacky but can't find another way to do that...


The entities aren't loaded by default (for performance reasons), but TermStorage::loadTree takes a $load_entities parameter:

  If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy_term_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.

That will give you access to the fields. E.g.

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadTree($vid, 0, NULL, TRUE);


Can failure to increase new user's UID consistently by one be related to this line inside user.module file?

uid and other identifiers are not sequential since Drupal 7. Identifiers are generated using a sequence API, see this issue: https://www.drupal.org/node/356074

If you check the db_next_id you'll see that the number passed as argument is just de minimum id that is considered valid.

See also this question and answer: What could cause uids to not be numbered consecutively?


How do I load a form with a specific form display (form mode)?

In D8 you can add display modes for forms in UI. But these form modes can't be used right away like view modes.

If you want to use a form mode in code you have to set a form operation with the same name in the handlers section of the entity type. The form class you use for this handler is the same as in the default handler, because you want to control which fields are displayed in the form mode, not in a different form class.

For example to use a form mode profile2, which you have configured in UI, you have to add a form operation profile2 to the user entity type definition in a hook_entity_type_build:

mymodule.module

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('profile2', 'Drupal\user\ProfileForm');
}

Then you can use the new form operation (form mode) in the code example from the question:

public function content($substep) {

  $user = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->load(1); // loading user 1 for test purpose

  $form = \Drupal::entityTypeManager()
    ->getFormObject('user', 'profile2')
    ->setEntity($user);

  return \Drupal::formBuilder()->getForm($form);
}


How change 1 line of code in a core module without hack?

You can take 3 different strategies to mitigate the problem the hack introduces.

Don't Hack/Ignore the error: Without knowing the deeper context of when this happens, this could be (as the d.o. thread suggests) just a quirk of other contrib modules that show up during the update process. You'll need to do more investigation to see if this occurs during a critical code (e.g. a module update) and if it can be ignored.
Don't Hack/Fix the error: Assuming the error is fundamentally a part of Drupal's forum module logic (i.e. not just something caused by a contrib module), you could submit a patch for the module to get it fixed for everyone that has the same issue.
Patch Management: Depending on your own codebase, process, & issues, patching might be unavoidable here. If that's the case, you can create your own patch for Drupal core and create some process where it is consistently applied every time you need to you need to update your codebase.


First Login Module will do the job for you , this is some description about this module from its page :

  A simple utility module which enables the use of "first logins". With this module the site admin can enable content or do things that appear only on the first login for users by using modules like Context or Views. Couple useful functions are included for use in custom modules.


How to add a checkbox in checkout form to optionally add 5$ to the product price as a donation?

Have a look at the Commerce Donate module. From its project page:

  This module provides a donation line item type along with a donation product and product display. This is partially based on Randy Fay's excellent screencast at http://commerceguys.com/blog/using-custom-line-items-provide-donation-fe...

  It uses the Select or Other module to provide the donation amount form field. If you need to modify the default donation option values, the install the Commerce Customizable Products module in order to modify the line item type form settings.

  In addition to being able to create a donation product, this module also provides a donation checkout pane, allowing customers to add a donation to their order as part of the checkout process.

Especially the last paragraph seems pretty close to what you're looking for.


Drupal 7 - Suppress output of nodes on Taxonomy Pages

Solution from http://www.wardontheweb.com/remove-node-lists-from-taxonomy-pages-in-drupal-7/ works for me well:

function THEMENAME_preprocess_page(&$vars){
   if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))){
     unset($vars['page']['content']['system_main']['nodes']);
     unset($vars['page']['content']['system_main']['pager']);
     unset($vars['page']['content']['system_main']['no_content']);
   }
}

Note: you should reset your site's cache.


How do you go without hierarchical taxonomy filters, when the site heavily relies on content browsing(multiple filters and sorting)?

This is unfortunately a big pain point with Drupal 7.  On my site, I handled this with Views and Panels.

In my case, the hierarchies with places generated by the Location taxonomize module in the form of country / state / city or country / city.

To give you a rough idea of how I approached it: I overrode the taxonomy term path using Panels/Page Manager.  I then added two variants in the following order:

a variant containing a content pane that aggregates countries and shows only those countries with 1 or more entries
a variant containing a content pane that takes a country as an argument/contextual filter and shows users having that taxonomy term as well as  a list of states using the special Panels related terms (show children) block

Depending on the structure of your taxonomy and what you are trying to show, this can be an extremely complicated setup, but it is possible even without direct support from hierarchical select.


There are two things you should know to make it works:

Your query should extend PagerDefault.
Element inside content should be Rendered Array

here is a working example adjust the code to your needs:

//- Build array
  $build = array();
  /**
   * @TODO: adjust the query to your needs.
   */
  //- Prepare the Query to Extend PagerDefault
  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
    ->fields('n', array('nid'))
    ->condition('type', 'page')
    ->condition('status', 1)
    ->execute()
    ->fetchCol();
  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $content = array();
    foreach ($nodes as $event) {
      //- Prepare the content
      $content[] = array(
        '#type'   => 'markup',
        '#markup' => '
' . $event->type . ' - ' . $event->nid . '
',
      );
    }
    //- Add Content to the build
    $build += $content;
    $build['pager'] = array(
      '#theme'  => 'pager',
      '#weight' => 5,
    );
  }
  return $build;


Rule should not fire when user logs in with one-time-link from password recovery

You may want to give this a try:

Rules Event: User has logged in.
Rules Condition: Text Comparison with

Text Data Selector = site:current-page:path
Matching Text = reset
Comparison Operator = contains

Rules Action(s): whatever makes sense.

I'm not 100% sure about the value of the "Matching Text" (if it's not reset, then adapt that value to something that fits for these kinds of one time login URLs).


Form submission not saved when using a dynamic redirect

A form submission handler, as well a form validation handler or a hook to alter a form, should never call drupal_goto() since it outputs a HTTP header and interrupts what Drupal is doing.
The correct way to redirect a form from a form submission handler is setting $form_state['redirect'] in Drupal 7, or calling $form_state->setRedirect() in Drupal 8. The alternative for Drupal 8 is calling $form_state->setRedirectUrl().
For Drupal 7, the following code would redirect the users to node/123?foo=bar#baz.
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);


You can add your form validation handler (hook_form_alter):

$form['#validate'] = array('delete_validation_handler') + $form['#validate'];

Your validation handler:

function delete_validation_handler($form, $form_state){
    if(!$form_state['values']['confirm_delete'])
        form_set_error('confirm_delete', t('Message about to confirm it first'))
}


I think the Pathologic contributed module will do it. I have used it in the past and it's awesome. Configuration is a bit tricky, but once it's done you can forget about most file path problems. It's an input filter for text, so it can be used anywhere you can set an input format.

Configuration of Pathologic is covered here. I think it may have issues with internationalization in some cases though.


How to display configuration updates when deleting fields programatically

As discussed in the comments the solution, in most cases, is to add the field storage to the config/install folder of the module specifying persist_with_no_fields: true.
core/modules/block_content/config/install/field.storage.block_content.body.yml
langcode: en
status: true
dependencies:
  module:
    - block_content
    - text
id: block_content.body
field_name: body
entity_type: block_content
type: text_with_summary
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: true
custom_storage: false

Then the configuration updates will be displayed when the module is uninstalled.
Sometimes the dependencies on the module disappear after configuration saves because Drupal is optimizing duplicate dependencies. Then enforce the dependency for this configuration item. See How to properly manage field types for a content type created by a module?


Sending a JavaScript variable to a PHP function

Let's look at what the client can do as an alternative to setting a cookie:

Make an AJAX request that lets the server store the variable.
Add the variable name and value to the query string of every internal link and to every form submission (not just the next one).

I do not see any benefits of Solution 1, that justifies the extra HTTP request. Especially, you cannot circumvent the necessity for the user to have Cookies enabled, because the value must be stored close to the user and Drupal uses Cookies exclusively to determine the session (and thus the user).

Solution 2 allows for different values within the same session. If this is not one of your requirements, I consider this solution too much of a hassle.


How to expose variable from php to js - and keep it updated?

You have two options, depending on how responsive you need it to be, and how complex you're willing to get:

1) You can add Javascript to your page that will continually send AJAX requests to the server in the background, essentially asking for the value of that variable. You would achieve this by creating a new menu path with the sole purpose of serving the value of that variable in JSON. The JS that sits on the page could then be set up to ask for that variable every X seconds until it changes (or it could just keep doing it forever if you wanted).

2) You could write a separate Node.js application that runs on your server, which listens for updates to the variable from the background task  and then pushes a notification to the JS in your page via websockets. That's obviously a lot more complex. But potentially more performant, and the updates would be instant. See this module for an example of a Node.js chat application: https://www.drupal.org/project/nodejs


The block widths are most likely controled by the theme CSS and it seems each block is given a third of the width of the container.

To change that and make one block take up two thirds of the container width you have to override the theme CSS. Exactly which selector and declarations to use depends on your particular case. You enter your overrides in the CSSinject or a similar module that overrides CSS through the interface.

If your theme is using floats, then you can find with your browser dev tools which selector was used to set that and the width, then use that same selector but with your own declaration override, something like:

.special-region .block {
  width: 60%;
}

If the layout method isn't floats then you'll have to adjust accordingly.

One other thing to consider is that this is most likely only code for wide screens, and it should be different for mobiles. Usually the mobile styles stack blocks one on top of the other so you won't have to do anything there, but you'll have to restrict your float to the same @media query as used by the theme, for example:

@media screen and (min-width: 900px) {
  .special-region .block {
    width: 60%;
  }
}

You can find out about which media query is being used through the browser dev tools.


In Drupal the content of a page view is created by a template file and $variables. The variables are typically a simple PHP string or Drupal7 render arrays when the content is more complex than just a string, and the system composes all the render arrays into page output.

A render array for instance can be a Webform, or a Node of a Page (content type). When you place Node ID 1 which contains a Webform reference the system is really composing these 2 items into your 1 page.

A single key per render array may be a #weight value this integer value denotes where this content appears from top to bottom among the many render arrays composed by the system within a given Region of the page.

Yes, it is possible to flip or change the ordering of the Body field and the Webform presentation to the visitor. Typically you would do this in the theme layer of drupal by implementing a Drupal hook to change the weight value in a render array.

If you don't want to code alot there are numerous modules that can let you change the display of items on the page with little or not coding. One example is Display Suite (otherwise known as DS). It allows you to override or customize view_modes of content on your site.

For example I have on a website the default Drupal content type of Page, and I've configured Webform to allow webforms to be placed on Page Nodes. Using DS I could change all webforms to appear before the Body of the Page Node in a simple administrative UI:

I leave it to you to do additional research to find the tool(s) you are comfortable with to complete your task. I've outlined at least 2 here (DS and core APIs).

EDIT

To be clear, if you're using Webform as a content type directly (and not attaching it other content types) DS may not show you "Body" and "webform" fields on the Webform content type -- but the webform Node is still just a render array and its fields still have #weight values. I find it more useful to attach webforms onto content, then to use Webforms by themselves.


You can have node type specific page templates by adding custom template name suggestions from the template preprocessor then using those template file names.

For more information see Page templates depending on node type.


Creating iframe to be used in other websites

The problem was solved by installing and enabling Allow site iframing contrib module.

  Drupal 8 has a feature built into core that stops the site from being
  rendered within an iframe, there are good reasons for this -
  https://www.drupal.org/node/2514136 But sometimes you want your site
  in an iframe, so that's what this module does.


What hook runs on all filtered input text of all filter types?

Here's my best clunky workaround so far:

  <?php
  function mymodule_entity_presave($entity, $type) {
  $fields = field_info_fields();
  foreach($fields as $field) {
    if ($field['type'] == "text_long" || $field['type'] == "text_with_summary") {
      if( isset($entity->{$field['field_name']}) ){
        foreach ($entity->{$field['field_name']} as $langcode => $items) {
          foreach ($items as $delta => $item) {
            $value =&$entity->{$field['field_name']}[$langcode][$delta]['value'];
            $value = _mymodule_do_stuff( $value );

            if ($field['type'] == "text_with_summary") {
              $summary =&$entity->{$field['field_name']}[$langcode][$delta]['summary'];
              $summary = _mymodule_do_stuff( $summary );

            }
          }
        }
      }
    }
  }
}

Not ideal at all, but I think it beats the only non-core-hacking alternative I can see which is to use hook_field_attach_presave();. The code would be almost identical, and I believe it would be worse since we'd have to call and loop through field_info_fields() once for every field on every saved entity (instead of once for every saved entity).


Views exposed filter redirects to wrong url

View Settings - PANE SETTINGS (middle column) - Use Panel path:Yes


Entityqueue - Handler drop down is empty after installation

I uninstalled the module but it was still appearing in the Modules list and I could not re-install it for this reason. However when I re-enabled it and saved, the Simple Handler appeared in the drop down. Good grief.


Can't Write to Public Files but Permissions Appear Fine

Finally managed to solve this. The entire purpose of this cloned server was to test out speed improvements from PHP-FPM. So since PHP evaluation is essentially offloaded to PHP-FPM, it doesn't matter if httpd has permissions, it matters whether the php-fpm process has permissions.

ps aux | grep php-fpm output:

root      5744  0.0  0.3 462268 14988 ?        Ss   16:45   0:00 php-fpm: master process (/etc/php-fpm.conf)
php-fpm   5745  0.0  0.9 467332 35196 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5746  0.0  0.4 466656 16528 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5747  0.0  0.3 466656 14032 ?        S    16:45   0:00 php-fpm: pool www
php-fpm   5748  0.0  0.3 466656 14028 ?        S    16:45   0:00 php-fpm: pool www

groups php-fpm:

php-fpm : php-fpm

So the ownership of my folder as apache:web is what doesn't fit. I just added the user php-fpm to the group web and changed things back to 775.

sudo usermod -aG web php-fpm

I would love comments on pros and cons of what I see as other possible solutions, especially from a security perspective:

1) Add php-fpm to the 'web' group.

2) Make php-fpm the owner, and httpd as member of web so it can still serve the files later.


How do I limit permissions to manage an event?

Per the other thread listed above, Daniel answered:

  Are you saying you have never seen the 'Registration list' tab? If
  this is the case you need to create that view by enabling rng_views
  module. Then go to the event type edit form. An option to create the
  view will appear.

This worked perfectly, thanks again Daniel!!


How to remove exposed filter if value is supplied in url?

Here's a clever way to do it without coding: use two different Views displays and embed one of them as View area into another's No results behavior and configure the contextual accordingly.

Create the Page with the Exposed Filter but without the Contextual filter
Duplicate that Page to create another Page display with the same Path, but make these changes:

override the Filters and remove the Exposed filter
override the Contextual filters and Add your Term name there with these settings:
When the filter value is NOT available
Display contents of "No results found"
When the filter value IS available or a default is provided
Specify validation criteria
[your settings]
Action to take if filter value does not validate
Display contents of "No results found"
Override the No results behavior, add View area and choose the first Page display under View to insert (the one with the Exposed filter). Save the View if you don't see that display as option at first.

This way you get the first page to kick in for /some-path and you see the exposed filter, but if you add a term name to the path and it validates /some-path/value2/ the second Page display kicks in and you don't see the Exposed filter, you see the contextual results.

If the argument doesn't validate, you see the first Page and allow users to choose the term from the Exposed filter. You can change that to something else if it makes more sense. The part that makes this views switching work is the first part of the contextual filter When the filter value is NOT available
Display contents of "No results found" and the embedded View area.


Adding class to form element via hook_form_alter for views exposed filter is not working

Did you check the actual markup after the page is rendered with Firebug or something to see for sure if another module's hook_form_alter() is overriding yours? If that is indeed the case then an easy way to get around is it by increasing your module's weight so hook_form_alter() in your module is called after other modules.

db_query("UPDATE {system} SET weight = 20 WHERE name = 'my_module'");

EDIT: I should say that this code should go in hook_install() and you should then reinstall your module to get the weight set properly.


How can I programmatically apply text formats?

As I was pressing post on this question, I realized the problem. It's the twig code. In order to get the text formatter properly applied, I had to call my field as follows:

{{ content.field_career_job_description1 }}

Leaving this question up because I couldn't find anything like it on google


How to automatically highlight syntax of code displayed on page?

There are several options to highlight code.

From the modules available on d.o. -- GeSHi Filter and Syntax highlighter

A very recent module (yet to make it to Drupal.org) is Wiredcraft's highlight_js on GitHub. They provide a Drupal 7 only version, but (*shameless plug*) I've ported it to Drupal 6 -- https://github.com/ThinkFabrik/highlight_js/tree/6.x-1.0

Edit: depending on the module you may either have to create a new input filter or use Full HTML to get best results


Programatically render a node in a specific language

The field labels are used from the config translation system. You also need to set the config override language. See user_mail() in core.

  // Temporarily alter the language manager.
  $language_manager = \Drupal::languageManager();
  $langcode = $message['langcode'];
  $variables = array('user' => $params['account']);

  $language = \Drupal::languageManager()->getLanguage($params['account']->getPreferredLangcode());
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);
  $mail_config = \Drupal::config('user.mail');

  // Restore the language manager.
  $language_manager->setConfigOverrideLanguage($original_language);


Theme Ubercart product node and form in Drupal 8

This might work:

public function MYFUNCTION() {
  $myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myformclass]');
  // If you want modify the form:
  $myform['field']['#value'] = 'From my controller';

  $build = [
    '#theme' => 'mytemplate'
    '#form' => $myform,
  ];
}

In twig:

{{ form }}


Documentation for the API exposed from Pressflow

Pressflow is designed to be API compatible with Drupal. As a consequence you should only use the API functions of Drupal 6 when developing for Pressflow 6.


Ternary Flags? Or possibly cancelling flags

This is not available in the Flag module (as you already know) and won't be available in the future (Issue: Flag States).  I have not seen an add-on module that will allow you to do this either.

An easy way would be to use Flag with Rules.  You would have to create multiple flags to use, and when a user flags one of the states, have set rules to unflag the other 2 states.

Another option would be to write a custom module.  Maybe even utilize the Voting API


Programmatically deleting a filefield content and the associated file?

No, it doesn't. You should use file_delete(). The function will remove the attached file from the database and from the disk.

// Load the node.
$node = node_load('1');
// Get the language for the file field.
$lang = field_language('node', $node, 'myfilefield');
// load the file
$file = file_load($node->myfilefield[$lang][0]['fid']);
// unset the field for the node
unset($node->myfilefield[$lang][0]);
// delete file from disk and from database
file_delete($file);
// Save the node.
node_save($node);

The file_delete() also takes a second argument $force that if set to TRUE will remove the file even if it's reported as in use by the file_usage table.


Seems to me that you should consider the Profile2 module for getting this to work.

Excerpt from issue # 1796856 :

  Multi-Step Registration module works out of the box with Profile2 and all we need to do is assign the profile type to a particular step.

That same issue also contains some extra details about getting around possible access errors.

Refer to the Community documentation of Profile2 for more details about this module.


Just posting this for future viewers:

You can add a hook to the theme_webform_mail_headers in your theme's template.php

function mytheme_webform_mail_headers($variables) {
    $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
    );

    $headers['cc'] = 'email@example.com';

    return $headers;
}


How to show new added filed to comment table in comment form page

First, you need to make sure Drupal knows about your paragraph field. Adding it to the database alone won't work. Use hook_schema_alter() to alter the DB schema information for the comment table. Do this by adding something like the below to your module's install file (a PHP file you name mymodule.install in your module's folder):

function MYMODULE_schema_alter(&$schema) {
    $schema['comment']['fields']['paragraph'] = array(
        'type' => 'int',
        'not null' => FALSE,
        'default' => 0,
        'description' => 'Paragraph of the comment.',
    );
}

Be sure to flush your caches to update the schema.

Now you need to alter the comment form, and process the paragraph value. Something like the below should work:

function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
    $form['paragraph'] = array(
        '#type' => 'textfield',
        '#title' => t('Which paragraph you want to put comment on?'),
        '#required' => FALSE,
        '#size' => 10,
        '#maxlength' => 2,
        '#default_value' => !empty($form['#entity']->paragraph) ? $form['#entity']->paragraph : NULL, // set the default value to the current paragraph value
        '#weight' => $form['subject']['#weight'] + 1, // place after the subject field by setting the weight to +1 of subject weight
    );

    $form['#validate'][] = 'MYMODULE_form_comment_form_validate';
    $form['#submit'][] = 'MYMODULE_form_comment_form_submit';
}

function MYMODULE_form_comment_form_validate(&$form, &$form_state) {
    if (!is_numeric($form_state['values']['paragraph'])) {
        // Validate the paragraph value to make sure it is numeric. Non-numeric values will break because we created paragraph as an integer field
        form_set_error('paragraph', t('Only numeric values are allowed for paragraph number.'));
    }
}

function MYMODULE_form_comment_form_submit(&$form, &$form_state) {
    // update the paragraph field in the comment table
    db_update('comment')
    ->fields(
        array(
            'paragraph' => $form_state['values']['paragraph'],
        )
    )
    ->condition('cid', $form_state['comment']->cid)
    ->execute();
}


I believe you have to use the Rules module and create a new rule.

Use react on: after payment is received/complete (or something along those lines)

Then use add action >> set a data value >> (find your order status field token)


Getting group posts in og's home page view

I recommend creating a whole new view, which would list the three most recent posts for the group passed in the argument.

To make it work together with your existing og view, you'll want to attach the new view to your group content type using one of Viewfield, Views Field View and View reference modules.

For example, using Viewfield; to the group node type add a hidden View field called Recents. Set it to "Always use default value". Set the default value to the recent posts view. The argument is "%nid". Exclude its display from node teaser, full view etc.

In the group view, then, along with group name and mission, also add Attrview as a field. Good luck!


Allow special characters in the Search Form

Drupal's built-in search, as well as Search API, generally search full words.
Using Search API, you can further configure the search to match parts of words and consistently ignore special characters in the matching process (as some may reserve other purposes like logical AND / OR).

Based on your use case/example,

check the minimum character length for search suggestions (it is usually three) (but since it strips away special characters such as the &, your search criteria is only two characters), and
enable the "Ignore characters" processor and configure it to ignore the ampersand symbol, hyphens, or any others consistently in both the form submission and the search index results as suggested here in this Search API issue post: Special characters are always ignored in searches on DB backend

Additional references:

Review all the configurable Search API processors to ensure you are indexing your content appropriately: https://www.drupal.org/docs/8/modules/search-api/getting-started/processors
Check out this succinct blog post "How to set up search API for partial words in Drupal" that provides a checklist for configuring your Search Index.
Consider configuring a search view that reflects a "Single phrase" parse mode to find exact matches with special characters. This Using Search API, Search API Solr and Facets in Drupal 8 slidedeck provides a good rundown of caveats with Search API for D8.


How to save custom label as parameter for a custom entity_reference field widget?

You need to create a custom field type that can hold the value along with the entity reference.

A field widget can not store any data that the field type has not provided space for.

You must create a new field type would look similar to this:

<?php

namespace Drupal\MY_MODULE\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;

/**
 * @FieldType(
 *   id = "entity_reference_with_value",
 *   label = @Translation("Entity reference with value"),
 *   category = @Translation("Reference"),
 *   default_widget = "my_custom_field_widget",
 *   default_formatter = "some_formatter",
 *   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
 * )
 */
class EntityReferenceWithValue extends EntityReferenceItem {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = parent::schema($field_definition);
    $schema['columns']['value'] = [
      'type' => 'varchar',
      'length' => 255,
    ];
    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Value'))
      ->setRequired(TRUE);

    return $properties;
  }

}

Now you can get the value with $entity->field_name->value.

It would also be better to extend EntityReferenceAutocompleteWidget in your field widget, instead of WidgetBase. Then you can just do like this in the formElement method:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $widget = parent::formElement($items, $delta, $element, $form, $form_state);

  $widget['value'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Value'),
    '#default_value' => $items[$delta]->value,
    '#weight' => 999,
  ];

  return $widget;
}


Use view_embedd_view function and you will get the view.

$output = views_embed_view($viewName,$display_id);
print $output;


When to create schema while working with config entity?

Short answer: you should always have one, but you can avoid it if you really want (see point 3 below).

  What are schema files used for?

  The primary use case schema files were introduced for is multilingual support. We need to have a tool to identify all translatable strings in your shipped configuration so when you ship with your own settings as well as default Views, additional user roles, menu items, etc. we can offer those up for translation as part of your module/theme release on http://localize.drupal.org. The nesting levels and types would be enough for this use case.
  We also use schemas to provide actual translation forms for configuration based on your data. This use case is where types gain more importance and labels become crucial. The core Configuration translation module uses schemas to generate translation forms and save translations. The two most important built-in translatable types are 'label' for one-line text input and 'text' for multiline text input.
  Using the knowledge embedded in the configuration schemas about what is stored of a configuration entity, the default persistence implementation for configuration entities requires a configuration schema for the configuration entity, so the right properties are exported with the types defined. Although it is better to provide configuration schemas, if you really don't want, implement the toArray() method in your configuration entity implementation to not require schema for saving configuration entities of your type.
  Last but not least configuration schema is also used to automatically typecast values to their expected types. This ensures that although PHP and web forms in general favor strings over all other types, the right types are used when saving configuration. That is important so when deploying configuration, only actual changes will show up in the difference, no random type changes.

From Configuration schema/metadata


User roles and keeping their IDs when using features

The Role Export module causes Role IDs to be hashes of Role Names — so the same Role Name will have the same Role ID on all sites.  Great in conjunction with Features.

For Taxonomies, the UUID Features module may be helpful.


How to create a custom Webform handler to submit to a SOAP API

In your custom module add a folder src/Plugin/WebformHandler and create a file Subscription.php. Add the following code:

<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "subscription",
 *   label = @Translation("Subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions via SOAP"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class Subscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const SOAP_URL = 'x'; // url of soap call here

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // The data to send to the API
    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // Add your SOAP Call here
    $client = new SoapClient(self::SOAP_URL);
    // .. Go on here
  }
}

Enable the module and clear cache. Now, in your webform backend, go to settings and then emails / handlers (/admin/structure/webform/manage//handlers). Add your handler here. For a little more detail and instructions, see: https://stefvanlooveren.me/blog/how-create-mailchimp-subscription-drupal-8-webform-module


How do I modify the URL to a taxonomy term?

Please check if you have a URL Alias in the system for "/term1".

It might be mostly the case of all your old Alias existing in the system not the new once. If you don't find the update URL alias under admin/config/search/path. Then it just a simple bulk regenerate (admin/config/search/path/update_bulk).

Please ensure you have selected

Taxonomy term
Update the URL alias for paths having an old URL alias (at Times you may want to use the option Regenerate URL aliases for all paths)


How do I get rid of the "Configure Blocks" link above my menus?

I think those links come from the core "Contextual links" module; you should be able to pop to http://mysite.com/admin/modules, disable the module and see the links disappear :)

A bit of extra info on Contextual Links:

http://drupal7ish.blogspot.com/2011/06/contextual-links.html


If you are asking about theme()ing the page on which the node edit form is displayed, you would use page--node--edit.tpl.php.

More information on Drupal 7 Template Suggestions can be found here.


So after some research i have found the answer. I did this with ajax submit. In hook_form_alter i have added ajax submit callback with markup element:

$form['actions']['submit']['#ajax'] = array('callback' => 'common_webform_client_form_1562_submit_handler',
           'wrapper' => 'form-ajax-node-content',
      'method' => 'replace',
      'effect' => 'fade',);
       $form['markup'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
            '#markup' => '',
            '#weight' => 2000, //set weight to show markup at the bottom of the form
       );

And in my callback i can generate any output i want to!)

function common_webform_client_form_1562_submit_handler($form, &$form_state) {
   $output = 'Dummy text';
   $form['markup'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
            '#markup' => $output,
            '#weight' => 2000,
       );
    return $form['markup'];
}


A Product Page with dynamic variants without using Commerce

As the user eluded, display suite or perhaps panels would be the go-to way to dealing with customized multi-column content type displays. Often on commerce sites, the quick tabs module is used to display tabbed product information.


Create multiple basic pages with different fields

IIUC you need the Bricks module. This module is similar to Paragraphs but a lot more abstract and allows for the customized options you mention.

You will have to create all the possible "Bricks" that can be found on your pages, then it won't be difficult to create each page with the custom structure it's supposed to have.

You don't have to use the Layout builder if your cases aren't that complex. The most important thing is to create some strategy around your different cases, analyze your needs so you know what different combinations need to be created. Go for the simplest possible solution, don't overcomplicate needlessly or you'll create a mess that is difficult to maintain.


You can use Path Breadcrumbs module. This module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL.

If this module is not satisfy your requirements, then visit Comparison of Breadcrumb Customizing modules to get more information.


How to rename uploaded file using form API and Drupal managed_file field

Assuming you know about file status, file_save & file_usage_add.

In your submit callback:

$file = file_load($form_state['values']['image_fid']);
$file->filename = 'somefilename';
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'yourmodule', 'foo', 1);

More info at the Form API Reference.


How to update a field in Drupal 7 without saving whole node

function common_update_db($entity_id, $field_name, $value, $clear_cache) {
  foreach (array('data', 'revision') as $table) {
    $result = db_update('field_'.$table.'_'.$field_name)
        ->fields(array(
            $field_name.'_value' => $value,
        ))
        ->condition('entity_id',$entity_id,'=')
        ->execute();
  }
  if ($clear_cache) {
    cache_clear_all("field:node:" . $entity_id, 'cache_field');
  }
}

This will update the field and the revision field. If you send clear_cache = TRUE, it will also clear that nodes cache. This only works for *_value fields and nodes, but it's easy to modify.

Examples:

common_update_db(1234, field_run_cron, 1, TRUE);

on node 1234, set field_run_cron value to 1 and clear the cache for immediate visible effect to the user.

common_update_db(1234, field_run_cron, 0, FALSE);

on node 1234, set field_run_cron value to 0, don't clear cache as the user doesn't see this field anyway.


How to insert a link in a private message by code?

This is how I do it:

function _send_notifications($entity, $recipient) {
    $params = set_params($recipient, $entity);
    $sent = privatemsg_new_thread(array($recipient), $params['message_subject'], trim(token_replace($params['message_body'])));
}

function set_params($account, $entity) {
    if (isset($entity->nid) && $entity->type == 'entity_type') {
        $author = user_load($entity->uid); // Load the node author.
        $params = array(
            '!first_name' => $account->field_first_name[LANGUAGE_NONE][0]['value'],
            '!last_name' => $account->field_last_name[LANGUAGE_NONE][0]['value'],
            '!node_type' => drupal_ucfirst(str_replace('_', ' ', $entity->type)),
            '!node_title' => $entity->title,
            '!node_url' => url(drupal_get_path_alias('node/' . $entity->nid), array('absolute' => TRUE)),
        );
        $data['message_subject'] = t('New node type has been created');
        $data['message_body'] = t(
            "Dear !first_name !last_name,\na new !node_type has been posted with the title \"!node_title\".\n\nYou can view the post here:\n!node_url\n\n--  [site:name] team", $params
        );

    return $data;
}


Quiz Module persistance implementation details

You need to be familiar with Drupal concepts like Nodes and Entities because they are used to model a Quiz.

The logic to keep the pieces synchronized is implemented via Hooks, like _hook_insert_ and _hook_update_, located on the quiz.module file.

Quiz 2.0 Architecture Information

  A Quiz is a Drupal node, and thus the node table contains a row for
  each Quiz. Similarly, a Question is also a Drupal node, so it too has
  an entry in the node table. Additional properties for Quizzes can be
  found in the rows of the quiz_node_properties table. Similarly, all
  question-types have a table called quiz_node_question_properties to
  store additional data. Each question-type also makes it's own set of
  tables to hold answers and user feedback. That means the
  multichoice.module question-type gets a quiz_multichoice_answers and a
  quiz_multichoice_user_answers.

From Community Documentation: Chapter 3 ~ Under The Hood

hook_insert

/**
 * Implements hook_insert().
 */
function quiz_insert($node) {
  // Need to set max_score if this is a cloned node.
  $max_score = 0;

  // Copy all the questions belonging to the quiz if this is a new translation.
  if ($node->is_new && isset($node->translation_source)) {
    quiz_copy_questions($node);
  }

  // Add references to all the questions belonging to the quiz if this is a
  // cloned quiz (node_clone compatibility).
  if ($node->is_new && isset($node->clone_from_original_nid)) {
    $old_quiz = node_load($node->clone_from_original_nid);

    $max_score = $old_quiz->max_score;

    $questions = quiz_get_questions($old_quiz->nid, $old_quiz->vid);

    quiz_set_questions($node, $questions);
  }

  _quiz_common_presave_actions($node);

  // If the quiz is saved as not randomized we have to make sure that questions
  // belonging to the quiz are saved as not random.
  _quiz_check_num_random($node);
  _quiz_check_num_always($node);

  quiz_update_defaults($node);
  _quiz_insert_resultoptions($node);
}

hook_update

/**
 * Implements hook_update().
 */
function quiz_update($node) {
  // Quiz node vid (revision) was updated.
  if (isset($node->revision) && $node->revision) {
    // Create new quiz-question relation entries in the quiz_node_relationship
    // table.
    quiz_update_quiz_question_relationship($node->old_vid, $node->vid, $node->nid);
    drupal_set_message(t('Some of the updated settings may not apply to quiz being taken already. To see all changes in action you need to start again.'), 'warning');
  }

  // Update an existing row in the quiz_node_properties table.
  _quiz_common_presave_actions($node);

  quiz_update_defaults($node);
  _quiz_update_resultoptions($node);

  _quiz_check_num_random($node);
  _quiz_check_num_always($node);
  quiz_update_max_score_properties(array($node->vid));
}


Firing ajax_callback on textfield after a minimum number of character

One option is to use a custom jQuery event, eg. something like "startajaxCall". Set $form['my_input']['#ajax']['event'] = 'startajaxCall' and provide some JS to trigger your custom event after an appropriate number of keys is entered.


It works !! Try this
<?php

namespace Drupal\fapi_example\Form;

use Drupal\Core\Form\FormStateInterface;

class AjaxAddMore extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = array(
      '#markup' => '
'. $this->t('This example shows an add-more and a remove-last button.').'
',
    );

    $i = 0;
    $name_field = $form_state->get('num_names');
    $form['#tree'] = TRUE;
    $form['names_fieldset'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('People coming to picnic'),
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    if (empty($name_field)) {
      $name_field = $form_state->set('num_names', 1);
    }
    for ($i = 0; $i < $name_field; $i++) {
      $form['names_fieldset']['name'][$i] = [
      '#type' => 'textfield',
      '#title' => $this->t('Name'),
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['names_fieldset']['actions']['add_name'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add one more'),
      '#submit' => array('::addOne'),
      '#ajax' => [
      'callback' => '::addmoreCallback',
      'wrapper' => 'names-fieldset-wrapper',
      ],
    ];
    if ($name_field > 1) {
      $form['names_fieldset']['actions']['remove_name'] = [
      '#type' => 'submit',
      '#value' => $this->t('Remove one'),
      '#submit' => array('::removeCallback'),
       '#ajax' => [
        'callback' => '::addmoreCallback',
        'wrapper' => 'names-fieldset-wrapper',
      ]
      ];
    }
    $form_state->setCached(FALSE);
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function getFormId() {
    return 'fapi_example_ajax_addmore';
  }

  public function addOne(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    $add_button = $name_field + 1;
    $form_state->set('num_names', $add_button);
    $form_state->setRebuild();
  }

  public function addmoreCallback(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    return $form['names_fieldset'];
  }

  public function removeCallback(array &$form, FormStateInterface $form_state) {
    $name_field = $form_state->get('num_names');
    if ($name_field > 1) {
      $remove_button = $name_field - 1;
      $form_state->set('num_names', $remove_button);
    }
    $form_state->setRebuild();
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValue(array('names_fieldset', 'name'));

    $output = t('These people are coming to the picnic: @names', array(
      '@names' => implode(', ', $values),
      )
    );
    drupal_set_message($output);
  }
}


How can users set their own price for their products?

Assuming that you are using the Flag module (as I suggested in my answer to your prior question to "How authenticated users can choose favorite products and show them in their profile?", you could implement an extra (price) field when you define a flag. Such field can then be used to store the Product's price.

So if a user (= Store) then flags a product (to indicated "This store sells this product"), such user could use the extra field to actually indicate the price for that store.

Refer to the community documentation about Attaching fields to flags for more details about this.


My images are not showing up after importing to Pantheon

By default, images uploaded through an image field are saved to the sites/default/files folder and not the database. Be sure that you have also imported your /files folder into your new site and the images should show up without needing any changes to file paths.


I was able to achieve it by using the helper service defined in https://www.drupal.org/project/prev_next.


How do I extract individual fields from rendered user?

A lightweight custom module to create a block for your business members and one for your regular members should do it. Creating a custom block isn't as daunting as it seems, it's one of the easier customizations you can do. The Block API should be very helpful here. Here's a quick example:

 /* Implements hook_block_info() */

function myblock_block_info() {
  $blocks['my block'] = array(
    'info' => t('Business User Block'),
    'cache' => DRUPAL_CACHE_PER_PAGE
  );
  return $blocks;
}

/* Implements hook_block_save() */

function myblock_block_save($delta = '', $edit = array()) {
  variable_set('block_text_prefix', $edit['block_text_prefix']);
  variable_set('block_text_suffix', $edit['block_text_suffix']);

}

/* Implements hook_block_view() */
function myblock_block_view($delta = '') {
  //get the information you want out of the profile here
  $block['content'] = //your information formatted here
}

Devel info:

If you double click on a row in the devel table, it will tell you how to reference it:


From what I understand there are two primary reasons this was done. The first was because people were using templates incorrectly - they are supposed to be templates, not logic files. People were putting lots of logic into the tpl.php files, when any logic should be in a preprocess function. The other reason is that TWIG escapes data, preventing people from putting bad code into a template, making Drupal sites more secure overall.


Views Load More pagination causes duplication

Some suggestions:

1) Do not use the LOAD MORE option in views but use a self generated link with the help of global text in the footer. Then this link is going to a second page and then you have the view in a new fresh window. Hopes this helps.

2) You can try if the behavior of the view is the same without Ajax. Sometimes live is a miracle. if so you know that is a ajax issue and not a views issue.


Got it!

The main problem was that the new form was loaded from a cached version of the previous submitted form.

This is what I've got in my AJAX callback:

$new_form_state = array();
$new_form_state['build_info']['args'][] = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'node_type',
  'language' => LANGUAGE_NONE,
);
$new_form_state['no_redirect'] = TRUE;
$new_form_state['input'] = array();
$new_form = drupal_build_form('node_type_node_form', $new_form_state);
$commands[] = ajax_command_replace('#node-type-node-form', drupal_render($new_form));

The $new_form_state['no_redirect'] = TRUE; prevents the redirect, and the empty array in $new_form_state['input'] prevents the form from being loaded from a cached version.

@googletorp, thanks for the help!


How do I move a view display from a view to another one?

This is tricky, but you can export both views to code and then add the desired display manually to the View.

In your case:

First export User view and Flags views

The exported views should be something like this:

$view = new view();
$view->name = 'frontpage';
$view->description = 'Emulates the default Drupal front page; you may set the default home page path to this view to make it your front page.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Front page';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Content: Sticky */
$handler->display->display_options['sorts']['sticky']['id'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['table'] = 'node';
$handler->display->display_options['sorts']['sticky']['field'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['order'] = 'DESC';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Promoted to front page */
$handler->display->display_options['filters']['promote']['id'] = 'promote';
$handler->display->display_options['filters']['promote']['table'] = 'node';
$handler->display->display_options['filters']['promote']['field'] = 'promote';
$handler->display->display_options['filters']['promote']['value'] = '1';
$handler->display->display_options['filters']['promote']['group'] = 0;
$handler->display->display_options['filters']['promote']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 0;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'frontpage';

/* Display: Feed */
$handler = $view->new_display('feed', 'Feed', 'feed');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Front page feed';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'rss.xml';
$handler->display->display_options['displays'] = array(
  'default' => 'default',
  'page' => 'page',
);
$handler->display->display_options['sitename_title'] = '1';

As you can see, first you have the general View config, and then the definition and config for each view's displays.

Then you have to select the code regarding your display in User view and copy to the code of the Flag view, so you end with a Flag view with an added display.
Using the import functionality of Views import the modified view.

If everything is ok, Views will import your modified view with the added display.

The two views should be similar (they should show similar content, for example).


Avoiding entity-type errors on module installation

I've revised my approach here several times, but so far the cleanest solution in my opinion is:

Store the entity_type.manager service, not the storage. When the storage is used, place the whole chain $this->manager->getStorage()->loadMultiple() into a try/catch.

This avoids having to handle the special case in two places: Once in the constructor (when acquiring the storage might fail), and again in the loading function (when the storage might not exist, because it failed in the constructor).

<?php

namespace Drupal\dblog_persistent\Logger;

use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\dblog\Logger\DbLog;
use Drupal\dblog_persistent\DbLogPersistentStorageInterface;

/**
 * Class DbLogPersistent
 *
 * @package Drupal\dblog_persistent\Logger
 */
class DbLogPersistent extends DbLog {

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $manager;

  /**
   * @var \Drupal\dblog_persistent\DbLogPersistentStorageInterface
   */
  protected $storage;

  /**
   * @var \Drupal\dblog_persistent\Entity\ChannelInterface[]
   */
  private $channels;

  public function __construct(Connection $connection,
                              LogMessageParserInterface $parser,
                              EntityTypeManagerInterface $manager,
                              DbLogPersistentStorageInterface $storage) {
    parent::__construct($connection, $parser);
    $this->manager = $manager;
    $this->storage = $storage;
  }

  protected function getChannels() {
    if ($this->channels === NULL) {
      try {
        $this->channels = $this->manager
          ->getStorage('dblog_persistent_channel')
          ->loadMultiple();
      }
      catch (PluginNotFoundException $e) {
        $this->channels = [];
      }
    }
    return $this->channels;
  }
}


Views field that links to fragment URL of comment on /node/ instead of /comment/

An ugly workaround (which will not work for paginated comments):

Add the field "Content: Link to Content"

Use the relationship "Content" (should be default when creating a comments view)
Enable "Exclude from display"
Enable "Output the URL as text"

Add the field "Comment: Comment ID"

Set "Formatter" to "Unformatted"
Enable "Exclude from display"

Add the field "Comment: Title"

Set "Formatter" to "Plain text"
Disable "Link to the Comment"
Enable "Output this field as a custom link" (under "Rewrite results")
Link path: {{ view_node }}#comment-{{ cid }}
(field names might differ, use what’s listed under "Replacement patterns")


What would you want to configure?

As this message tells you, there is no need to configure anything when using the XMLRPC server. That's all. This isn't an error.


This is what the node api hooks are good for.

From the docs:

  The node passed validation and is about to be saved. Modules may use
  this to make changes to the node before it is saved to the database.

You don't specify D6 or D7

In D6

hook_nodeapi() $op == 'presave'

In D7

hook_node_presave()

You can modify values in your implementations of these hooks and they will be saved.

edit

If you need the NID you have to use hook_node_insert, but you will have to save to the DB directly.


I've come up with a working solution. It might not be the best approach but it works.

You need to create your routing file:

my_module.routing.yml

diocese_core.path_with_data:
  path: 'path-with-data'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::Render'
  requirements:
    _access: 'TRUE'

Creating the controller for your page

src/Controller/MyController.php

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use \Symfony\Component\HttpFoundation\Response;

/**
 * An example controller.
 */
class MyController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function Render() {
    $build = array(
      '#type' => 'markup',
      '#markup' => t('Hello World!'),
    );
    // This is the important part, because will render only the TWIG template.
    return new Response(render($build));
  }

}

And you only need to call in javascript

jQuery('#my-div').load('path-with-data');

An this will be the output once the code is executed:

Hello World!

References:

Drupal 8 module - How to use AJAX?
Drupal8:Basic Jquery Ajax custom module controller


The best way to get started is to watch the video series Learn the Rules Framework.  It will demonstrate how to create the node and populate any data fields according to the content in your type A node.


How to add an item to the secondary menu in Drupal 7?

See www.domain.com/admin/structure/menu/settings

If you set both to "main menu", then the parent items will be in the main menu and child items will be in the second level menu. The menu system will respect the access system, so if a anonymous user does have access to content A. They will not see content A in the menu.

Hope it helps


Publish content on user unblock event Drupal 7

In your custom module you could use a hook_user_update and if the $account->original->status == 0 & $account->status == 1 (meaning that the user just got active [untested]), publish the content.

something like:

<?php
/**
 * Implementation of hook_user_update()
 */
function MODULE_user_update(&$edit, $account, $category) {
  if($account->status && $account->status != $account->original->status) {
    // with the user id you can find (i suppose) the content this user has just
    // created and publish it, using something like the link below
  }
}

publish-unpublish


Show users a different page (depending on their role) after logging in

Have a look at the Front Page module. Module description:

  The Front Page module allows for customised home pages dependant on
  role. The pages can be of the following types:

  Alias (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
  Redirect - Allows you to redirect users to a local or remote URL.
  Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
  Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

One of the options should fit your need.


Page not found when trying to access my custom module

hook_menu() had 3 entries: one for entering parameters, one for showing the question selection, and one for showing the answers.

The error was in the second page, which still pointed to an old (disabled) URL.
The very very strange thing is that the module didn't show even the first working path and that there was no error of it.


How to put a token in field Simplenews -> Subscribtion block -> block message

It's likely there's no off-the-shelf solution here. The block message field is a variable in the Simplenews module. It's not possible to make variables dynamic; there's no hook to override variable values.

In order to make something like this happen, you'd have to use a combination hook_form_alter() to change the block setting form & hook_block_view_alter() to alter the output of the Simplenews block.


How to disable a module and its dependents modules with Drush?

You should update your drush by the sounds of things. Doing drush dis views should result in the following:

drush dis views
The following extensions will be disabled: views, views_bulk_operations, og_ui, views_content, og_example, views_php, views_ui
Do you really want to continue? (y/n)

Which means the dependents are disabled at the same time.


How to use drupal_get_form outside of a menu

As I understand it, you want to link to a page that displays a form and accepts certain parameters that will influence the form.

  2) I am also getting a message that says drupal_get_form is an unknown function.

That is because drupal_get_form() is not known when Drupal hasn't been formally loaded (bootstrapped). When you call PaymentMethodEditDelete.php directly, then Drupal doesn't know about it, and PHP doesn't know about any Drupal API functions. In order to have all Drupal functionality available, the point of entry must be the index.php in the webroot and not a custom script somewhere.

In order to achieve what I think you want, you need to define a so called menu callback. This is simply a url that is associated to a callback function. You can find more on the menu system in the docs to hook_menu().

In order to use this menu callback with drupal_get_form you would define the menu item like this:

function mymodulde_menu() {
  $items = array();
  ...
  $items['my/custum/url/to/form'] = array(
    'title' => 'My form title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_custom_form_id'),
  );
  ...
  return $items;
}

This is the bare minimum to define a page that will render as a form.

Now in order to handle arguments, you can either pass them in as ordinary $_GET parameters that you can access normally inside your form builder function.

Or you alter the newly defined menu so that it will accept additional arguments and passes them into the form builder, as arguments to drupal_get_form (see Wildcards in Paths). Also have a look at this question for more information: https://drupal.org/node/2054083.

Some more reading I can recommend:

What is the basic concept behind hooks?
http://befused.com/drupal/page-request


$form_state variable holds 'triggering_element' element which indicates what button triggered (or also you can use #clicked_button element), example (in ajax callback function):

function my_form_submit($form, &$form_state) {
  //dpm($form_state);
  if($form_state['triggering_element']['#value'] == 'MY_ELEMENT\'S_NAME') {
    //do_operation();
  }
}


Using .tpl.php files would indeed give you more control over the HTML Drupal will create in the end.
Also using a module like Display Suite (DS - drupal.org/project/ds) will give you more control over the fields in a certain display so that some settings about that field on that display are stored in database instead of in code.


How to install Social Auth LinkedIn PHP Library with composer for Open Social Drupal module?

According to the composer.json of that module, you need happyr/linkedin-api-client. So to install that with Composer, from the root of your Drupal project run:

composer require happyr/linkedin-api-client:1.0.0

Since that library has dependencies too, you probably need to install them too. Basing on the documentation, you could need to execute the following too.

composer require php-http/guzzle6-adapter
composer require guzzlehttp/psr7 php-http/message


What is the front page path of the Recruiter Distribution?

You can define it at /admin/config/system/site-information. This is the value the <front> path uses.

UPDATE:
The default frontpage after a fresh install appears to be /node as defined per /admin/config/system/site-information


Hierarchical Term Reference Autocomplete module have the option to show the children with their parent.

  This module provides a new widget for a term reference field that
  displays the parents of a term matching the autocomplete as well as
  providing actual TIDs back to the form handlers.


Can a form submit handler return results without using the $_GET array?

You can save $content in a session variable, and then redirect the users to a new page. The page callback of that page will then extract the data from the session data.

$_SESSION['mymodule_content'] = $content;
$form_state['redirect'] = 'form/result';

// The page callback then will execute the following code.
$content = $_SESSION['mymodule_content'];

The pros of using session data are:

There isn't the length limit GET data has
The data will not be visible in the browser address bar
The data can be complex like an array, or an object