It looks like what you'll want to do is add it in a separate js file in a module. Use hook_form_alter() or hook_form_FORM_ID_alter()and identify the form that you want the script run on. Then In hook_form_alter() use drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js'); to add the JavaScript file to that page.

Also in hook_form_alter(), you'll want to identify the button you want to add this to and add a prefix and suffix markup to it.

$form['button']['#prefix'] = array('
');
$form['button']['#suffix'] = array('
');

In the JavaScript file, where you see div.foo you'll want to enter the name of that div that you created on the button.

$('div.my-button-class').unbind('keydown', 'Ctrl+a', fn);

Also in hook_form_alter() you need to add a class to an input or button or whatever you are using.

$form['field']['#attributes'] = array('class' => array('my-other-class'));

For this, in the js file you need to replace:

$('input.my-other-class').bind('keyup', '$', function(){

EDIT: Note the input.class. If you're targeting a different type of element this will need to be changed accordingly. Same with div. class. I think you can also do IDs like input#my-input-id.


Hope this will help you,

Before site goes offline for maintenance mode, check the user who has permission to access the site during maintenance mode via admin/people/permissions
and check for this permission Use the site in maintenance mode. Default access will be given to the admin.

In Drupal 7, to create a custom maintenance page we have to override the default maintenance template file

We can do it by the following steps:

Copy maintenance-page.tpl.php from modules/system/
Paste it in active theme folder inside templates folder
ie., sites/all/themes/your_theme/templates/
Make the changes in new maintenance template file.
Clear the Drupal cache - configuration > performance > clear all caches

Note:

If you want how to Put Drupal 7 in Maintenance Mode, you can go through this link
To bring the site back online

The user who has permission to access the site during maintenance mode can
able to login using login page
Go to admin/config/development/maintenance and uncheck Put site into maintenance mode and save it.


What happens when you choose a default country during installation?

In drupal core this is only used for date and time formats. If you leave it empty you can set it later in the admin menu:

/admin/config/regional/settings


Is there a CCK fieldtype that would display a static field?

If I understand correctly, you don't need an input element at all. In this scenario, you can use hook_form_alter() or hook_form_FORM_ID_alter() in a custom module of site specific customizations to add a form element of type 'item':

$form['my_form_component'] = array(
  '#type' => 'item',
  '#title' => t('My Label'),
  '#markup' => t('This text follows the label'),
  '#description' => t('An optional description appearing below the markup'),
);

See the Forms API Reference for more details.

Edit: If you're not interested in custom modifications, the Markup module seems to provide this kind of utility in a contributed module for D6


default value when adding new item of date field

Try something like this:

//this hook or general hook_field_widget_form_alter
function hook_field_widget_date_popup_form_alter(&$element, $form_state, &$context){

  //only when field is specific name and during node creation form
  if ($element['#field_name'] == 'field_date' && !isset($element['#entity']->nid)) {

    //if default value is not set, only for second and later elements, when first item value is set
    if (!is_array($element['#default_value']) && $element['#delta'] > 0 && isset($form_state['values']['field_date']['und'][$element['#delta']-1]['value'])) {

      //set value
      $element['#default_value'] = array(
        //advance by 24 hours
        'value' => $form_state['values']['field_date']['und'][$element['#delta']-1]['value'] + 24 * 3600,
        //same timezone
        'timezone' => $form_state['values']['field_date']['und'][$element['#delta']-1]['timezone'],
        'timezone_db' => 'UTC',
        'date_type' => 'datestamp',
      );

      //if second value (date to) is set (by comparing value and value2)
      if ($form_state['values']['field_date']['und'][$element['#delta']-1]['value2'] != $form_state['values']['field_date']['und'][$element['#delta']-1]['value'])
        //set and advance second value by 24 hours also
        $element['#default_value']['value2'] = $form_state['values']['field_date']['und'][$element['#delta']-1]['value2'] + 24 * 3600;

      //#date_items needs to be same as #default_value
      $element['#date_items'] = $element['#default_value'];
    }
  }
}


How to configure fivestar's star set in Drupal 7?

Having used FiveStar with Drupal 6 and knowing where the configuration is I've had a look at FiveStar on D7 and I would suggest that because it is still Alpha the team hasn't got to moving the new features across yet as I could not find the required config either.

EDIT: I tell a lie. You can configure the star set, and as an improvement you can do it per fivestar field (i.e. you could have two ratings against a node that have different star sets). To do this go to "Manage Display" of the content type that contains your fivestar field. At the right of the field there will be a "gear" icon. Clicking on this will bring up options including the star set to use.


try to use rewrite field option on your Views to rewrite content link as absolute URL or try using node/[nid] format on the href


Change user profile image on profile page to activate colorbox


if Inherit exposed filters and Inherit contextual filters in Attachment settings is set to Yes then it will inherit filters and it's values


Drupal 8 correspondence to node_access function on Drupal 7

You want Node::access():

if ($node->access('view', \Drupal::currentUser())) {
  // User is allowed to view the node.
}


My website suddenly started giving Error 200 on anything AJAX related!

You've made a change somewhere that is adding <?php to the beginning of all responses.

In "When editing a View" above, you can see this <?php at the beginning of the response text.  Everything after the <?php is valid JSON and so likely the valid response.

I looked at your home page at http://www.spiritmolecule.com and it also has <?php added to the beginning of the HTML source.  This causes the <STYLE> tag to be ignored. <?php<STYLE TYPE="text/css"> gets interpreted as a single unrecognizable tag and so the CSS statement afterwards is displayed as text on the browser.

HTTP=200 normally means OK (no errors) which makes sense since it was able to respond, just it has the junk <?php in front.  Of course, in a file processed by PHP, <?php means the file is about to start some PHP code instead of HTML/JSON markup.  Did <?php get added to a file NOT processed by PHP (and so <?php is passed thru as response text)?

Only you can know what you did to get <?php added to the beginning of all responses, HTML or JSON.  Do you recall any other files that you changed before going to sleep?  Since the <?php gets added to many (or all?) responses, it is likely in a common file.

Good luck troubleshooting!


How to change or update select list of field which is already filled with values

That's quite a daunting task - in order to keep consistency of existing values already stored in your database you can either change all of the nodes containing the value you want to change or add a new option to the select-field.

Changing a lot of options at once could be done by a views-bulk-operation and the operator Change value (not sure, if it's called this way - but it exists ;)).

If i run in such a situation i often write an update_hook to change all values of the field in the db (do not forget to change revision table also) and change the select values afterwards.


Use static function as operations with batch API

The function that Drupal uses to process the batch operation is _batch_process(), which uses the following code to call the operation callback.

  // Build the 'context' array and execute the function call.
  $batch_context = array(
    'sandbox'  => &$current_set['sandbox'],
    'results'  => &$current_set['results'],
    'finished' => &$finished,
    'message'  => &$task_message,
  );
  call_user_func_array($callback, array_merge($args, array(&$batch_context)));

Since call_user_func_array() allows to use a string like MyClass::myMethod as callback, the code you wrote should work, if the Drupal autoloading system is able to find the file containing the class definition, which means:

You need to respect the file structure as per the PSR4 structure expected by Drupal
You need to fully qualify the class name by adding its namespace

In the case the file containing the class it is not in the directory where Drupal looks for class files, such as in the case the class is contained in a my_operation_callbacks.inc put in the same directory containing the module file, then you need to use code similar to the example code shown in Batch operations.

$batch = array(
  'title' => t('Exporting'),
  'operations' => array(
    array('my_function_1', array($account->id(), 'story')),
    array('my_function_2', array()),
  ),
  'finished' => 'my_finished_callback',
  'file' => 'path_to_file_containing_myfunctions',
);

$batch['file'] in that code tells Drupal which file it needs to load before executing the operation callbacks.
Even in this case, the class must be referenced using its namespace, which could simply be \ in the case the class is put in the global namespace.


How can I keep paragraphs of text in one cell when i import data from a CSV file without it making it all one big paragraph?

If your CSV file is saved with new line characters then I expect it is also saved that way into the database. You can check this if you have access to the database. But you can also check this more or less on the Edit page of some of the content that has been imported.
Drupal uses Text formats to display the text. This means it can change what is being served from the database.
Check which Text format is being used on that field and then check the configuration for that format. You can check which Text format is being used on the Edit page, right below the text area element.
"Losing" new line characters can happen if you don't have a Convert line breaks into HTML (i.e.
 and
) option turned on on the format that you apply to your field.
Try using that option on the Text format of the content you've imported, or maybe you have the "Plain text" format, since you're importing content, but make sure that this format has the option Convert line breaks into HTML (i.e.
 and
) enabled.
You can find Text formats under Configuration > Content authoring > Text formats and editors.
Just make sure you don't save the node with a Text format chosen that doesn't have that option enabled (you will see all the paragraphs lumped together), because saving the node will override what is written in the database. Don't save if it doesn't look good, and try to find which Text format makes it look good, it will probably be the one that has the mentioned option enabled ;)


How do I display a "Thank You" message after submitting a Webform 3.x form?

From the webform node, click the Webform tab, then the Form Settings sub-tab. There should be a large textarea labeled "Confirmation message".

If you are on node 1, the URL would be example.com/node/1/webform/configure.


How to organize the features export modules

What we usually do, is create Features based on Content Type, and group everything related in there.

So a Content Type News, would be put in a Feature 'MyProject_News'. Together with everthing that is relevant, like Views related to News, pathauto pattern, specific image styles only in use by News content, etc ..
Usually, we also have another Base or General Feature, containing more generic stuff like text format settings, site settings, .. and also our roles. This Base/General Feature, is a dependency in all other Features.

Others split it up differently, with a Feature containing all the Content Types, another to hold all Image Styles, another one for Contexts, etc ..

In the end, it's all up to you. You can organize it any way you wish.
However I do choose the first method, as in my opinion, a Feature should be able to operate on it's own, or being disabled, without messing up anything in the site.


You are printing the node value directly, which is bypassing the field formatter and other things (since you are not using the render array).

Do this instead:

{{ content.field_date }}

This will render normally and ensure field formatter settings are respected.


How to fully localize popup calendar field

Well I'm a bit ashamed :( No need to do such complicated things. In the edit field page, there are some advanced settings and values I had never paid attention to :

Date entry options : control the order and format of the options users see.

Default date : Relative default value (Describe a time by reference to the current day, like '+90 days' (90 days from the day the field is created) or '+1 Saturday' (the next Saturday). See strtotime for more details.


Generating internal URL/redirect by path>

drupal_goto is removed in favor of RedirectResponse (record).

  As of Drupal 8 drupal_goto() has been removed in favor of
  RedirectResponse which comes together with the Symfony HttpFoundation.

  hook_drupal_goto_alter() was also removed as well, in favor of just
  using an event listener on kernel.response

Drupal 7

<?php
function my_menu_callback_foo() {
  //....
  drupal_goto('user');
}
?>

Drupal 8 (procedural)

<?php
function my_menu_callback_foo() {
  $url = Url::createFromPath('node/1');
  return new RedirectResponse($url->toString());
 //Or try this:
 return new RedirectResponse('node/1');
}
?>


PHP Parse error: syntax error, unexpected T_FUNCTION in redhen_activity.module on line 608

I think you're using PHP 5.2 or earlier, which doesn't support closures. You can find out which version of PHP you're using  phpinfo().

Lindly upgrade to PHP 5.3+, or use create_function, or write a static function and pass it as a callback.


Okay, found out it works when just applying one draggable view and sort a list of all nodes.
if the taxonomy tags are allready in the right order and are under another, the grouping will be sorted by the order of the nodes...

this is sufficient for me, but maybe someone has a better solution?


Add an empty space -

<i class="fa fa-drupal">&nbsp;</i>


You can preprocess a new variable and use views_embed_view like:

$variables['my_view'] = views_embed_view('view_id', 'display_id');

So in your case:

$variables['my_view'] = views_embed_view('comments_recent', 'block_1');

And then in the twig file:

{{ my_view }}

See views_embed_view. It can also take arguments.


Views exposed taxonomy filter - show only terms within results

Have a look at views_hacks. Specifically refer to Views Selective Exposed Filters (views_filters_selective)


How do I delete all terms from a vocabulary (bulk delete)?

A favorite method of bulk-deleting content by content type, taxonomy vocabulary, etc utilizes the http://drupal.org/project/devel module. For deleting all terms in a vocabulary:

Enable the Devel and Devel Generate modules
Go to Development > Generate Terms
Select the Vocabulary from which you wish to delete terms
Enter "0" for number of Terms to generate
Check "Delete existing terms before generating new ones"
Click Submit

Voila-- empty vocabulary, otherwise untouched.


How do I restrict a content type to a subset of vocabulary?

I think http://drupal.org/project/term_reference_tree together with views will handle this for you. You will need to set up different views for each content type and then use term_reference_tree together with that view on each content type. As quoted from the module:

  If you want to filter by a view, make sure the view includes the
  taxonomy term ID, and that the items per page is set to unlimited, as
  the widget will only display the items from the first page of results.

Summarised module usage for reference:

Create a view to filter for the terms you want.

Choose Taxonomy for the content, and work on the Master display (not Page or Block)
Add the Name field
Add the Taxonomy term: Term ID field BUT check the "exclude from display" option.
Turn off the pager
For this specific case, add relationship: Parent term; create OR group in filter: (vocab=tags && (parent.tid={Apples's tid} || tid={Apples's tid}). This gives the Apples term itself and all its child terms.
Possibly needed if view does not work for non-admin users: change the  Disable SQL Rewriting option under Query settings, but beware that means there is zero access checks on your view.

Apply the view to the Term Reference field.

Go to the content type fields page.
On the Term Reference field in question, click the Edit link at the end of the row. You can now see the "Filter by view" option.  (If not, your view is wrong). Choose your view and save these options.
Now click the link to change the widget: choose Term Reference Tree.


view 3: filter for datetime field is not working

Try this handler views_handler_field_date, then uninstall and reinstall the module and try. Otherwise your changes will not affect.


Why are JavaScript files read from an external URL?

You're confusing the attributes on that tag.

class="js" is a class name, it has nothing to do with loading javascript from external sources. It's simply added to the tag by javascript when the page loads so that any process (css usually) that needs to know about it can easily tell whether javascript is enabled or not.
The xml:* attributes are required to identify the document as XHTML. They're not related to javascript in any way.

There's no need to change anything, unless you want to get a bit more up-to-date and install a theme that produces an HTML5 document.


Not sure whether or not this will actually fix your issue, but I'd try:

update the drupal/core version to in composer.json to be ^8.7.0
if you're using webflo/drupal-core-require-dev, update that to ^8.7.0 as per https://www.drupal.org/docs/8/update/update-core-via-composer
run composer update drupal/core webflo/drupal-core-require-dev --with-dependencies
run your database updates, drush updb or site.com/update.php

If that still doesn't work, try:

deleting your vendor directory, core directory, and composer.lock
run composer install


Populate a multivalue image field when importing xml data with Feeds

For Multi-Valued field you could use Explode Plugin in feeds Tamper
Also Use Trim Plugin to Remove white spaces if any in Image URL.
Reference: Feeds Example


You do not need a link field for that. You can generate link at theme level for example. Or even better in hook_node_view:

  The module may add elements to $node->content prior to rendering. This hook will be called after hook_view(). The structure of $node->content is a renderable array as expected by drupal_render().

Last but not least, if you really want it to be a field, use Computed Field and have it calculated at save.

  Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it.


How to disable automatically generated comments in node, but enable programmatically created comments?

Configure comments to be show in separate page, and you'll be able to show them with your view. Also, you've to hide the comment link if you do it.


Check the settings in the nodewords (or another meta tags) module look for noindex


How to update custom paragaph which is added to User Profile?

Don't save the paragraph, add it to the user field and then save it together with the user:

$paragraph = Paragraph::create([
  'type' => 'mmodule_paragraph',
  'field_employee_id' => 'Field value',
  'field_location' => 'Field value',
  'field_name' => 'Field value',
  'field_segment' => 'Field value',
]);
$user->field_paragraph[] = $paragraph;
$user->save();

In case you want to replace the field content overwrite the entire field array:

$user->field_paragraph = [['entity' => $paragraph]];


Display categories in views to get chosen and to display specific tags

Yes, You can able to list taxonomy terms of specific vocabulary using views.

You need to create a custom block and a view for this..

A custom block, Which lists all vocabularies .. Views doesn't support vocabulary listing..
Two, A view which lists specific vocabulary terms. You need to pass vocabulary id to this view in an URL and read it using contextual filters to filter the terms by category.

You can get list of vocabularies using below api function..

taxonomy_get_vocabularies

Link the vocabularies terms to some path like category/list-terms/{vid} .. make category/list-terms/% as your view path and read the argument using contextual filter vocabulary id to list terms..


hook_theme() is a hook that must returns the list of theme functions implemented by a module, or a theme.

Calling drupal_add_library() or drupal_add_js() inside hook_theme() is not the way to add a JavaScript file to a page.

As reported in Structure of the .info file, a theme can use the scripts directive to declare the JavaScript files that it uses.

scripts[] = js/custom.js

Alternatively, a theme can use drupal_add_js() inside a theme function, or use the following snipped inside page.tpl.php, or any alternative page template Drupal would use.

drupal_add_js($path_to_script);
$scripts = drupal_get_js();


I assume you want to add this image for each view row?

Then you would need to add "Global: Custom text" as a new field, and put your image HTML into it.


Storing data / session for anonymous user

Late answering, but it's worth mentioning that you can use private tempstore for anonymous users, as long as the tempstore has access to an active session. To do so, you need to inject your class with services for the temp store, session, and current user, like so:

public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user) {
    $this->tempStoreFactory = $temp_store_factory;
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;

    $this->store = $this->tempStoreFactory->get('myclass.storename');
}

public static function create(ContainerInterface $container) {
    return new static(
        $container->get('user.private_tempstore'),
        $container->get('session_manager'),
        $container->get('current_user')
    );
}

Then you just need to ensure you start the session manager if the user is anonymous, before you need to put anything in the temp store:

if ($this->currentUser->isAnonymous() && !isset($_SESSION['session_started'])) {
    $_SESSION['session_started'] = true;
    $this->sessionManager->start();
}

You might find this approach preferable because it means that you can use a single system for temporary storage, regardless of whether a user is logged in.

(My code examples are lifted more-or-less verbatim from this excellent tutorial on building multi-step forms.)


Is it possible to assign an anonymous user's flags to a new user on registration?

I am not aware of any module that already does this with flags. But you can take a look at Anonymous publishing. Its "Lazy Registration" mode will assign any node created by the anonymous user to a newly created user if that anonymous user later registers an account.

The method used is to require the anonymous user to submit and confirm an email address when creating a node. When somebody with that email register, the nodes tagged with that email address can be assigned to that newly created user.

It should not be difficult to use the same method to assign for flags/requests created by the anonymous user to a newly created user.

If you can allow for some errors, you can use something less intrusive than a confirmed email address to link the anonymous user to the newly created user, such as a persistent cookie (will fail when the cookie expires or the user moves to a different computer), or an IP-address (will fail if the user moves to a different computer, if two different users users use the same computer, or if a dynamic IP-address gets reassigned.)


The Better Exposed Filters module integrates with the date type fields, including the date popup. You can use this module to easily add an exposed filter with the date popup.

There are some known issues with BEF's integration with the date module; from the module page:

  (Note: Support for fields supplied by the Date module is a little funky until #392836: Exposed Date filter format (in Views) and/or #502824: Date format in exposed filter (views) are resolved).

Also, you can only add this type of filter to entity fields at the moment, not properties. There are various discussions going on about this.


How can I add a class with table theme function to a table header row?

If your current example works I'm assuming you are on drupal 6.

You can add attributes to the header array like this:

$section = array(
  '#theme' => 'table',
  '#header' => array(
    array('data' => 'foo', 'class' => 'cell-class'),
    array('data' => 'bar', 'class' => 'cell-class'),
    'class' => 'row-class',
  ),
  '#rows' => $rows,
),


Why does composer not work with core composer.json file when adding new libraries?

Hope it helps someone else. The issue was that I only updated drupal's /core folder, not composer.json. So I had a very old composer file. When I updated it with the composer.json from the latest D8 download, things started working again.


This wouldn't delete just the field, it would delete the row for a user whose uid equals $account->uid. The ->expression() and subsequent ->execute() as @kiamlaluno points out, wouldn't work right anyway.

If you want to simply delete the value, you are better off doing something like this:

// $account is defined up ^^ there somewhere.
$account->url_time = '';
user_save($account);


May not be the answer you're looking for but have you considered Advanced CSS/JS Aggregation as one of the features is "Prevent more than 4095 CSS selectors in an aggregated CSS file (IE 6-9 limitation)"


How to create a 3rd Ad push in a custom Omega Kickstart subtheme

Go to Site settings->Visual & Layout -> Views. You will see the View for Ad push blocks. Click on Edit for this View. Clone the Second ad push block. Be sure to:

change the name to Third ad push block
set the Pager to 1 item, skip 2
save changes

Go to Site settings->Visual & Layout -> Blocks and add the Third ad push block to the Postscript Third Region and click Save blocks.

Reload your page and the block should be visible on the front page.


How to save file uploaded with plupload integration module, and make it managed?

I didn't really checked all links in this email but I have used Plupload very extensively and worked very well.

<?php

  $form['upload'] = array(
    '#type' => 'plupload',
    '#title' => '',
    '#description' => t('Maximum file size allowed: 10MB'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('zip rar 7z odt doc docx xls xlsx png jpg pdf rtf txt'),
    ),
    '#plupload_settings' => array(
        'runtimes' => 'html5,flash', // Also consider the order of technologies.
        'chunk_size' => '10mb',
        'unique_names' => TRUE,
        'flash_swf_url' => file_create_url(_plupload_library_path() . '/js/plupload.flash.swf'),
      ),
    );

  return $form;

  // Submit handler:
  //function ..._submit($form, &$form_state) {
  if (!empty($form_state['values']['upload'])) {
    $form_state['uploaded_files'] = quotes_file_save_files($form_state['values']['upload']);
  }

  // }

function quotes_file_save_files($files) {
  $saved_files = array();
  $scheme = 'private://'; // Change to "public://" if you want to move to public files folder.
  foreach ($files as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      // Check the $file object to see if all necessary properties are set. Otherwise, use file_load($file->fid) to populate all of them.
      // $file = file_load($file->fid);
      $saved_files[] = $file;
    }
  }

  return $saved_files;
}

?>

I think the point is, plupload does not save the files to the managed files folder by default, but populates all the data in the $form_state array for you to process and save.

Edit: In relation to the other answer that mentions file object's status should be permanent. I'm sure you already know that the status must be 1. But plupload_file_uri_to_object function sets the $file object's status to 1, so it's not done in the example.

Good luck!


You are more likely to get an answer in the RDF Extensions issue queue on drupa.org. see this comment as an answer to your question: http://drupal.org/node/1296820#comment-5068706


Translated terms are not searchable with Search API

I think that this is core issue that the search index does not add the localized term to the index, I solved that by implementing hook_node_update_index($node) and fetching the localized term name by querying it from database because I don't know why i18n_taxonomy_localize_terms function doesn't load the term properly. my code is below:

function mymodule_node_update_index($node) {
  $text = '';
  $tid = key($node->your_taxonomy['und'][0]['tid']);
  if($tid != 0) {
    $query = db_select('locales_target', 'lt');
    $query->addExpression('CONVERT(translation USING UTF8)', 'translation');
    $query->join('locales_source', 'ls', 'ls.lid = lt.lid');
    $query->condition('context', 'term:'.$tid.':name');
   $text = $query->execute()->fetchColumn();
  }

  return $text;
}

Note: in my case the text is Arabic so I converted the field character set from blob to utf8.


How do you prevent twig variable from last instance of template overriding those that go before it?

$render_controller->view() invokes hook_ENTITY_TYPE_view() and this would be a better place to add custom values to the entity view.

Although probably not good practice you could get your approach working by cloning the entity before modifying the field values:

$entity = clone $entity;

In any case you need to adjust caching so that you store for each variant a different cache item in the render cache. For example by adding cache keys to the build array before returning it:

$build = $render_controller->view($entity, $view_mode);
if (isset($entity->foo)) {
  $build['#cache']['keys'][] = $entity->foo;
}
return $build;


Drupal views print date 'time ago' as a PHP conditional field

In User Last access field UI, under the Date Format, select 'Custom' and then enter custom date format. For minutes you can enter 'i' which will show the number.

Refer http://php.net/manual/en/function.date.php for date formats.

Thanks


File upload disappears in Web File Manager

This is a critical bug of Web File Manager module that sates "files are being deleted while browsing WebFM with Chrome" (Considering that you have been using chrome to upload files your Web File Maanger)
For more reference please refer to this.


You should create a content type Locations

and add the following as form fields
1.cities
2.states(Provinces)
3.countries

Use two modules

Entity Reference

Use a field entity reference in your custom form for origin and destination with content type locations
Tokens  3. Auto nodetitle
By installing the tokens and auto node title you can set the title for locations as per your needs
like [field:cities]|[field:province]|[field:country] in the edit link of content type locations

the title u set for the content type will be used in the origin and destination field . You can set your field as autocomplete as well as follows:

function module_name_menu() {
  $items['location/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('access location autocomplete'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function module_name_form() {
  $form = array();

  $form['origin'] = array(
    '#title' => t('origin'),
    '#type' => 'textfield',
    '#autocomplete_path' => 'location/autocomplete',
   );

  $form['destination'] = array(
    '#title' => t('destination'),
    '#type' => 'textfield',
    '#autocomplete_path' => 'location/autocomplete',
   );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
  );

  return $form;
}

function _module_name_autocomplete($string) {
  $matches = array();

  $query = db_select('locations', 'loc');
     ->fields('loc', array('title'))
    ->condition('c.title', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->title] = check_plain($row->title);
  }

  // return for JS
  drupal_json_output($matches);
}


How to use conditions on a REPLACE expression?

The problem with the code above is the apostrophes around the placeholder.

LIKE \':value\'', should be LIKE :value',.

I would still like to know how to do this with addExpression though :-/


This feature already there with flags module.

Please check in your flags settings page.


How do I use the value of a webform_field as the default-value for a later webform_field?

The short answer is 'No' to using tokens to sync two element values, unless the two elements are on different pages. The simplest solution is a write a little JavaScript to sync the nickname with the username.

You can search for examples of sync'ing two input fields.

The Webform module's Options admin widget uses a little JS to sync an option's value with the option's text. @see webform.element.options.admin.js


Create one content views for block
Relationship > Taxonomy term: Content with term
aggregation setting yes
use count on aggregation setting for the field.

There are other options available over here.
https://www.youtube.com/watch?v=w22Utjm-chs


How to edit the People (users admin view) to include filter by user name?

You can take a look at the Administration Views Module:

  Replaces administrative overview/listing pages with actual views for
  superior usability.

  Features

  Filter all administrative views via AJAX.
  Perform any kind of bulk/mass operations on items in administrative views.
  Filter content by title, node type, author, published status, and/or vocabulary.
  Filter comments by title, author, node title, or published status.
  Filter users by name, ban/blocked status, or user roles.

  *Note: If you are upgrading from an older version of Administration views and the default views have been overridden (saved in the
  database) you could encounter issues or not see any new changes unless
  you revert these views, so the default in-code views are used. This
  can be done in the views UI listing or using drush (drush cter
  views_view --module=admin_views)

By default it has a specific users view, but since it is a view, you can modify it.


Ongoing email alerts for content "assigned" to users via Entity Reference

http://nodeone.se/en/learn-the-rules-framework
Check out episodes 2 and 3 in particular. Then watch the rest of the series. Then watch all the other series. Then rejoice that Johan Falk is so freakin' awesome.


Is your administration theme the active theme when the Rule fires? This documentation page about using a custom mail template with Mime Mail might be referencing the issue:

  If you use sub-themes or multiple themes, especially if you use a different administration theme than your default theme, you might end up with a different theme to what you expect.

In the Mail System module configuration settings (admin/config/system/mailsystem), try changing the Theme to render the emails from Current to the Default theme or to the theme where your overridden mimemail-message.tpl.php lives.


Managing multiple versions of files on nodes

You could try either Revision All

  Revision All allows for centralized management of content type
  revisioning. Revisioning can be turned on/off individually by type or
  enabled for all simultaneously. There is also support for enabling
  automatic revisioning of future content types and the disabling of the
  "create new revision" checkbox on node and/or content type forms.

or Document modules

  A Document Management System for Drupal.

Features:

Complete integration with Drupal node system. This module adds a custom Node Type, Document. Each Document you create is a Drupal node, and hence enjoys all features available to a node.
Support for Document revisions/versioning - This module allows you to maintain multiple versions/revisions of the same document.
Views 2 Integration - The custom fields added by the module to the Document node type are accessible in Views, plus the module provides some useful out-of-the box Views.
Theming support
Searching - The documents being nodes are fully indexable by the Drupal search system. In addition, the module provides its own custom search for Documents.
A couple of blocks are available for document search that can be placed flexibly in your theme layout.


Avoid duplicate ID for a field that appears multiple times on the same form

Drupal has a helper function for that:

drupal_html_id():

  Prepares a string for use as a valid HTML ID and guarantees uniqueness.


How to restrict what content types can be added to a Book?

The answer seems to be within the permissions. For books there are a few main permissions (plus others in the Node section):

Administer book outlines
Create new books
Add content and child pages to books

Removing the 'Administer book outlines' will allow roles who have the other two permissions to create book pages but not see the option to add other content type nodes into a book. This is exactly what I was looking for.


How to grant userpoints only for modifying nodes last changed at least 20 days ago?

Sorry to say, but the previous answer has some challenges:

Rules Event After saving new content is not the right event.
I disagree with the "You will need a custom module ...", since there is an out-of-the-Rules-box Rules Condition you can use ... Read on for more details on that.

Here is a rule (in Rules Export format) that does what you're asking for:

{ "rules_grant_userpoints_after_updating_old_content" : {
    "LABEL" : "Grant userpoints after updating old content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "userpoints_rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "node-unchanged:changed" ],
          "op" : "\u003C",
          "value" : "-20 days"
        }
      }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "site:current-user" ],
          "points" : "123",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Modify existing node (nid=[node:nid]) that was not updated in the last 20 days.",
          "operation" : "Grant points",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Some more details about the above rule:

Rules Event: After updating existing content (you may want to limit it to selected content types only).
Rules Condition: Token [node-unchanged:changed] is at least from 20 days ago.
Rules Actions:

Grant 123 user points (adapt the number and the other options as you want).
Load the current userpoints balance.
Display a message with the current userpoints balance.

If you have the Rules UI enabled (and the Userpoints Rules module, you should be able to just import the above rule in your own site.

PS: After you're convinced the rule works as you want, you may want to remove the last 2 Rules Actions about the message shown to the user after user points were granted.


To show only the output of the callback, and not the complete page Drupal would render, output the HTML using print or echo; if you return the HTML output as string, Drupal will render the normal Drupal page, which includes the HTML your callback returns.

The code contained in index.php that causes this behavior is the following one:

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_set_header() is used from drupal_json() to change the content type of the output (the "Content-Type" metadata); normally Drupal will set it to "text/html" which is not appropriate for what returned from a callback returning JSON; in that case, the content type that allows the requester to handle the output correctly is "text/javascript."


How to remove the default  tags generated by modifying manage display?

It seems you are missing the  Display Suite Extras submodule (ds_extras)?
You can change the default field templates easily there.
From DS Extras doc:

Default Field Template

Default: will output the field as defined in Drupal Core.
Reset: will strip all HTML.
Minimal: adds a simple wrapper around the field.
Expert Field Template: gives full control over the
HTML, but can only be set per field.

You can override this setting per field on the "Manage display"
screens or when creating fields on the instance level.

admin/structure/ds/list/extras:

Once the Extras submodule activated you will have control by fields. visit the CT "manage display" page and the main CT page (edit). Mode "Minimal" or "Expert" seems what you need.


nodes in views and views in search results

Take a look at Rabbit Hole ( https://www.drupal.org/project/rabbit_hole ) , it has several options as to what has to happen when a Node is viewed ( or trying to get viewed ) directly.


This is a solution I found, but it isn't really handy to use... I really want a better solution, like something directly from twig templates.

function template_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if ($element['#name'] == 'field_c_button_link') {
    $variables['items'][0]['content']['#options']['attributes']['class'][] = 'button';
  }
}


One taxonomy term in multiple vocabularies

Well you could combine them in a single vocabulary and then your term can have two parents:

Properties
-Properties for sale
--Apartment
--House
--Land
-Properties for rent
--Apartment
--summer house
--Room


No you can not ignore the "sid" from submission confirmation page.

Yes you can create a separate thank you page and redirect to that page.

You can install this modules:

->     rules

->     webform rules

Now add a rule that redirects the user to your URL after a webform submission.

Using hook_form_alter(), and set the override there.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
     $form['#submit'][] = 'my_submit_handler';
  }
}

function my_submit_handler(&$form, &$form_state) {
  $form_state['redirect'] = 'home';
}

Refer Redirect Drupal Webform Submissions


The problem is the lack of a return value in facebook_main_contents(); As you can see in the api documentation $block['content'] should contain either a Drupal render array or fully rendered html. facebook_main_contents(); is not actually returning anything but instead echoing output to the page.

You need to collect your rendered html and return it, like so:

$content = "
";
// check if post type is a link
if ($post['type'] == 'link') {
  $content .= "
" . $post['message'] . "
";
  $content .= "
";
  $content .= "

";
  $content .= "
" . $post['name'] . "
";
  $content .= "
";
  $content .= "
Posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "
";
}
...

return $content;


Scan Remote FTP server (Akamai) for files, use filename to create content

How about feeds?

(Sorry this would/should be a comment but I don't have enough rep yet)


How to display product attribute as filter in product listing page?

bit late for the answer perhaps, but perhaps someone else finds it usefull.

Ubercart uses 'Attributes' and 'Options'. Filters uses 'Taxonomies' and 'Terms'. Menu modules like taxonomy filter, hierarchical select use the terms. There is no connection of these two as far as i know.

To use these filters, we have terms synchronized with options. So for every option there is a term as well. On the product edit screen, we have enabled the taxonomies corresponding to the product attributes. So on the product edit screen you can manually add terms for taxonomies. We set these tags automatically when we import the options data through a csv or cash-register connection. (And set options based on received term data as well.)

When you have this solved there is issue 2. Options without stock should (often) not be shown in menu options.

So when f.i. Shirts->Red-Size XL has Size XL out of stock, then term XL should no longer be visible in the filters (when this is the only product). We made small adjustment to 'order-invoice' trigger where stock is reduced, to also check and remove terms where needed.

For handling this automatically and with a nice user interface I created a custom module.


Using the hook_form_FORM_ID_alter format is ideal:

function MODULENAME_form_CONTENTTYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_agent_name']['#access'] = FALSE;
}

More info on hook_form_FORM_ID_alter


Why does file_validate_extensions fail to validate?

$form['#attributes']['enctype'] = 'multipart/form-data';
$form['survey']['file-upload'] = array(
  '#type' => 'file',
  '#prefix' => '
',
  '#suffix' => '

',
  '#description' => 'Image type PNG/JPG Max Size:2Mb.',
);

function create_survey_form_validate($form, &$form_state){
$save = file_save_upload('file-upload', array('file_validate_extensions' => array("jpg png")),"public://user_sheets",FILE_EXISTS_RENAME);
  if($save == null){
    form_set_error('file_upload', 'Please select a file');
  }
  else if($save == FALSE){
   form_set_error('file_upload', 'Error in file upload');
  }
}


Views Filter 2 Content types but with condition on one of them

Although this post is quite old, it appears it's still an issue going up to Views 7.x-3.7. Referring to the post already mentioned here and specifically comment 36 on that page, I found my working solution.

I had two content types that I wanted to show the title from: an Event and a Blog, however I only wanted the blog posts which had a Boolean field returning as true.  Below is a screenshot of what my grouping filters look like but the trick is, on the Boolean filter, make sure you select the 'Reduce duplicates' check-box. Once I did that, I got the results I was expecting.

Hope that helps.


Get content types field in another content type with the entity reference relationship

With Entity Reference Autofill You can achieve something like you specified.

    The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


Best practice: Twig template for custom module's block

I would prefer option 1. Theme the inside of a block in a custom template with custom variables or build a render array with render elements. Use the block template only to theme the outside of the block, for example add a wrapper div.

Option 2 is not a good idea, because it uses this block template:

{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ var }}
{% endblock %}

Normally a block template looks like this:

{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ content }}
{% endblock %}

By ignoring {{ content }} in a block template no cache metadata can bubble up. See https://www.previousnext.com.au/blog/ensuring-drupal-8-block-cache-tags-bubble-page

You could try to add the cache metadata with block methods. But this is not good practice, because if later someone tries to add block content and is not aware of that the block template doesn't use the base hook variables this person will have a hard time debugging this.


Module file:
Hook name is source_entity_info()  insted of source_entity_entity_info()

    <?php

    function source_entity_entity_info() {
      $info = array(
        'source_entity' => array(
          'label' => t('Source Entity 1'),
          'base table' => 'source_entity',
          'entity keys' => array(
            'id' => 'teid',
          ),
        ),
      );
      return $info;

}


How can I retrieve a user name and password?

Drupal does not store passwords, but rather password hashes. There is no way to recover the password. You can use Drush to either set a new password or generate a one-time log-in link:

Reset PW: drush upwd <username> --password="<password>"
One-time login-in link: drush uli <username>


How to add Drupal Coupon discount for selected category or item only?

You you can do it by adding new RULES. If you are using Percentage Coupon then you must have a rule in the list of rules list named "Calculate coupon with percentage amount".

Clone this rule & add more conditions according to your need like "Order contains products of particular product types" or "Order contains a particular product".

Its totally upto you to use conditional based discount and disable the default coupon redeem rules.


drupal #default_value not working for #type radios

A radio group can only have one radio selected. Did you try '1' as default value?


Drupal Commerce Free Shipping For Some Products

In such a simple scenario, where you only have two products, I would just use the condition Order contains a particular product to look for the shippable product to enable the paid shipping service. I'd then use the same condition negated to enable the free shipping service.


There are two modules that you could use, the 'Database Administration' and 'Views Excel Export' These are still in alpha and dev for drupal 7 but might worth a try.


want to ask if there is a way that I can display a field from another content type to a field of another content type

You can use the entity reference module for accomplishing your requirements.

On the "Courses" content type you will add a field type entity reference which refer to the "Course Schedules" content type.

Then in the "Courses" content type Manage Display, You can choose that the referred node link to appear, I think you can also choose that the rendered node to appear.


Persistent session cookies: remember session even after closing the browser

Hi you could use javascript for this.

Using these 3 functions.
its properly the best way and then you wont have problems if your are using Varnish

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}


You can configure one of your text formats to use the "Convert URLs into links" filter, then to apply that text format to some text you can use the check_markup() function like this:

// Run text through the Filtered HTML text format.
$formatted_text = check_markup($original_text, 'filtered_html');

You can change 'filtered_html' to be whichever text format you want to apply.
Note that it will run all the other filters of that text format on the text also.


It sounds like there is just a problem with the loading of the attached files in your $form['#attached'] setting. Are you getting 404 errors from your debugger for the js and css files or is it not trying to load them?

You should try rewriting your form settings with the type as a settings array (if you need it) according to the API documentation

$form['#attached'] = array
(
        'css' => array
        (
                $path .'css/test.css' => array('type' => 'file',),
        ),
        'js' => array
        (
                $path .'js/test.js' => array('type' => 'file',),
        ),
);

or maybe more simply as:

$form['#attached']['css'] = array(
  drupal_get_path('module', 'test') . 'css/test.css',
);

$form['#attached']['js'] = array(
  drupal_get_path('module', 'test') . 'js/test.js',
);


You can create a template for your panel and add whatever div or wrapper you need there, by wrapping it around the content div. This post is a great resource:
https://www.drupal.org/node/1678810

In brief, for panel panes, your template file should be named:
panels-pane--[pane type]--[pane subtype].tpl.php

This post also shows you how to find your panel's machine name.

If you aren't familiar with templates, this is also a great resource:
https://www.drupal.org/documentation/theme


Auto add nodes on save to a queue using entityqueue

Try Auto Entityqueue module to Automatically add entities to entityqueues.


Suppressing APC cache warning messages in watchdog log

You can create a module to use the hook_watchdog function. This hook would kick in when there is an error so you can check the type of error decide not to write it to the table. But the variable seems to be passed not as a reference and hence I dont think you would be able to change the variable it self.

The logs are written to the table by the dblog module. using the hook implementation of the dblog module. Just make sure that your function gets called after this so that the entry is already in the db. this should be the case already if not you can set the priority in the systems table to make this effect.

Now within your hook function you can decide to delete the entry that is just written.

function dblog_watchdog(array $log_entry) {
  Database::getConnection('default', 'default')->insert('watchdog')
    ->fields(array(
    'uid' => $log_entry['uid'],
    'type' => substr($log_entry['type'], 0, 64),
    'message' => $log_entry['message'],
    'variables' => serialize($log_entry['variables']),
    'severity' => $log_entry['severity'],
    'link' => substr($log_entry['link'], 0, 255),
    'location' => $log_entry['request_uri'],
    'referer' => $log_entry['referer'],
    'hostname' => substr($log_entry['ip'], 0, 128),
    'timestamp' => $log_entry['timestamp'],
  ))
    ->execute();
}

Another option would to create a hook_cron in your module and delete the wantchdog entries you dont want during the cron run.


Should I stay with Poormanscron or is it worthwhile to set up an external cron?

Unless I'm mistaken. Poormans cron significantly impacts page load performance when cron runs. I only use it on sites I'm quickly working with locally and have no intention of working on in the near future again.
Using crontab to run cron completely removes the detrimental performance of using poormans cron, apart from the subsequent page load having to re-build the necessary caches. Using crontab is the better option, it provides predictable behaviour, is more reliable, and has less of an effect on users.
You may also want to look into using drush to run cron.
As a side note, on the performance tab there is a setting for the 'Minimum cache lifetime' does not only affect the page cache but all caches. If a time is not set there then as far as I know all caches are dumped on each cron run. (There are one or two sensationalist blog posts which appear to say otherwise though, but if you look at the core code they are incorrect.) This is something else which comes into play with cron runs and performance.
Elysia cron: This is more cron on steroids, and is not a replacement for poormans cron, as the Elysia cron documentation suggests, you should have cron running every minute to get the most flexibility with it, which poormans cron is just not capable of.


How to set/display select options in selectbox using form-api

You can make use of theme_table to make a table view.
You can use form-api inside the table as you wish.

Sample code for creating table.

$header = array();
$rows = array();
$rows[] = array(
    array('data' => 'Head1', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head2', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head3', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head4', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head5', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head6', 'colspan'=> 6, 'header' => 1),
);
$rows[] = array(
    array('data' => 'SubHead6-1', 'header' => 1),
    array('data' => 'SubHead6-2', 'header' => 1),
    array('data' => 'SubHead6-3', 'header' => 1),
    array('data' => 'SubHead6-4', 'header' => 1),
    array('data' => 'SubHead6-5', 'header' => 1),
    array('data' => 'SubHead6-6', 'header' => 1),
);

return  $output .= theme('table', $header, $rows);

To make a select box with db values you can try this

$query = "SELECT * FROM {tablemanme}";
$query_result =  db_query($query);
while (($data = db_fetch_object($query_result )) !== FALSE) {
  $opt[$data->id] = $data->name;
}

$form['select'] = array(
    '#type' => 'select',
    '#options' => $opt,
);

Good luck.


How do you check if table is empty before resetting the auto increment?

Important: This is a risky thing to do, particularly on a production site.
It could possibly cause problems with your database so be sure that you know your database schema very well and are fully aware of the implications of doing this.

You already use db_delete() so you seem to be familiar with database interaction.

So you just need to query to check for any values. You could use something like:

SELECT COUNT(*) FROM achievements

and make sure the result is zero, or

SELECT 1 FROM achievements LIMIT 1

and make sure that no rows are returned.

You can use db_query().

Then you can use db_query() again to reset the increment.

For example in mysql it would be:

ALTER TABLE achievements AUTO_INCREMENT = 1

Since it seems you already know drupal db this isn't really a drupal question.
It breaks down into:
How do I check a database table is empty and how do I reset an auto increment field.

In both cases searching google for that will get lots of results, including stack exchange answers or your chosen database's manual pages.


I'm creating a form in a module but when I try to add a radio group the title displays but not the options

Your #options setting only has keys, but no values. You need something like

'#options' = array(0 => t('Closed'), 1 => t('Active'));

Example from Radios form API reference.


How do I add a custom sorting variable to a view?

Have you created a custom theme, or are you using a contrib theme?  If you have created a custom subtheme, then you can override the template for this particular view at the appropriate level (e.g. something like views-view-fields.xxx.yyy.twig) and then you can implement custom logic that tests if that particular field is greater than today's date, and then inject a CSS class, or change the markup, etc.

If are not subtheming or just don't want to go down that road, you can do as you suggested and have a "Featured field".  There is a module called Computed Fields (which helps you create derived fields, essentially) which may facilitate you doing this: https://www.drupal.org/project/computed_field.  I've not tried it myself for your particular use case, but it may be worth exploring.


You could use Views to render a table view of fields (for Country, etc) and set the content filter of that view to pull only submitted webforms.


Bakery: Why do I get the "Logging out the user with the bad cookie"?

As an alternative to Bakery, if your sites are all co-hosted and you're using MySQL, you can get your sites to share user tables as described by Lullabot.

The important parts are the Master site setup:

$db_url = 'mysql://user:pass@localhost/master_database';
$db_prefix = '';

The shared cookie domain (which you already have):

$cookie_domain = '.example.com';

And the slave site setup:

$db_url = 'mysql://user:pass@localhost/slave_database';
$db_prefix = array(
   'default'   => 'name_of_slave_database.',
   'users'     => 'name_of_master_database.',
   'sessions'  => 'name_of_master_database.',
   'role'      => 'name_of_master_database.',
   'authmap'   => 'name_of_master_database.',
);

I have succeeded with this method in the past, though I think I used the normal database array instead of $db_url.


Why would a field be missing from the Rules data selector?

I found the answer in the Commerce documentation:

  This is due to the fact that Rules only knows about the default fields that we tell it should function in a manner similar to entity properties. In order to access additional fields, you have to do one of two things in your conditions:

  Use the Entity has field condition to ensure the field you want to access exists on the variable you want to use it for, or
  Use the Data comparison condition to check the type of the entity (i.e. product type) to gain access to every field on the entity.


you could try using hook_form_alter()

For e.g.

<?php
function your_module_name_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your_form_id'){
    //First element in the form.
     $form['element']['#prefix'] = '
Your paragraph before the form.
'
  }
}
?>


Can we upgrade a site directly to latest version (without an extra fresh site)?

No.

The old method of upgrading Drupal through update.php has been dropped in Drupal 8 in favor of the Migration framework & UI. The idea here is to provide a clean way into a new database schema without any problems of update.php trying to accommodate many diverse scenarios (as it was prone to do with moving complex sites from D5 to D6 & D6 to D7).

D8 has some significant changes to its architecture; trying to patch code & alter the DB schema for a D7 site to move it to D8 could be fraught with problems. It could theoretically be done, but you'd probably spend more time doing that than to just devise a content / custom code migration path.

For more information read Upgrading from Drupal 6 or 7 to Drupal 8 on drupal.org.


Is there any security or operational problems if I do not have any .htaccess file in drupal root?

You may have some problems, depending on how Apache is configured.

People may be able to browse directly to some hidden files.  Look at lines 6 and 73 in the .htaccess to see what it restricts.

People may be able to browse directories directly.  See line 10.

The site may not work right if you accidentally put a file called index.html in the root.  Line 20 makes index.php the primary file.

Clean URLs won't work.  I am not 100% sure if image cache will, either.

There may be some PHP security issue, but the php_flag directives have been standard settings in php.ini for a several years now.

Are you on shared hosting?  If so, the problem with the .htaccess could be the Options lines.  Some hosts restrict these.  Everything else should be feature checked the the <IfModule> directives.

It is possible to not have a .htaccess in the DOCROOT by placing the contents into the Apache config for the site, or in an include.  On high volume sites, there are some performance gains from doing this (.htaccess is read each request, where Apache config is read once when it starts).


Prevent output of control code characters in Views Data Export

Views Data Export enables you to write your own .tpl files for fields. So, in a template for a problematic fields, you might use

preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $input);

to strip all potentially problematic characters. Of course cut list of chars for your specific need and if they are in any way meaningful to your users, consider replacing them with some mark instead of eradicating them entirely. It's a bit clumsy solution, but as far as I remember it works, ant it's fast to get up and running.

You can also use preprocess hook instead of tpl:

/**
 * Implements hook_preprocess_views_view_field().
 */
function mymodule_preprocess_views_view_field(&$vars) {
  if ($vars['view']->name == 'myview' && $vars['view']->plugin_name = 'views_data_export_xml') {
    $vars['output'] = preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $vars['output']);
  }
}


Show block in particular nodes having some string in title

Try:

if (strpos($url, 'myword') !== FALSE) {
  $match = TRUE;
}

strpos() returns the zero-based index of the first occurrence of the substring.

So if "myword" is at the start of the URI string strpos() will return 0, and since 0 == FALSE in terms of a conditional, it will fail.

I've just tested your code and it works fine with the slight change.


What does the rule event mean "Drupal is initializing"

In Drupal 7, the rule will run when hook_init() is called. As explained on the Drupal documentation page for hook_init():

  This hook is run at the beginning of the page request. It is typically
  used to set up global parameters that are needed later in the request.
  When this hook is called, the theme and all modules are already loaded
  in memory.

  This hook is not run on cached pages.

  To add CSS or JS that should be present on all pages, modules should
  not implement this hook, but declare these files in their .info file.


How can update.php be disabled from checking for Postgres databases?

It turns out there were two Postgres directories in includes/database.

includes/database/pgsql/install.inc and includes/database/postgresql/install.inc. The latter was out of date and redundant and may have been installed as part of the requirements for some Feeds SQL Importer. After deleting it the installation now works fine.


Show only specific fields on Edit page when a Term is selected

conditional fields  is very powerful you can achieve your need with it. read README.TXT file carefully


How to execute request-specific tasks after page response is returned. Does hook_exit() actaully do this?

You're looking for fastcgi_finish_request(). Recommend using it inside of a shutdown function. If you need something else the HTTPRL module should be able to do what you need with threading.


I don't know if you found your answer but I had the same problem and found a solution :

In a hook_form_alter

  if ($form_id == 'simplenews_block_form_' . variable_get('simplenews_id', 23)) {
    $form['submit']['#ajax'] = array(
      'callback' => 'simplenews_block_form_ajax_submit',
      'wrapper' => 'block-simplenews-' . variable_get('simplenews_id', 23),
      'method' => 'replace',
      'effect' => 'fade',
      'progress' => array('type' => 'none'),
    );
    $form['submit']['#executes_submit_callback'] = TRUE;
    unset($form['#submit']);
    unset($form['#validate']);
  }

And then in the ajax submit

/**
 * Ajax callback to reload the image field
 */
function simplenews_block_form_ajax_submit($form, $form_state) {
  $return = '
';
  $return .= '
' . t('Newsletter') . '
';
  $return .= render($form);
  $return .= '
';
  if (!valid_email_address($form_state['values']['mail'])) {
    $return .= '
' . t('The e-mail address is not valid.') . '
';
    return $return;
  }
  else {
    if (module_exists('simplenews')) {
      module_load_include('inc', 'simplenews', 'views/simplenews.subscription');
      $tid = $form['#tid'];
      $account = simplenews_load_user_by_mail($form_state['values']['mail']);
      $confirm = simplenews_require_double_opt_in($tid, $account);
      $subscription = simplenews_subscribe_user($form_state['values']['mail'], $tid, $confirm, 'website');
      $return .= '
' . t('You have been subscribed.') . '
';
      return $return;
    }
  }
}

This will do a simple registration to the database in AJAX. You can adapt depending on what you exactly need.


How to place the pager for a view in page.tpl.php?

The following steps might help you to extract the pager out of a view conatiner with a help of small css fix,

1 : Override the view template file
I have created a view called extract pager and created a custom tpl for the same views-view--extract-pagertpl.php

2 : The data-members for pager will be available in the above tpl file copy and place the code into to a sepearte div container

<div class="pager-extract">
  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>
</div>

3 : Rescan the template files in the views and save the view.

4 : The above steps will help you to bring out the pager up to the view content block, use few css styles to theme your pager as per your requirements.


How to grey out fields with non editable permission upon node editing?

Form elements have a disabled property you can set as a boolean. For example:

$form['test'] = array(
  '#type' => 'text',
  '#title' => t('Test'),
  '#required' => FALSE,
  '#default_value' => 0,
  '#disabled' => TRUE,
);

Now, you can use hook_form_alter() to check that you're on the right form ($form_id), and any other conditions you require, like for instance checking user permissions, with the user_access() function.


taxonomy-term at the automatic creation of url alias of a content path

Install Pathauto and Token. Pathauto will let you create automatic aliases, and Token will supply the content's taxonomy term as a substitutable value.


Running code only once when building a form

Use built-in caching!

At the beginning of your function, test if results are already prepared in cache:

function mango_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  // Construct cache id. Let's start with function name, as it should eb unique
  $cid = __FUNCTION__;
  // Now let's add a fast hash of everything important. Seems only $items matter
  $cid .= '-' . hash('adler32', serialize($items));
  // Oh, and language, too!
  $cid .= '-' . $langcode;

  // Do we have results for this set of parameters?
  if( $result = cache_get($cid)  ) {
    // We do, return it.
    return $result->data;
  }

At the end of your function, just before you return value, save it to cache:

  cache_set($cid, $element);

That's all. It will not prevent your function from being called, but it will prevent actual computation in it. Just be sure to choose cache id carefully. It must be fast to compute, but avoid collisions well.


I've struggled with this question today, and because i didn't found any clear answer here's the method with drupal 8.7:

go to your node type structure, and select the display of your field (for example : DD-MM-YYYY)
go back to the feeds mapping, remove your date entry.
add a new entry for the date, or rebuild the entire mapping if you can't change the order of your csv.
clear the cache
the date work now with your new format


Creating module can display map in page or block in drupal

Firstly adding a JS file globally in hook_init function is wrong unless you want the file to be loaded on each page of your site. To add a JS file to a block use the #attached property in hook_block_view

eg:

'#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),

Secondly, I assume you want to show an address from Google Maps in your block.
In that case pull the embed code from Google Maps https://support.google.com/maps/answer/3544418?hl=en
and use that embed code in the block.

Sample Code for it: http://pastebin.com/5h1c2SBU

Though still curious about the JS file.


Why do I have error related to unknown themes during synchronization?

At some point, the config you are using has had those themes enabled.  Either from another site that you got the config set/ database from (e.g. the distro install?) or the themes were install/uninstalled/deleted on the dev machine (testing different themes?).

Since you seem to have the *.settings files for the themes, these were probably installed and then deleted without uninstalling them.  When a theme is uninstalled, this configuration information is removed.

To get rid of them, add back in the themes, re-enable them and then uninstall them.

An alternative is to use "drush cli"  / the log messages to identify the configuration object names.  Then use "drush cdel" to remove them from your dev box.  NOTE: backup your db prior to this!

Or you can find the yaml files in the exported configuration and remove them.  But you will have to do this each time you export to the remote site.

Another possible way is to try the easy uninstall project. Haven't used it but is seems to provide a GUI way to clean up the configuration.

Soapbox Warning

IMHO this is one of the great problems with Drupal 8 using a massive blob of config files.  Developers will test stuff and decide not use it.. and it's impossible to find the cruft in the massive blob...

Features is now available for D8.  It's a pain to set up, but your large blog can become a more manageable set of smaller config sets.


Render React Components in Twig Templates

After doing some research, I found 3 options to render React components on the server side.

Use the PHP V8Js extension to run an embedded V8 engine
Execute node.js processes on demand
Run a node.js rendering daemon for rendering

Rendering on the server side is beneficial for performance of the initial page load. Using the V8Js extension and a twig extension like Tesonet seems like the best option for me.

V8Js installation instructions can be found here

Some other good options to try out are: React Renderer or symfony-react-sandbox or React Bundle. Symfony React Sandbox integrates React Bundle. React Bundle integrates React Renderer.

Read more here


Redirecting from example.com to example.com/drupal

Try in .htaccess and make sure RewriteEngine On

RewriteRule !^drupal/ drupal/%{REQUEST_URI}

Then try example.com if this maps to example.com/drupal/

I think RewriteBase /drupal will not produce the result.

It should be either RewriteBase / or commented in the case above.

I have gone through this issues deeply and fixed on my end.

Put following rule to your .htaccess on root.

RewriteEngine On
RewriteRule !^drupal/ drupal/index.php?q=%{REQUEST_URI}

The default .htaccess of Drupal is restored to original.

After this setup css and image will fail those are depending on $base_path.
I then override $base_path value from /drupal/ to / using hook_init()

function my_custom_module_init(){
   global $base_path;
   $base_path = '/';
}

And this is fixed.


Why is my custom module is not listed with the drush command pm-projectinfo?

The solution is very simple, you just need to add project property in your .info file.

In this case:

project = "my_custom_module"

The Drupal documentation page Writing module .info files (Drupal 7.x) says about the project property:

  project (Discouraged, packaging use only)

  Module maintainers should not use this at all. The packaging script on
  drupal.org will automatically place a string here to identify what
  project the module came from. This is primarily for the Update status
  module, so that Drupal installations can monitor versions of installed
  packages and notify administrators when new versions are available.

But as this is a custom module I think that I need to put this property in my .info file because if not, drush pm-projectinfo my_custom_module will not works.

Let's see why if you don't use the project property this doesn't works

Inside the drush code you can see the implementation of the drush pm-projectinfo command:

function drush_pm_projectinfo() {
  // Get specific requests.
  $requests = pm_parse_arguments(func_get_args(), FALSE);
  // Get installed extensions and projects.
  $extensions = drush_get_extensions();
  $projects = drush_get_projects($extensions);

If you use:

drush ev 'print_r(array_keys((drush_get_extensions())))' | grep my_custom_module

You will see something like this:

[112] my_custom_module

So, we need to test the next step:

drush ev 'print_r(array_keys(drush_get_projects(drush_get_extensions())))' | grep my_custom_module

Nothing to show

So, if we go inside the drush_get_projects() function we can found the following code in line 673:

  foreach ($extensions as $extension) {
    $extension_name = drush_extension_get_name($extension);
    $extension_path = drush_extension_get_path($extension);
    // Obtain the project name. It is not available in this cases:
    //   1. the extension is part of drupal core.
    //   2. the project was checked out from CVS/git and cvs_deploy/git_deploy
    //      is not installed.
    //   3. it is not a project hosted in drupal.org.
    if (empty($extension->info['project'])) {

And in number 3 we have our answer.


Try this:
 - create the view for the month (with the pictures) [field collection module can help you here]
 - Then you create the view for year and call the MonthView inside

(i know this is not the most advanced response you could get, but my knowledge is basic as i been using drupal since last month)

i hope this can help you.


How to differentiate token replacement from array index

You can escape the left square bracket - [ using - %5B
and Right Square Bracket - ] using - %5D

So you should change your code in question to the following.

Create a PDF


How to clone a node without translations

A suggestion : use ->removeTranslation() to get rid of the languages you don't want to be cloned.

Example to get rid of 'es language' so that we clone only the english version :

$langcodetoremove = 'es';
$node = \Drupal\node\Entity\Node::load(1);
$node->removeTranslation($langcodetoremove);
$nodeDuplicate = $node->createDuplicate();
$nodeDuplicate->save();

hope this helps


Check Billing and shipping info to be the same using Drupal commerce module?

No.

I recently added this feature to the commerce shopping module (both 1.x and 2.x branch). It hasn't been widely tested yet though, but I am using it for a production site and haven't seen any problems.

It's available for the 1.0 version or the 2.x-dev version.

This feature has been moved to Drupal Commerce in the 1.4 release (at the time of writing yet to be released), which means right now it's in Drupal commerce dev release and not in the 2.x-dev release.

The setting can be found under:
/admin/commerce/config/checkout/form/pane/customer_profile_billing


How to publish referenced nodes at the same time node is published?

Rules Views Bulk Operations is being worked on which will hopefully allow a change in a node trigger, through a Views argument, a VBO reaction that will, for example, unpublish a set of  referenced nodes.

However, I just needed to hide Reviews in Views that were spread around the website. This is done by using the Relationships content: reference and adding a filter content: published that uses the referenced node relationship to test if it's published.

The reviews will always remain published. They can be viewed if people know where to look which doesn't make a difference. However, now an anonymous user doesn't land on the front page sees a view with a new review that links to a product which isn't published resulting in a page not found error.


How to I style the Superfish accordion menu to have bars?

Seeing you are using responsive and that implies that you are size aware. You may find an icon set more elegant rather than a fixed sized background image.

I load the font-awesome set into the site css anyway for use elsewhere. Therefor the icon's css are available sitewide.

If you look at the accordian settings for that sf menu, you'll see that you can edit that menu button (trigger) text. I found that though a text field, it does accept some html.

For example
Open Menu<i class="fa fa-bars" aria-hidden="true"></i>

gives you those the bars and they re-size as the button text does.


What parts go under source code version control?

There are different ways to approach this, depending on what you need. The easiest approach is the one you described in #1 (Put the entire Drupal folder under version control).

That allows you to easily checkout the full working copy of the codebase with just Git. The downside is that you are storing a lot of code in your Git repo which already exists in other Git repos (ie: Drupal core, contrib modules, etc).

With Drupal 8, the community is generally moving towards using Composer for managing dependencies and building the Drupal codebase. Then, you only need a composer.json file (which points to specific versions of Drupal core and contrib projects), and your custom code in the Git repository. More information: https://www.drupal.org/docs/develop/using-composer/using-composer-with-drupal

Another option is to create an installation profile, and use Drush Make. This method is deprecated in favor of Composer in Drupal 8, but still works nicely for Drupal 7 projects. This is better suited to common code/configuration that you might use to set up lots of similar sites, rather than one highly-customized and specific site.

Regarding Docker - that's sort of a separate decision. You'll still need to choose one of the above options, and then build the codebase accordingly inside the Docker container (or mount it in a volume).


Jquery popup stops the ajax in the form fields

Maybe not the answer you're looking for, but things would probably work if you load the form page within a iframe. I've used this approach successfully with forms that have AJAX fields. In D7 the admin overlay is also built using iframes.


You do it the same place where you add and edit contexts, the contexts admin page located at admin/structure/context. Context defined in code can't be deleted, but can instead be disabled.


Dynamic Form Elements state with multiple conditions

I found a way to use the "!" in order to specify what element i do not want it to show up for.  Its certainly an option and i can definitely use it.  Just thought you

'#states' => array(
  'visible' => array(
    ':input[name="sort_by"]' => array('!value' => 'alphabetical'),
    ),
),


How to add drupal contributed modules into a custom module

If any module is providing its API, than you can use its api.Image Field Crop is not providing any API so you can call any method from that module directly. Don't forgot to add contributed module name  as a dependency in your custom module info file.


How to programmatically delete a display from a view?

DisplayPluginCollection has a remove() method:

$view->displayHandlers->remove($display_id);

But this doesn't work and I couldn't find any code which is trying to actually remove the display from configuration.

So you would have to do this yourself in the view entity (storage):

$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$displays = $storage->get('display');
unset($displays[$display_id]);
$storage->set('display', $displays);
$storage->save();

The problem is this will not run the remove code of the display. For a block display this doesn't matter, but if you delete a page display you might consider running the remove method mentioned above before deleting the display from storage. This will delete the menu links from the page.


How to pass value from form to url parameter

This is solution and working form as desired.

<form name="addres" id="addres" method="get" action="add-your-restaurant">
 <input type="text" name="addresfield" class="resfield"
 name="key" value="Enter your Restaurant name"/>
<input type="submit" class="btn"/>
</form>


Drupal - Save for Later using Workbench, conditional required fields

Yes, this should be fairly easy to do with hook_form_<form-id>_alter():

<?php

function MODULENAME_form_page_node_form_alter(&$form, &$form_state) {
  $target_field = "FIELDNAME";
  $workbench_state_required = "draft";

  $form[$target_field]['#states'] = array(
    'required' => array(
      ':input[name="workbench_moderation_state_new"]' => array(
        '!value' => $workbench_state_required
      ),
    )
  );
}

Just replace MODULENAME with the name of your custom module, and FIELDNAME with the field in question to toggle required or not (you can print the $form array in this function to work out the exact field name if you like).

For more information on the Form States API, visit: api.drupal.org.


Separate line items when line item details are different

You could first have a look at Commerce Product Add-on module. That solution would split them per product type e.g. if you add one product with gift wrapping and one without you will have one line item for the product with quantity 2 and one for the gift wrapping with quantity 1. This gives the customer visibility of the exact pricing.

If however you still want to do it the way you described, the hook you mentioned should work.

function MY_MOULE_commerce_cart_product_comparison_properties_alter(
  &$comparison_properties,
  $line_item
) {
  $comparison_properties[] = 'field_wrapping_option';
}

Possible cause of trouble would be if the 'field_wrapping_option' of the line item being added is not set at all. The existing line item would always have the field set, even with an empty value, while you will have to set it for the incoming line item. It is possible that you set the field value only when gift wrapping is selected, try setting the field value to NULL if no gift wrapping is selected.

$line_item_wrapper->field_wrapping_option->set(NULL);

To further debug why line items are not properly combined, look at the 'commerce_cart_product_add' function at the commerce_cart.module file. The following code is the most relevant.

// Loop over each line item on the order.
foreach ($order_wrapper->commerce_line_items as $delta => $matching_line_item_wrapper) {
  // Examine each of the comparison properties on the line item.
  foreach ($comparison_properties as $property) {
    // If the property is not present on either line item, bypass it.
    if (!isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) {
      continue;
    }

    // If any property does not match the same property on the incoming line
    // item or exists on one line item but not the other...
    if ((!isset($matching_line_item_wrapper->value()->{$property}) && isset($line_item_wrapper->value()->{$property})) ||
      (isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) ||
      $matching_line_item_wrapper->{$property}->raw() != $line_item_wrapper->{$property}->raw()) {
      // Continue the loop with the next line item.
      continue 2;
    }
  }

  // If every comparison line item matched, combine into this line item.
  $matching_line_item = $matching_line_item_wrapper->value();
  break;
}


How to update payment status inside an order?

Please change the code from

 \Drupal\commerce_order\Payment\Payment::loadByProperties(['order_id' => $order_id]);
        TO
 \Drupal::entityTypeManager() ->getStorage('commerce_payment') ->loadByProperties([ 'order_id' => [$orderid], ]);


I've made something similar using normal taxonomy view for "category list" and made an exposed filter for "tags", and to show just tags related to the exact category i've used the "Views Selective Exposed Filters".


Filter the users name in the list of admin / people of organic groups Drupal 7

You can see admin/structure/views/view/og_members_admin/edit/default

In og 7.x-2.0-rc1 exists this functionality


Configuring Fail2ban for the r4032login module

For Fail2Ban v0.10.2, I edited two files in the /etc/fail2ban directory.

I added the following entry to jail.local:

[apache-forbidden]
enabled = true
port = http,https
filter = apache-forbidden
logpath = %(apache_access_log)s
maxretry = 3
findtime = 600
bantime  = 600

For filter.d/apache-forbidden.conf I have the following:

[INCLUDES]

before = common.conf

[Definition]

failregex = <HOST> - - .*HTTP/[0-9]+(.[0-9]+)?" 302

The 302 at the end is to reflect the redirect code for r4032login module.

NOTE: 302 redirects by other modules and Apache might also trigger a ban. Please see the comment below to mitigate this effect.


drupal_add_js not work in form validation failed

Javascripts are lost when the form is rebuilt when using drupal_add_js(). Use $form['#attached'] instead. Also, it's better to use hook_form_FORM_ID_alter() instead of a general hook_form_alter(). hook_form_alter() will run for every form on the page. Try using the below:

function mymodule_form_news_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'mymodule') . '/js/mymodulejsfile.js',
  );
}


You need to create fieldable entity type to make form as you wish and make your custom form by adding fields to it. Than this fields will accessible in page manager UI.


In content type show same field twice with different widget

The "right" way to add additional elements to a view mode (without using a module like Display Suite or Panelizer to take over view modes) is to use hook_field_extra_fields():  This hook will make your added element visible on the core view mode configuration screen.

If you're new to Drupal it might be easier to go with the preprocess route. But instead of working at the level of template_preprocess_field() you should be working at the level of template_preprocess_node(). The node hook contains the field you want to duplicate. The field hook deals with only one field at a time.


You can do it via CSS, just add the !important:

.password-suggestions {
  display: none!important;
}

Another option is to copy the modules/user/user.js file to your theme, add it to .info file and edit it the way you want.


How to get fields values in an override file?

If you look at the comment in the beginning of the template file you're overriding, you should notice that it lists the variables available for any override code.

For instance, in field.tpl.php (used as starting point for overrding field templates), you should see the following line inside that comment:

* - $element['#object']: The entity to which the field is attached.

This gives you the name of the global ($element['#object']) to examine to look for the values of the fields.

Now, you need to look "inside" this object to figure out how to access the values of these fields.  To do so, the Devel module is what you need, so install and enable this for your (test) site.

Then put the following near the top of your template override file:

<?php dpm($element['#object']); ?>

When you look at the page again as administrator (clear cache and reload if necessary), there should be a Krumo accordion in the message area that expands this object. Expanding it will tell you how to get to the value of each field present in the entity.  For instance, it may tell you that the value of field_one is $element['#object']->field_one['und'][0]['value'].

Now, you should be able to extract and add the fields, e.g.:

<?php
$field_one = $element['#object']->field_one['und'][0]['value'];
$field_two = $element['#object']->field_two['und'][0]['value'];
$sum = $field_one + $field_two;
?>

Disable Devel and delete the call to dpm() on a production site.


The problem was I hadn't the dependency libraries . Just downloading this module, updating, and adding the spyc.php in 'servers/rest_server/lib/' Rest server will work.


How to apply some rules to fields in native contact form?

If your real case is the telephone example, you need to enable the Telephone module that comes with Drupal 8 Core. Then add the telephone field to your contact form in "Manage Fields".

If you think you're doing something "popular" chances are high that someone already did it (ie Telephone module), so don't rebuild the wheel.

If your scenario is some special use case, then you want to do a custom form validation for your form field. See How do I add a custom validation to an existing form/field?


How do I add watermark to the image with insert module

Your question is threefold:
Adding a watermark
For this, I suggest using ImageCache Actions module. Of the effects it provides, first one is:

Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha transparency

Selecting watermark
Image field does not know about taxonomy field when it decides how to render it's content. You could hack it together in your template. I would rather go for Formatter Field - not exactly what you described, but use case on module page seems to fit your needs:

For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

Preventing original image from being downloaded
Drupal modifies user-provided content on display, not on save. This means your original image will be up there, without watermark. Image Style Access claims to be the solution:

This module provides access control for image files. Each access configuration can be set to allow or deny access to images and their derivatives by:

Disclaimer: I never used this one .


Should I enter data as English and then translate to my language?

Well, if you've a only one language website, you can directly enter the values directly in your own language. You can also install your language pack that you can find on localize.drupal.org.

If you gonna start a multi-language website, you should (and its easier) to start everything in english and after start to translate. But in that case, is already important since the beginning to active all languages that you need.


How to change form submit button value after form submission?

You can do this with two steps. The first is to check whether $form_state['values'] has been set, and change the value accordingly:

if(!isset($form_state['values'])) {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
}
else {
  $form['submit'] = array (
    '#type' => 'submit',
    '#value' => t('Submit Again'),
  );
}

The next step is in your submit function, where you have to tell Drupal to rebuild the form (rather than build it from scratch)

$form_state['rebuild'] = TRUE;


Path issues using composer for Commerce install on shared hosting

Went back and installed the drupal 8 tar.gz (without composer or drush) for the 3 directories I wanted and ran composer from each directory to update and then installed commerce.

After installing the tar.gz

ran: composer config repositories.drupal composer https://packages.drupal.org/8

then: composer require "drupal/commerce 2.x-dev"


add css class to row with specified field value in views

You can do this in views.
The class in views supports tokens. So if you use the value of a field [field_value] and put that in the class, then you can style it by using .field_value in your css.

This way every field will get a class, but only the ones you style in css will affect how they look.


Ok, so this was in fact very simple... though it took me a great deal of time to find the solution. I removed the snippet in the custom module above and instead I added the code below in template.php. Hope it helps somebody. I found the solution here: http://agaric.com/blogs/altering-views-results

function mytheme_views_pre_render(&$view) {
if ($view->name === 'myview' && $view->current_display === 'mydisplay') {
        foreach($view->result as $index=>$val){
          $product_node = node_load($val->field_data_field_related_product_nid);
          if($product_node->status === '0'){
             unset($view->result[$index]);
          }
        }
    }
}


problems with entity translation insert hook

A trick to bypass this could be to use a static variable to process nodes only once per request, e.g.

/**
 * Implements hook_entity_translation_insert().
 */
function yourmodule_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  static $processed = array();
  if ($entity_type == 'node' && !isset($processed[$entity->nid])) {
    // Do something
    $processed[$entity->nid] = TRUE;
  }
}


Imce file browser not showing select button

Oh for heavens sake. I turned off Aggregate-JavaScript and cleared cache. The select button shows up. As to why this happened I can't say. I'm leaving this answer here in case any one comes up against this.

Temporarily turn off magnification and clear cache.


How do I alter the submission button class?

If I were you, I would not change the class name but rather add your own class to the form element. You can do this by implementing hook_form_alter in a custom module or (in case of Drupal 7) in your theme. The code would look something like this:

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id = 'my_form') {
    $form['actions']['submit']['#attributes']['class'][] = 'form-submitone';
  }
}
?>

By the way, the submit button element is not necessarily $form['actions']['submit']. You will have to figure out which element is the submit button in your specific situation. You can do that by outputting the $form variable; I recommend installing the Devel module and adding dsm($form); to the function above.


It depends on which print engine you're using. I am using the following entity-print.html.twig with the dompdf engine.

    <meta charset="utf-8">
    <title>{{ title }}</title>
    {{ entity_print_css }}

{# The footer is repeated on all pages and must be printed first. #}

    {{  footer  }}

{%  if cover_page  %}

    {{ cover_page }}

{%  endif  %}
{# The header is repeated after the cover page for all pages. #}

    {{  header  }}

    {{ content }}

The header and footer must be styled with position: fixed, after which they are displayed on every page.

I haven't found any great combined reference for the entity print module, but searching for what you want to accomplish along with your print engine's name should be helpful.


Permission denied when configuring my module though admin page

Try to change

'access arguments' => array('access administration pages'),

into

'access arguments' => array('administer site configuration'),