Refresh two views with same exposed filter using ajax

ATTACHMENT is what you need!

Try using an "Attachment" in view, what you can do is create your View which can be either Content, User or Term View and just after that add an Attachment and attach is it the required view display, before or after that depends upon your requirement also don't forget to inherit contextual and exposed filter which should act as the key property here.

For a quick view purpose, I'm attaching a demo view exported code:

$view = new view();
$view->name = 'demo';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Demo';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Demo';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Author uid */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'node';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['value'] = '';
$handler->display->display_options['filters']['uid']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator_id'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['label'] = 'Author UID';
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
$handler->display->display_options['filters']['uid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

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

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';
$handler->display->display_options['inherit_exposed_filters'] = TRUE;


Ended up just grabbing the passed variables from $_GET.


So I realized I was using an outdated version of Chart.js (from an old production site).
I just updated to the latest version, and now all is well with the world.

Thanks.


trying to add a template file to my module using hook_theme_registry_alter

I'd imagine you should be using hook_theme() instead of hook_registry_alter() to define your theme function:

function MYMODULE_theme() {
  return array(
    'popover' => array(
      'template' => 'popover',
      'variables' => array('var1' => array(), 'var2' => '')
    )
  );
}

Then you can call it from anywhere (including a page callback, which I think is where you're trying to return this from given your comment above):

$output = theme('popover', array('var1' => $var1, 'var2' => $var2));

In the popover.tpl.php file in your module's root folder you'll have access to the variables $var1 and $var2, which will be the vars you defined/passed into the theme function.

Then you can build up your HTML as you need.


Email users on node creation based on taxonomy reference

Actually, you can pull up all users (or any entity) based on a field value by using the 'Fetch entity by property' action.

Since users (and nodes, and comments, etc) are all entities, you can use this action to pull up a list of users with a certain value in a field.

In your rule, that gets fired upon the update of a node, simply

add the 'Fetch entity by property' action,
select 'User' as the entity type, and
in the final screen choose the field (in your case a term reference) you want to check and the specific value you're checking for.
Feel free to change the name of the entities it will fetch for you.  By default they will be called fetched_entity.

THEN, add a loop to your action set after this fetch, to go through each of the found entities.  In this loop, we'll check for your second field and exclude the necessary ones.  From what I understand, you'll want to exclude the ones whose uid matches the user reference field on the edited node.

So here's how:

By now your rule's action set should look like this: You're fetching users by your taxonomy property, then you'll looping through all the found entries (make sure it's pulling as many as you want, because it limits to 10 by default, by the way).

Now, add a component in your rules.  Components are used when you need an entirely new rule to execute in your action area.  Now that we're looping through users, we need an entirely new rule to call (IF the user doesn't have field x, THEN do y).  However, when we're in the action area, we can't call conditions.  So that's why we'll create a component that's a rule within itself, and call it from here.

Go to admin/config/workflow/rules/components or Configuration --> Workflow --> Rules --> Components
Click to "Add new component"
Select "Rule" for the component plug in.  We don't want it to be just a condition test or an action, we want it to contain both a condition and action!
Call it something like "Email non-referenced users" or something like that
We will pass it two parameters. We need to pass it the user we're currently looping through and the node that has just been changed (that triggered the rule) because we'll compare the user's uid with the node's user reference field.

Add a condition to your component that is a 'Data comparison' condition and compare the looped_user:uid (or whatever you called that incoming parameter) to the user reference field of your updated_node (or whatever you called that incoming parameter)
Careful here, make sure to check the 'Negate' checkbox at the bottom of that condition.  We want to let through only those users for whom the two fields DON'T match, i.e. the ones that aren't referenced.

 - As an action in the component, have the system send out the email you want

Voila!  Almost done.  This component now narrows down our looped users (with the correct terms) to those who aren't referenced and emails them.  The one thing we have left to do is to CALL this component in our user loop.

Go back to your original rule, and click 'Add action' to your loop (not below it, but on it)

In your list of actions, at the very, very bottom, you will see the names of components you have created.  Your new component should be there.  Just select it, and pass it the updated node and the 'fetched_entity' (which is your currently looped users) as the two parameters.

Test!

Hope this helps.


How to change date repeat display format

Similar question was raised before. There is still no way to override the format of the Repeat rule via theme functions. The answer that was given for the linked question provides a possible workaround (quoted below).

  you may override theme_date_repeat_field(), which calls
  date_repeat_rrule_description(). You could call your own version of
  that function to customize the display.

  This would leave the contrib modules untouched, but you would be
  duplicating some effort and have more code to maintain.

There is an active issue for Date Repeat sub-module - Make Repeat Date Format/Display More Flexible which did not receive enough attention.

You can also patch the date_repeat.module directly and keep track of it during updates, but that is obviously not a desired way to go about this.

The function that constructs the output of the string you need to change is

function date_repeat_rrule_description()

check $output variable - that is what you are trying to modify.


Making user profiles publicly accessible in Drupal 7

Simply go to /admin/people/permissions, scroll to the bottom of the page and turn on all check boxes for the View user profiles permission.


Retrieveing config for a custom ctools content type

What I think you want might be possible, but it is not easy.
The configuration settings are saved in the DB in the panels_pane table as serialized data in the 'configuration' column. That allows each instance of the pane to have its own configuration. In order to get that you would need to know how to get the specific instance of the pane being displayed, grab the column, and then unserialize it.

You are probably better off figuring out a different way to handle this (if you haven't already).


Subdomain involuntarily redirects to primary domain after logging in or saving

In the settings.php someone uncommented $base_url and put the primary domain of the site as a value. Changing the value into the subdomain I was working in solved the issue.


how do I programmatically save nodes with multiple photo uploads?

You would normally just build up the files in a loop like so:

$images = array();

foreach ($file_data_array as $file_data) {
  $file = new stdClass();
  $file->filename = basename($file_data['filepath']);
  $file->filepath = $file_data['filepath'];
  $file->filemime = $file_data['mime'];
  $file->filesize = filesize($file_data['filepath']);

  $file->uid = $uid;
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);

  $images[] = array(
    'fid' => $file->fid,
    'alt' => $file_data['alt'],
    'title' => $file_data['title']
  );
}

$node = new stdClass;
// Build up the rest of the node as normal

$node->field_images[LANGUAGE_NONE] = $images;

node_save($node);

This assumes you have your CSV data loaded into an array called $file_data_array.

fid, alt, title, height and width are the only columns available to an image field type so there's no need to build up an array for each field entry containing all the file details (you can ignore that bit in the other answer you linked to as it's unnecessary).

Also note the use of file_save() instead of drupal_write_record() to commit the file to the database...it's much better to use file_save() as it fires the necessary system hooks to let other modules react to your files being added.

Hope that helps


Brandon's answer is good for altering the email messages.

If you are looking to alter the status message that pops up afterwards, I found this answer helpful: https://stackoverflow.com/a/38797543/963866


Why doesn't the "auto-create feature" in the Ftools module work on Features 2.x?

Features 2.x has this functionality built in, so you don't need to use ftools anymore.  Go to the feature configuration page, click Advanced options, set the Path to Generate feature module, and then click Generate feature.


Redirect 'user' and 'user/uid' to 'users/name'

By redirecting /user you'll be redirecting the login page to a user page.  When someone goes to /user and logs in they are automatically redirected to /user/username.  Unless you have login disabled(not advised) I can't see what you want to achieve, can you explain further?

Redirects are best handled by the path redirect module

or using rules in .htacces or etc/apache2/httpd.conf


Download file after fill in email address

The easiest way without resorting to coding would be setting up a Webform that the user is required to fill out, containing only one email field, and putting the link to the PDF in the completion message.

If you need strict access control on the PDF, you can setup your site with Email Registration and Generate Password, and redirect the user after registration to a node that is visible only to authenticated users. Add a file field using the private file system to the content type and attach the PDF to the node.


What configuration is required to use date_views with a field?

In addition to mapping 'handler' to 'date_views_filter_handler' you need to tell date_views that the field is a date:

function mymodule_views_data_alter(&$data) {
  ...
  $data['mymodule_referral']['referred_at']['filter'] = array(
    'handler' => 'date_views_filter_handler',
    'is date' => TRUE,
  );
}

In the filter settings for referred_at you will now see referred_at as an option for "DATE FIELD(S)", and if you select it then it will work as expected.


How to fix 'Cannot access empty property' when visiting admin/reports/databasereport?

I haven't used the Database Administration module before but when i looked on the line 44 of that module and I found that:

$value = new stdClass();
$query = db_query('SHOW GLOBAL STATUS');
foreach ($query as $row) {
  $column = $row->variable_name;
  $value->$column = $row->value;
}
return $value;

It means you can't fetch the data from 'SHOW GLOBAL STATUS' SQL statement. So i think maybe your current MYSQL account didn't have right to do that.


How to redirect after node insert (not form redirect)?

You could do a redirect in hook_node_insert(), however that would then prevent any other implementations of hook_node_insert() that come after your implementation from being executed.

I would instead suggest removing the code you've added in hook_node_insert(), and instead adding a custom submit handler to the node creation form. You can get the newly created node ID from $form_state->get('uid'). You can use that to load the newly created node, then create your node, and finally add the redirect in the form state, as you've mentioned in your post. This way no APIs are bypassed, and your redirect will happen after everything has been executed.


The variable you are looking for is not ns_custom_template but test_var

To get all variables in your twig file, you can try {{ kint() }}

To get the variable you have previously declared in mymodule_theme, you can try {{ kint(test_var) }}

BUT there is another mistake:

The twig file in which you will find test_var is not node--page.html.twig but only ns-custom-template.html.twig

if you want to have test_var inside node--page.html.twig, you can use a preprocess function : function template_preprocess_node with a code like:

$var['test_var']='my value';

EDIT:It seems that you would like to use the template ns_custom_template in a node template: to achieve this, you need to populate your variable test_var with a render array having the name defined in mymodule_theme as a value of the #theme key.

function mymodule_preprocess_node(&$var) {
  $var['my_free_var_name'] = ['#theme' => 'ns_custom_template', '#test_var' => 'your value'];
}

After doing this, you can display your template inside node--page.html.twig bu using the following code:

{{ my_free_var_name }}


Why would my Cron run fail when run by system crontab, but succeed when run manually?

Check to see if you have a php-cli.ini file being loaded. From the command line, do:

$ php -i |grep ini

and see what ini file is being loaded. If there's a cli ini loading, it may not have the same memory limit as your 'normal' php.ini.


Access denied on image styles files on Drupal 7.34

It's common to have incorrect permissions on that folder. You'll need to fix the permissions for /site/default/files directory. For a complete answer, see the recommended directory permissions or just run the following from the website root (per @David's comment below).

find sites/default/files -type d -exec chmod 755 {} +
find sites/default/files -type f -exec chmod 644 {} +
chown -R www-data:www-data sites/default/files

For additional issues, check Status Reports on yourWebsiteName.com/admin/reports/status.

Update:

I think I found the issue.

There was a similar question asked on Drupal.

It seems that the issue is that certain hosts, such as BlueHost, HostMonster and Virtualmin forbid +FollowSymLinks. You will need to change +FollowSymLinks into +SymLinksIfOwnerMatch in your .htaccess file. See an entire discussion on Drupal.


How can I take control of the rendering of a file entity when inlined in text?

Your best bet is http://drupal.org/sandbox/DevinCarlson/1823634 - which is an add on to media, but I'm not certain whether or not it can also display fields that are attached to a file entity.

As per http://drupal.org/node/1792738 this functionality is planned to be rolled into the media module at some stage.


I had the same problem.

I have a view with links to content, where the URLs are item/[one content's field value]. One day, I watched the view as anonymous user and noticed that these had been changed to index.php/index.php/item/[one content's field value]. (On the other hand, when I visited as administrator user, it didn't happen.)

I didn't know why it happened, and it was solved by executing drush cc render.

However, the problem would still be left.

The environment is Drupal 8.3.9 and PHP 7.0.25.


Omega & delta: rendering node title in a block

Delta Blocks (sub module included with delta) makes that available as a block, as well as things like the author, terms, and post date. Combine with the context module and you can place the blocks in whatever order you like for particular content types.


Apply percentage coupon to entire order (Commerce)

Price calculation in Drupal Commerce always happens at a line item level. There are order level coupons for knocking a set amount off an order total, but we treat percentage coupons as these line item level price calculations. You should be able to adjust the weight of your product pricing rules so your rule that updates the price gets evaluated prior to the rule that applies the percentage coupon to the item. Give that a shot and leave me a comment if it doesn't work.


how to propose when editing content 2 possible media style for an image field?

You could add a separate select dropdown textfield with two options, which are the image styles you'd like, and if they select the alternate one, update the field in hook_entity_view.

 function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
   if ($entity->getEntityType()->id() == 'node' && $entity->bundle() == 'article' && !$entity->field_image_style->isEmpty()) {
     $style = $entity->field_image_style->getValue()[0]['value'];
     $build['field_image'][0]['#image_style'] = $style;
   }
 }


How do I limit a normalizer to a given class or interface?

You didn't explicitly state that your class is extending NormalizerBase, but I assume that's the case. My reply is based on that assumption.

If you look in the code for NormalizerBase, there are two spots where $supportedInterfaceOrClass is accessed, in supportsNormalization() and supportsDenormalization(). If you override supportsNormalization() as option #2 from the original post suggests, your normalizer will be restricted to nodes. However, it overrides the base method, bypassing a check to see if the given normalization format is even supported, which is not good. If someone were to try to normalize an unsupported format, the overridden method would incorrectly return TRUE. Therefore, it is better to set supportedInterfaceOrClass according option #1 from the original post, as that will also cover the denormalization option, as well as allow the base API to do its work.

Verdict: Do NOT use method #2. Do use method #1. I would implement __construct() and set the node class upon instantiation:

public function __construct() {
  this->supportedInterfaceOrClass = NodeInterface::class;
}


How do I get the fields of a user object

The full answer is: There's no single piece of code which can answer your question. Since PHP has weak and dynamic typing, any piece of code can access the global $user object and can remove/add something to the the object (whether this is always a good idea is an other question).

As a Java (which statically and strong typed) veteran this was the biggest difference to cope with.

BTW: Use dpm which comes with krumo support instead of var_dump this makes the output much more readable. An other aproach is to get familiar with a debugger (Xdebug or Zend).


Is there any alternative of node_save to update database fields in iteration?

you can use entity module. This module proves entity_matadata_wrapper API which allows you to load and save fields of nodes. The following code is an example of altering a node's title.

$nodeWrapper = entity_metadata_wrapper('node', node_load($node->nid));
$nodeWrapper->title->set(t("Saved by Entity Save"));
$nodeWrapper->save();

entity_matadata_wrapper is not limited to nodes. As you can see in it's signature you must specify the element which in your case it is node.


how to get content type field name as drop down for filter in view

I can only give you an example of querying the users table and displaying the people in the users table as an option but this might help:

  function example_page_builder() {

  $form = array();

 //getting the list of users
  $query = "select * from users where name!='';";

  $result = db_query($query);
  foreach ($result as $user) {
    $users[$user->uid] = $user->name;
  }

  $form['example_field_set']['users'] = array(
    '#type' => 'select',
    '#weight' => -6,
    '#title' => t('Select User:'),
    '#options' => $users,
  );

  return $form;
}


"add content" suddenly not showing on navigation block anymore

First a clarification about terminology: make sure to correctly separate access to "blocks" from "navigation links": your non admin users seem to have access to that "block" also (that Ajax link in it proofs that to me). Your real issue/question should be something like "why are some of the menu links missing in that block?".

Seems like you need to resolve that "Access Denied" message first. Even though it's hard to tell (from the screenshots provided), My best guess would be that you need to review/tune some of the settings related to "node" within admin/people/permissions.

So check/confirm that for the users who receive this "Access Denied", they are granted the permission like "View Published Content". If that permission was not granted yet, then do so now and try again to see what happens.

A few more "comments" (moved from the comments below to around here):

The "menu items" that are shown in that block, will be shown (only) to the users who have access to the actual content (node) that the menu items are related to. And apart from that there is the "block visibility", which is typically something you "can" set so that it is only shown (or hidden) on specific pages, or so that it is only shown to users with specific roles.
About "I didn't want every user to other users' published content": looks like there is something you mis-interprete about the "View published content": that permission is ONLY a way to tell Drupal "which roles are allowed to see anything (nodes) that have the "published" checkbox turned on. It seems to me that you MIGHT need to add something like the (great!) "Content_Access" module to implement something similar to what you wrote in one of your last comments.
If it makes sense, you should set the "default" content access for each content type first, so that you only have to change it for those nodes where you want content access to be different from that default. So no need to "go through every content to manage their content access".


To pass the tid as an array value in callback funtion

I am sharing here some dummy data with you, it might help you.

{
    "tid": "25,17,28",
    "pager": 1,
    "limit": 5,
    "order": "desc"
}

   array(
                  'name'         => 'order',
                  'type'         => 'string', // it should be string because it can be either ASC or DESC
                  'description'  => t('The order clause for the query that retrieve the nodes.'),
                  'source'       => array('data' => 'order'),
                  'optional'     => TRUE,
                  'default value'=> array('t.sticky' => 'DESC', 't.created' => 'DESC'),
                ),

// Call back function

function taxonomy_service_select_nodes($tid, $pager, $limit, $order) {
  $tid_collection = array();
  $tid_collection = explode(',', $tid); // Here your tids are in array format and you can use in your code accordingly.
  echo $pager;
  echo $limit;
  echo $order;
}


Adding members to a group dynamically in Drupal 8

So, modifying the code a little bit and saving the group after adding member to it worked for me. Pasting the updated code below:

use Drupal\Core\Entity\ContentEntityBase;
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$group = \Drupal\group\Entity\Group::load($group_id);
$group->addMember($account);
$group->save();


mysql server gone away while loading drupal site in the shared environment

Increase max allowed packet size is the only proper way of doing this.
If your host doesn't allow you to change values in your multi-site environment simply change the host because you could experience a lot more problems overtime if you're not allowed to change anything!
A quickfix solution could be to limit the number of activated modules and by this limit the number of queries executed on page loads.


How to print/render nested Paragraph values to twig template?

I am also curious about the best way to do this. While I'm still trying to figure out what that is, here is what I've done:

I've enabled the Twig Tweak module, and inside the first paragraph template, I pull in the second paragraph with a selected view mode.

{{ drupal_entity('paragraph', content.field_sidebar_area[0]['#paragraph'].id(), 'MY_CUSTOM_VIEW_MODE') }}

And then in the template for the second paragraph, I can adjust the Twig as I please. Note that the naming convention would be:

paragraph--PARAGRAPH-TYPE--MY-CUSTOM-VIEW-MODE.html.twig.

Best of luck!


I can't get the SKU value for a commerce product in a rule action

In order to access the SKU for the product you must first use two conditions in your rule to assure that you are dealing with the right type, these are :

Entity is of type commerce-line-item
Entity has field commerce_product

Just as an example this Rule export applies a discount ( 5_eur_disc ) to a product with an SKU of SKU-FOO-ITEM after checking that the discount dates are current.

{ "commerce_discount_rule_discount_discount_per_sku" : {
    "LABEL" : "Discount per SKU",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [
      "commerce_discount_date",
      "rules",
      "commerce_discount",
      "commerce_product_reference"
    ],
    "ON" : [ "commerce_product_calculate_sell_price" ],
    "IF" : [
      { "commerce_discount_date_condition" : { "commerce_discount" : "5_eur_discount" } },
      { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "data_is" : {
          "data" : [ "commerce-line-item:commerce-product:sku" ],
          "value" : "SKU-FOO-ITEM"
        }
      }
    ],
    "DO" : [
      { "commerce_discount_fixed_amount" : {
          "entity" : [ "commerce_line_item" ],
          "commerce_discount" : "5_eur_discount"
        }
      }
    ]
  }
}


How can I place the article date before the title?

You can do this by implementing template_preprocess_page_title() hook in your Theme (THEME_NAME.theme). Check example below:

/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function [THEME_NAME]_preprocess_page_title(&$variables) {
  // Check if page is node page, and is instance of Node.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && ($node instanceof \Drupal\node\NodeInterface)) {
    // Get created time of Node and convert to human readable, and append Node title.
    $variables['title'] = '' . date("d m Y", $node->created->getValue()[0]['value']) . " " . $node->getTitle();
  }
}

Similar question is answered by @Linus's here.


You can implement hook_form_alter() for your content type and then do something like this inside your implementation:

// implement hook_form_alter() for cex_3dr content type:
function cex_3dr_form_alter( &$form, $form_state, $form_id ) {

  if ($form_id == 'cex_3dr_node_form')
  {
    // get rid of form elements that may confuse end-users
    unset( $form['menu'] );
    unset( $form['body_field']['format'] );
    unset( $form['revision_information'] );
    unset( $form['path'] );
    unset( $form['attachments'] );
    unset( $form['author'] );
    unset( $form['options'] );
    unset( $form['comment_settings'] );
    unset( $form['buttons']['preview'] );
  }
}

you can also print out the contents of the form to see what fields are there, and then you know which ones to get rid of via an 'unset()'.

BTW, this is Drupal6 logic. Haven't done D7 modules yet, so the technique may vary a bit, but the concept is 'very drupal' so I'd be surprised if it were no longer possible.


Taxes are dependent on shipping address so adding a tax line item to the cart does not make sense. Try looking at one of the tax rules on /admin/config/workflow/rules/components to see how the tax line item is added to an order. By default, tax line item is added in the pane that comes after a customer has entered her shipping address and before payment is submitted. Adding a tax line item to a cart requires a custom line-item type and a shipping address to be provided for tax calculation.


Using different markup for views last item

To do this:

Find template file that adds "last" class
Override it in your custom theme
Expand if responsible for "last" class, to make it contain all element's markup
in if block write markup for last element, in else block - for all other elements.


array_keys($result['node']) isn't going to return an object that you can select a nid property from; it's going to return an array of nids that have $termid tagged in its field_terms field. If you're just looking for the first nid in the query results you can do $nid = array_keys($result['node'])[0];


According to the documentation the URLs shouldn't necessarily have .json at the end, but I guess this is a setting you've changed if it's working for the node functions. I know you're not going to like this answer (I'm fairly certain you've tried it before) but the URL is: mydomain.com/service/rest/taxonomy_vocabulary/getTree. I've even been through the service and rest_server modules' respective code and that is definitely what it should be.

For further proof look at the (valid, passed) test module for services taxonomy_vocabulary:

ServicesResourceTaxonomyTests::testVocabularyGetTree.

You'll see that the URLs accessed by this successfully passed test are: $path . '/taxonomy_vocabulary/getTree', where $path is the path to the endpoint (i.e. mymodule.com/service/rest/).

It really would help if you could provide a live link though so we can test to see if the problem is in your Java code or with Drupal (although the latter seems very unlikely).

EDIT

p.s. do comment on this answer as I have a lot of experience with the services module and I'm sure I can point you in the right direction with a bit more info. It pains me to see someone struggling with something that I've had nothing but joy with in the past!

ANOTHER EDIT

This is the response I get from http://delvelogic.com/merchant/drupal-6.22/services/rest/taxonomy_vocabulary:

<?xml version="1.0" encoding="utf-8"?>
  <result>
    <nodes/>
    <module>taxonomy</module>
    <name></name>
    <help></help>
    <relations>0</relations>
    <hierarchy>0</hierarchy>
    <multiple>0</multiple>
    <required>0</required>
    <tags>0</tags>
    <weight>0</weight>
    <vid>4</vid>
  </result>

Notice the <vid>4</vid> bit...I'm pretty sure the vid you should be looking for is 4, not 1!


How to pass a field value as contextual filter argument using Twig Tweak drupal_view?

First of all check drupal_view implementation but I think that the arguments parameter (contextual filters) is an array, though the function wraps scalars into an array you should pass an array (robustness). Said that everything looks fine in your template perhaps you should do {{ vardumper(content) }}  to see what actually is getting to your template variable. In order to use the vardumper function you need to install the VarDumper module.


How to modify/add addition variable to service json after successfully register.json?

Add custom code/module to modify the service response, check hook_services_endpoint_response_alter and all other similar alter hooks services alter hooks

e.g.:

function MODULENAME_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller->callback == '_user_resource_create') {
    if ($result->uid) {
      $user = user_load($result->uid);
      $result->user = $user;
    }
  }
}


I know what you're trying to do with Views, and it's easier than you think once you get comfortable with Views Contextual Filters.

Check out this video (or the text version article) that clearly walks through how to use Drupal Views Contextual Filters. The linked examples use Pets (Dogs, Cats) as sample data, so you'll see how to filter Cats versus Dogs quickly.

VIDEO: https://www.youtube.com/watch?v=lJFMTDuaxy8 (YouTube video short-url: lJFMTDuaxy8)

ARTICLE: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views


Adding an address to a node's address field programmatically

I provided a code example using entity_metadata_wrapper() in this issue. As soon as I finish cleaning up the issue queue, I'll make a regular documentation page out of that. You can follow this issue to see when the documentation page gets published.


How to add relationship in view for custom entity

Entity API supports this out of the box, but you will have to let it know which entity your data represents. If Entity API encounters a field containing numeric data it will by default assign it the type 'integer'. Just change the type to the right entity type and you can define the relations in Views:

<?php
  /**
   * Implements hook_entity_property_info_alter().
   */
  function my_entity_entity_property_info_alter(&$info) {
    $info['my_entity']['properties']['nid']['type'] = 'node';
    $info['my_entity']['properties']['uid']['type'] = 'user';
    $info['my_entity']['properties']['tid']['type'] = 'taxonomy_term';
  }
?>


Drupal Commerce Rules if Paypal Payment Method is Selected

You can use the event

'After updating an existing commerce order'

on condition

'Selected payment method comparison' under commerce Payment and select its value to 'Paypal'

Now in action add 'Remove taxes applied to a line item' and another action 'Add an item to list' to add %3 amount to total .

It will perform accordingly.

Hope it will work for you!


How do i use pathauto to create a url alias for nodes' menu local tasks?

The Sub-path URL Aliases module will do this.


Some of my site's pages are retrieving the .css files from a different directory

May I know where you have added CSS? on theme.info file or template.php

This issue occurring because of your theme has contained an absolute path, You need to replace absolute path the relative path.

First, you need to check that, On which file this CSS has called.

Remove from there and add CSS on theme.info file or template.php file.

On theme.info you need to add like stylesheets[all][] = custom/mytheme/css/main.css

On template.php you need to add css using drupal_add_css on template_preprocess_html(&$variables).


Updating Commerce Kickstart’s Contrib Modules

First, you need to understand that Commerce Kickstart is a Distribution. So your goal is to learn how to update a Drupal distribution before their official release.

For the most part you would need to understand how Drupal Make works. Where is a great article ( Maintaining your installed Drupal distro.) that would explain you how to maintain Drupal distributions.

If you successfully was able to update your Drupal distribution (commerce_kickstart) using Drupal Make. You should created a patch and provide that patch to the commerce_kickstart issue queue.


Change drupal 7 way of hashing password?

This is entirely possible but requires custom code for your alternative solution. For an example see:
https://www.drupal.org/node/1109374#comment-4711644

From the linked thread you may simply:

(1) Create a new module, I called mine projectname_legacy_auth

/**
 * supply alternate authentication schemes
 */
variable_set('password_inc', drupal_get_path('module', 'projectname_legacy_auth') . '/projectname_legacy_auth_password.inc');

function projectname_legacy_auth_uninstall() {
  // put it back the way it was...
  variable_set('password_inc', 'includes/password.inc');
}

function projectname_legacy_auth_disable() {
  // put it back the way it was...
  variable_set('password_inc', 'includes/password.inc');
}

(2) add the authentication mechanisms you need to projectname_legacy_auth_password.inc'.
In this case, it's md5().

/**
 * simplified example for md5, no salting
 */
function user_check_password($password, $account) {
  if ($account->pass == md5($password)) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Simplified example for md5 hashes, no salting
 */
function user_hash_password($password, $count_log2 = 0) {
  return md5($password);
}

/**
 * this is probably a bad idea :-)
 */
function user_needs_new_hash($account) {
  return FALSE;
}


How to allow users to cancel their own account?

Seems the Cancel Account Separate Form module does exactly what you want. It provides a form that finally calls user_cancel with the current user's UID as parameter.

  This is a very simple, lightweight module that provides cancel user
  account separate form and adds it to user edit form by default if user
  has cancel account permissions and edits his own account.


Go back and scrutinize your validation function. The code you are showing here actually works, so the problem is something you did not include in your sample.

For the reference, the working implementation over here is:

function form_newteam ($form, &$form_state) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    drupal_set_message("valid");
}

function form_newteam_submit($form, &$form_state) {
    drupal_set_message("submit");
}

Please note that your function names do not conform to the drupal coding standards. Function names must be prefixed with the module name. Therefore you should name your functions like this: tournament_newteam or tournament_newteam_form. If those are administrative forms, stick them into tournament.admin.inc otherwise place them into tournament.pages.inc.


Field widget value not able to save via ajax

There might be a few issues, but it hard to tell.

First make sure the field is actually on the node. (Source https://www.drupal.org/documentation/entity-metadata-wrappers):

function _wrapper_debug($w) {
  $values = array();
  foreach ($w->getPropertyInfo() as $key => $val) {
    $values[$key] = $w->$key->value();
  }
  return $values;
}

dpm(_wrapper_debug($some_wrapped_object));

If it is there, perhaps you made the field a multi value field (it can hold more then 1 value), in this case you need to assign it like this:

 $node_wrapper->field_log[]->set(1); // Note the extra []

If this does not solve the problem, have a look at the above metadata wrapper page. It comes with a lot of examples en explanations.


How do I display the attachment's file size of a node?

You can do this hardcoded with the $node object by doing so (preferably in theme_preprocess_node in template.php) :

If you field field_my_field as a single value :

$file = field_get_items('node', $node, 'field_my_file');
if ($file) {
    $file_size = $file[0]['filesize'];
    $file_size_formated = format_size($file_size);
}

If you field field_my_field as a multiple value :

$files = field_get_items('node', $node, 'field_my_file');
if ($files) {
    $files_size_formated = array();
    foreach ($files as $key => $file) {
        $file_size = $file['filesize'];
        $files_size_formated[] = format_size($file_size);
    }
}

In template.php you should have something like this :

// This function allow one preprocess_node function per content type
function mytheme_preprocess_node(&$vars) {
  $node = &$vars['node'];
  // Preprocess function for each node type
  $function = __FUNCTION__ . '_' . $node->type;
  if (function_exists($function)) {
    $function($vars);
  }
}

function mytheme_preprocess_node_my_content_type(&$vars) {
  $node = &$vars['node'];
  $file = field_get_items('node', $node, 'field_my_file');
  if ($file) {
      $file_size = $file[0]['filesize'];
      $vars['file_size_formated'] = format_size($file_size);
  }
}

Then in you node--my-content-type.tpl.php you can print your var $file_size_formated where you want like this for example :

<?php print $file_size_formated; ?>


Filter Criteria "Workbench Moderation: Current" only works on published revisions?

I found the answer in this post: https://drupal.org/node/1947732

From that post:

"The key is when you create the view, you need to set it to show content revisions rather than content. They mysql query used when showing content revisions is different than when showing content. One pulls data from the node table, the other pulls from the revisions table. The latter is what you want when dealing with revisions. In my testing so far, the Workbench Moderation: Current filter works fine in a content revision view."


How to generate block with Views, Entity Reference and Taxonomy Terms

Many thanks to @flocondetoile for responding, but I think the problem I posed was a join too far for Views. That is, whereas @flocondetoile needed to join:

parent-node -> child-node -> parent-node

I needed to join:

parent-node -> child-node -> taxonomy-term -> child-node -> parent-node

Try as I might I could find no way to do this directly in the Views UI. I did though find an elegant solution which I share here in case anyone else finds it useful.

Step 1

Save your query as a database view, i.e.,

CREATE VIEW view_name AS ...

Step 2

Describe your database view (or table) to the Views module. This is done by implementing hook_views_data (you can find the Views version in node.views.inc). It's a big method, but not too scary. In effect you just build up an array of meta-information about your database view. I based mine fairly closely on the code in node.views.inc. This step is described in some detail on this blog page, which also includes a worked example. Be sure to check out the slides linked at the bottom of the page.

Step 3

Views will now know about your custom database view/table. You can query it directly.


How to filter views result using the views_php module?

It is a Drupal bug that is in active state until date but there are some work-arounds, one of them I am sharing with, if it could help you out.
Use $data variable to access your fields value because $row only gives numbers, which appear to be node ID's (Drupal Bug).

Use the following code I wrote in Global:PHP 'filter code' text area

$field_code = $data->_field_data['nid']['entity']->field_code['und']['0']['value'];
$field_rank = $data->_field_data['nid']['entity']->field_rank['und']['0']['value'];

$math = ($field_code / $field_rank) * 100;
if ($math < '30') {
  return TRUE;
  // If you dont want to display the result otherwise use FALSE in place of TRUE
}

Use this code as it is in your view. It works perfect; I have tested it.


Sending an email to everyone with a certain role

If all you want to do is send emails to users of a certain role, you can use the Mass Contact module.  It enables a user to send an email to users by role or taxonomy. It is very easy to use, without any coding knowledge necessary. I have used it on a couple of business-related sites.

The other alternative is to use Simplenews. This is used mostly for sending email newsletters to lists of subscribers, if that is the kind of email you want to send.

But if you really want to use rules, I suggest you go through some documentation like this. Under the "Add a new action" of your rule, under the "System" section, there is a "Send email to all users of a role" action. That may be what you need.


Font Awesome not working in my sub theme of the Open Framework theme

Your html is perfect - I think you probably just need to include the font-awesome.css library file itself.

There are a few ways to do this. I usually just include this in my pages <head> section:

<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">

But some people prefer to actually download the font-awesome.css from fontawesome.com, place it in their theme folder and point to that.


You can use CSS background image concept to show images instead of Views & Comments text.

It should be very simple & straightforward ! You just need to identify the unique id or class in the html to apply css to that. Below article should be a good starting point for you !

http://stopdesign.com/archive/2003/03/07/replace-text.html


After study, I used the above css with a 'btn btn-primary btn-block' in the Other of my View (where the Rule itself goes) in the CSS information properties.  It for now gave me a working button, but it does need some further CSS, but I have my answer.

Additionally, I added :

/* Rules Link Post unvisited link */
.rules-link-post-classified
a:link {
    color: #FFFFFF;
}
a:hover {
    text-decoration: none;
}
a:active {
    text-decoration: none;
}

into my theme.css (using currently the Tweme Bootstrap).
As I wanted white text on a blue button, and then I used the above css with a 'btn btn-primary btn-block' in the other of my View in the CSS information properties.

Furthermore, I didn't want the 'hover' underline to show on the link when the user moved over it to click, so I used the text-decoration as 'none' to remove it under the 'a:hover' with 'a:active' elements above.
BINGO!

There maybe more functional CSS ways in the file.css, but hey we're learning!


As for any application, unless you are perfectly sure of what you are doing, are comfortable with it and have a good understanding of the inner working of the Field API and the SQL storage engine for fields, you shouldn't try to do your insert directly in SQL.

Instead, you should use the Node or Entity APIs to load your contents, update them and save them back in PHP code. This will be more expensive performance-wise, but much more easier to implement and maintain.


How is AJAX attached to exposed filters?

Still early rendering should be avoided whenever possible. Did you try to return the unrendered view in an ajax command?

  $view = views_embed_view('user_admin_people', 'page_1');
  $ajax_response->addCommand(new HtmlCommand('#wrapper', $view));

If you use the unrendered build array all the things you've described in the question like reattaching drupal behaviors, js, and css are handled by the ajax implementation in drupal, on the server side when assembling the response and on the client side when processing the incoming json data.

For this to work you also need to enable the option "Use AJAX" in the view user_admin_people, otherwise the "Filter" button rebuilds the form on a new page, which then happens to be the admin page.


when it's structure only, you will have to upload your dev feature, replace it with the production one and revert the production feature.


Cannot redeclare MyClass - but it's only declared once

When you are creating a custom module, you have to make sure your module registers its own namespace. In the current situation your module is attempting to use the namespace of the image module namespace Drupal\image\Plugin\ImageEffect;. Where you should actually be using a namespace of your own module namespace Drupal\mymod\Plugin\ImageEffect;

Then if you require functions of the image module, you can (as you have done already) load the other classes and functions with use. Like use Drupal\image\ConfigurableImageEffectBase;.


Send email to specific users when Webform submitted

This could be done by combining Rules and Webform Rules Modules
In Rules Module You could use the following Settings:
Events: After a webform has been submitted
Conditions: User has role(s) and Webform has name (to apply for particular webform)
Actions: Send HTML e-mail


How do I send a drupal_http_request() with GET method?

The first method is correct; you don't use url() to pass the data. Also, application/x-www-form-urlencoded is the content type used when POSTing data.

You could also use drupal_http_build_query() to build the data to pass.

$data = array('name' => 'value', 'name1' => 'value1');

$options = array(
  'method' => 'GET',
  'data' => drupal_http_build_query($data),
  'timeout' => 15,
);

$result = drupal_http_request('http://example.com/foo', $options);


How can I display the value of an addressfield in a single line?

I had to do the same thing a couple of days ago, this is what I came up with using hook_field_formatter_info() and hook_field_formatter_view():

function MYMODULE_field_formatter_info() {
  return array(
    'inline_address_field' => array(
      'label' => t('Inline Address Field'),
      'field types' => array('addressfield'),
    )
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $build = array();

  $count = 1;
  foreach ($items as $item) {
    $inline_address = "
Address $count
";

    $address_parts = array();
    if (!empty($item['first_name'])) {
      $address_parts[] = $item['first_name'];
    }
    if (!empty($item['last_name'])) {
      $address_parts[] = $item['last_name'];
    }
    if (!empty($item['premise'])) {
      $address_parts[] = $item['premise'];
    }
    if (!empty($item['thoroughfare'])) {
      $address_parts[] = $item['thoroughfare'];
    }
    // And so on for all of the columns that you're interested in, in the order
    // that you want them to be displayed.

    $inline_address .= '
' . implode(', ', $address_parts) . '
';

    $build[] = array('#markup' => $inline_address);
    $count++;
  }

  return $build;
}

It provides a field formatter you can pick for the address field on the node's "Manage Display" form.


How to create a theme date view with CSS styles?

I have my CSS to achieve this poster but I do not know how to add ??
how broken down the date for this display

Add 1 more Content: Even Date field.
Then for each Even Date field, select custom formatter.
for the first one put d (Note: there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change)

for the second one put F Y (Note: there seems to be a bug, you will have to do this twice, as when you save the 1st time it does not change)

Result

PS: You can add CSS classes to your field under the fields STYLE SETTINGS, no need to use template files to add css classes.

Then, for example, you add .cool { border: solid red; } to your theme's css file.


Sounds like you should look at the Printer, email and PDF versions module. It is designed to create alternate versions of your pages for print and documentation purposes. It allows you to specify different template files for the output, and you can customize it any way you wish.


How to push values from views attachment to Javascript?

It really depends on what you want and what data structure you have.
Normally I would say if you want only chart on the page/views, than create a new views type (Like block, page, etc) and then you can do whatever you want, and you can still attach it to another views. (I think this is it: https://www.drupal.org/docs/8/creating-custom-modules/building-a-views-display-style-plugin-for-drupal-8)
If you just want to show a chart side-by-side with some other data, maybe you need to create a new field (for views), than you can put there the stuff. (https://www.webomelette.com/creating-custom-views-field-drupal-8)
You can also hook in any time to a view, but it will make a mess after a while, however, every time you need to use the drupalSettings (Pass variable to drupalSettings) if you want to pass php data to javascript and some custom JS code to glue the ChartJS to the drupalSettings.


How to send an email to select set of users for moderation states?

you can maybe use rules module

alternatively create a custom module and you can inspire from this, that is used with core content moderation module:

use  \Drupal\user\Entity\User;

/**
 *
 *
 * Envoie de mail en fonction des transitions le modération de contenu.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 */
function my_module_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() !== 'content_moderation_state') {
    return;
  }

  $article_id = $entity->get('content_entity_id')->getString();
  $article = \Drupal\node\Entity\Node::load($article_id);
  if ($article->bundle() !== 'article') {
    return;
  }

  global $base_url;

  $article_title = $article->get('title')->getString();
  $article_url = $base_url . "/node/" . $article->get('nid')->getString();

  $author_name = $article->getOwner()->get('field_cn_ldap')->getString();
  $author_email = $article->getOwner()->getEmail();
  $current_user_uid = \Drupal::currentUser()->id();
  $current_user_name = \Drupal\user\Entity\User::load($current_user_uid)
    ->get('field_cn_ldap')
    ->getString();
  $is_author = ($current_user_name == $author_name);

  $uids = \Drupal::entityQuery('user')
    ->condition('status', 1)
    ->condition('roles', 'redacteur_en_chef')
    ->execute();
  ;
  $users = User::loadMultiple($uids);

  $emails_redacteur_en_chef = [];
  foreach ($users as $user) {
    $emails_redacteur_en_chef[] = $user->getEmail();
  }
  $emails_redacteur_en_chef = implode(',', $emails_redacteur_en_chef);

  $moderation_state = $entity->get('moderation_state')->getString();
  $moderation_state_original = '';
  if ($entity->original) {
    $moderation_state_original = $entity->original->get('moderation_state')
      ->getString();
  }
  $is_transition_change = ($moderation_state !== $moderation_state_original);

  include 'includes/notification/messages.php';
  include 'includes/notification/titles.php';
  $send_to = $author_email;
  $params['node_title'] = $title_mod;
  $params['message'] = $message_same_state;
  $send = FALSE;

  switch ($moderation_state) {
    case 'draft':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      break;

    case 'relecture':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      elseif ($is_transition_change) {
        $send_to = "joe@google.fr";
        $params['node_title'] = $title_prop;
        $params['message'] = $message_prop;
        $send = TRUE;
      }
      break;

    case 'relecture1':
      if (!$is_transition_change && !$is_author) {
        $send = TRUE;
      }
      elseif ($is_transition_change) {
        $send_to = "whatever@yahoo.com";
        $params['node_title'] = $title_relec1;
        $params['message'] = $message_relec1;
        $send = TRUE;
      }
      break;

    case 'relecture2':
      $send_to = $emails_redacteur_en_chef;
      $params['node_title'] = $title_relec2;
      $params['message'] = $message_relec2;
      $send = TRUE;
      break;

    case 'published':
      if (!$is_transition_change) {
        $send_to .= ',';
        $send_to .= $emails_redacteur_en_chef;
        $send = TRUE;
      }
      else {

        $send_to = "all@hotmail.com";
        $params['node_title'] = $title_pub;
        $params['message'] = $message_pub;
        $send = TRUE;
      }
      break;

    case 'maj':
      $send_to = "whatever@wahtever.com";
      $params['node_title'] = $title_maj;
      $params['message'] = $message_maj;
      $send = TRUE;
      break;

    default:
      break;
  }

  if ($send) {
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = "amu_dud_rules";
    $key = 'state_changed_action';
    $to = $send_to;

    $langcode = \Drupal::currentUser()->getPreferredLangcode();

    $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);

    if ($result['result'] !== TRUE) {
      drupal_set_message(t('There was a problem sending notifications.'), 'error');
    }
    else {
      drupal_set_message(t("A notification has been sent to $to"));
    }
  }
}

/**
 * Implements hook_mail().
 */
function my_module_mail($key, &$message, $params) {
  $options = [
    'langcode' => $message['langcode'],
  ];
  switch ($key) {
    case 'state_changed_action':
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $from = 'from@from.com';

      $message['from'] = $from;
      $message['headers']['From'] = $from;
      $message['headers']['Sender'] = $from;
      $message['headers']['Return-Path'] = $from;
      $message['subject'] = t('@title', ['@title' => $params['node_title']], $options);
      $message['body'][] = $params['message'];
      break;
  }
}


I ended up doing this with the Menu Position module and Menu Blocks module as well as Panels.

Create a Menu Block with

Parent item:

Menu: Primary Links
Item: <root of primary links>
Starting level: 2nd level (secondary)

Create a Menu Position rule:

Content Types:

Update

Menu item:

Updates

Add your menu block as panels content (if desired) to the nodes of the desired type.


Why don't content changes appear on front end?

Found I was saving it as a draft, not as published.


Theme Organic Group Entity Reference on user profile

You need to create an entity reference view and use it for your og_groups_ref field. In Views where you click Add, you will see entity reference view next to block, page etc.

Create the view to show the groups and the add fields for title and description. Place description above title and exclude it from display.

Rewrite the title in field settings to something like [title] -[description]. The replacement patterns are in the view field settings.

Go back to your groups audience field settings (main settings, not widget) and choose entity reference view instead of organic groups or simple. Use the view you created.


fetchAll Database query returns an error

fetchAssoc worked for you because of the result is an associative array.
fetchAll did not work because the result is an array of stdClass objects and JSON normalizer did not know how to return the data.
I think you will need fetchAllKeyed(0,0), but better play around a bit.
reference: https://www.drupal.org/docs/8/api/database-api/result-sets


View display nodes with taxonomy term found in URL

I gave up trying to understand why it doesn't work and resorted to using Has Taxonomy term ID instead.

The URL contains the taxonomy term ID so only a Contextual Filter is needed. In raw value the URL is taxonomy/term/[id] , so all that needs to be done is tell the Contextual Filter to Provide default value from Type Raw value from URL and Path Component 3. I also added a Specify validation criteria WhenThe Filter Value is available or a default is provided, of Validator Taxonomy term ID and chose the appropriate Vocabulary.


views - remove duplicates based on field value

I would use Views Distinct module to filter the duplicates out. The way this works is this:

you select the displayed view field,expand 'Views Distinct Settings' and select 'Filter Repeats'

So, for your particular case, if you want to show only the last payment method, order by payment method (ID ?) DESC, and on the order_id filter repeats. This way, only the last row for every order_id will show.


Try out the WYSIWYG Filter module. It allows to restrict all described things.

After installation you will be able to configure its settings in the "Input formats" section.


How to add the image url in the head tag

Or possibly a better solution - use the metatag module and you can customise this through the CMS globally or for specific pages. "og" stands for Open Graph so you just need to pop your data in the relevant open graph section

https://www.drupal.org/project/metatag


Why would some backup schedules work and others not?

By creating different destinations for each schedule, the problem goes away.

Apparently Backup & Migrate simply assumes each schedule has a separate destination (although the UI gives no hint that this would be the case, and in fact gives reason to expect that there's no problem with sharing a destination).

For instance, one of my schedules is set to keep 12 copies.  Rather than keeping track of which backups belong to which schedule, it merely deletes all but the last 12 backups in the directory.

At any rate, isolating each backup allows everything to work as expected.


Locked out of my local site after transfer

well you can first

drush upwd --password="yourNewPassword" UserName

to reset your password.

then you would need to remove the attempts so you can try to login again, you need to truncate the table flood.

TRUNCATE TABLE flood


Populate Dropdown list from a web service without code

I think you have to do it in code call the webservice in a custom module process the results and pass it to the template for display as you need


After having a look in the Contrib Module space, I would say no, it's not possible. The main problem as you probably already know: A file upload will break if you navigate away from the page.

However, if you have lots of time to invest in implementing this, I could imagine the following workaround: You could ajaxify your whole Drupal website, e.g. with ajaxify so that some outer elements of your page will persist while your navigation is taking place and your content is rendered inside a "content" element. You could then process the file upload in e.g. an iframe that resides outside of your "content" area.

Hope this helps!


Is there an easy way to have an image in a radio button label?

You can do this using CSS.

Add appropriated class from $form then use CSS to add images as background-image.

For example:

$form['example'] = array(
  '#type' => 'radios',
  '#title' => t('example'),
  '#default_value' => 1,
  '#options' => array(0 => ('Value 0'), 1 => ('Value 1')),
);

CSS

.form-item-example > labela[for=edit-example-0]{
      background-image: url('/path/to/image-0.png');
}


Your core directory is included in your .gitignore. I don't know which strategy you want follow but, like you have vendor, modules/contrib, themes/contrib, etc, you should launch composer install to download your core and contrib modules/themes in your workflow to complete your installation (your composer.lock should be commit).

If you prefer commit your modules, themes, profiles, libraries, core, etc., because some parts of your content are not managed by composer or because you don't want risk a bug of network during the build, you should remove these directories from your .gitignore and add them in your git repository.


The SQL would be something like:

UPDATE [field table] SET [field column name]=1 WHERE [field column name]=0


Uncheck Generate automatic URL alias problem

Check if "Path" module is enabled.  If not, enable it.  I think it is enabled by default.

And go to admin/people/permissions and check "Administer URL aliases" under "Path" section.


How can i make a new node title into a taxonomy term?

This article might help you sort it out with the Rules module.

Otherwise you would have to create your own module and look into the hooks mentioned here.


How can I reuse translations from other contexts?

The problem is that the set of i18n modules set the context for strings automatically.  For instance, suppose I reuse a taxonomy reference field in many content types.  The vocabulary name and each of the field labels are exactly the same and have the same set of translations, but each one must be translated entirely independently.  That field may also show up as an exposed filter in views and I have to translate it independently in each view as well.

Now suppose I mistranslated the vocabulary name for one of the languages and need to fix it.  I have to change it everywhere, which is a ridiculously tedious process.

It would be REALLY nice to be able to translate a particular string such as this once and have it automatically update everywhere that string appears.  I have been able to hack it by manipulating the locales_target table in the database directly, but that is definitely not a good solution.


Unknown option `--tail` when running `drush ws --tail`

It's all in the linked issue.

  Some existing Drush commands were simplified in Drush 9. I think that
  --tail would still be a welcome addition, if someone wanted to submit a PR.

But as of today the pull request is still unmerged. Maybe you can reanimate it and provide some help.


Can I automatically expand my paragraph item after the node creation?

I have done this before, I found out that the only way to do this is with jQuery. I did like this:

/**
 * @file
 * JS code for node/edit pages
 */

(function ($, Drupal) {

  'use strict';

  $(document).ready(function () {
    $('TARGET').click();
  });

})(jQuery, Drupal);


By default this puppy does not come with Views integration, perhaps it will soon in the near future.

For now, you will need to patch it, with this patch.


How to get a count of number of nodes created per month in views

I just figured it out:

Create a view for all nodes (filtered by type or status if
necessary).
I use a table layout, enabled aggreation, added field
"nid" with "Count distinct".
I then add a sort by "post date" with    "monthly" granularity.
Then I added a "post date" field with custom    format "M-Y". I
select "min" instead of "group results together. That's important, otherwise it will not group the results by month


switch views or hide block based on content type

It's possible with views:

#1 Configure field with images:

#2 Add contextual filter:

#3 Save the contextual settings and then add "No result behavior':

#4 You just need to display a default image in case the other content type than basic page, so you can apply the Unfiltered text, and type the html source of the image:

That's it!


Form is not being rendered in template file

Drupal render will return the html

drupal_render(drupal_get_form('form_id'));

you have to print the returned html as well.

print drupal_render(drupal_get_form('form_id'));

in your case

$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
drupal_render($form_template);

change it to

$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
print drupal_render($form_template);


If I understand your question, I think you want the Taxonomy Menu module:

  Custom Menu per vocabulary
  Uses the default taxonomy term path or custom paths
  Integrate with Views
  Integrate with Pathauto: use URL/path aliases
  Does not interfere with other menu modules

However, the last time I did this, I wrote my own module.  Essentially, I wired up taxonomy hooks to call menu_link_save() for new terms, and menu_link_delete() when terms were deleted.  This is a rather complicated process.  If you go this route, I would study the submit handlers for the menu module to see how everything works.  You also need to study the taxonomy API to see how to walk trees when you have a hierarchical vocabulary.


How to delete a webform submission in a custom module?

If you are calling this webform_submission_delete() function, then both the first and second parameters must be objects. At least the first parameter is a node object. Most likely you are calling this using:

$nid = 12345;
webform_submission_delete($nid, $sid);

instead of doing

$node = node_load(12345);
webform_submission_delete($node, $sid);

and as a result causing PHP to complain.

If you have doubts on how to implement webform_submissions_delete(), I suggest you take a look at the various functions that implement it for an example.


You can't xdebug in hook itself, you need to go to method calling this hooks which is in class ViewsData  path /core/modules/views/src/ViewsData.php
and put breakpoint in getData, clear cache and you will get what you need.


How to create a block of links shared by a user?

Just wanted to make sure you've tried this simple approach. Create a check-box field for the all posts (whatever content-type it is) you were referring to with options embedded or non-embedded and create a view with a filter to only display embedded content.

Edit: Have a checkbox for the content-type (responsible for posts) which asks anyone creating posts if they are using the oembed text filter, give a description to check "embedded content" if they are.
Then create a view and pull all the posts by setting the filter- "CheckboxName (isOneOf) Embedded content".


For general entity, yes you can use entity.manager service.

For user entity, you can use \Drupal\user\Entity\User. However in your case, you are going to load user by username, this can't be done by User Entity class, you have to use entity.manager.

user_load_by_name will call something like this:

$entity_manager = Drupal::service('entity.manager');
$user = $entity_manager->storage('user')->loadByProperties(array('name' => $nusername));

I will just use this function if there is no reason to replace it.
Use the session_manager service.

$session_manager = Drupal::service('session_manager');
$session_id = $session_manager->getId();


Views... two panes each contains a view.  One is the exposed filter, other is the fields.  How can they communicate?

Exposed filters are only linked to the view they were exposed on.

I haven't done this before, but I think the correct method would be:

Create a view
Expose any of the filters you need to on that view (not a separate one)
In the advanced settings of that view, set "Exposed form in block" to yes
Add the block to your panel (not a separate views pane)


How can I have profile edit pages displayed in admin theme?

The profile form is already designated as an admin route, so you just need to change the permissions for relevant roles so they can view that theme.

The specific permission you're looking for is:

  View the administration theme


Title changed programmatically is not put into breadcrumbs

drupal_get_title() gets the title from a PHP static variable, which is different from the variable $variables['title'] passed to the template files.

Your template hook would work if it uses the following code.

function lwt_preprocess_page(&$vars) {
  $path = drupal_get_path_alias();
  if ($path == 'scores/completion') {
    // -1-
    $vars['title'] = t('Completion');
    drupal_set_title($vars['title']);
    // -1-
  }
}

What happens is the following:

lwt_preprocess_page() is invoked, and (through drupal_set_title()) sets the static variable containing the value returned from drupal_get_title().
template_process_page() is invoked, and it calls the theme function for the breadcrumbs; in your case that theme function is lwt_breadcrumb(), which calls drupal_get_title(), obtaining the same value you set in lwt_preprocess_page().

In lwt_preprocess_page() you could also replace the code between // -1- with the following one.

    unset($vars['title']);
    drupal_set_title(t('Completion'));

The reason also this code works is that template_process_page() first checks if $variables['title'] is set; if it is not set, it calls drupal_get_title().

  if (!isset($variables['title'])) {
    $variables['title'] = drupal_get_title();
  }

References

theme(), for the order in which theme template hooks are executed
drupal_static(), for understanding how the page title is stored in a static variable accessible to any function


Maybe this post will help you out http://thereisamoduleforthat.com/content/recipe-extending-views-handlers-without-subclassing


How do I add field collection unlimited items from hook_form_alter()?

here in my below example i want to attach 5 images which will save in admin field collection , so here is code for it . here 109is node id in which i want to save field collection value. field_manager_update is my field collection name.

<?php $images = array(//images to attach to node
    '0' => 'http://cf.juggle-images.com/matte/white/280x280/drupal-logo-primary.jpg',
    '1' => 'http://cdn.flaticon.com/png/256/37187.png',
    '2' => 'https://www.drupal.org/files/project-images/logo-128x128.jpg',
    '3' => 'http://guillermocerezo.com/sites/default/files/field/image/drupal-logo_0.jpg',
    '4' => 'http://drupalcrafters.org/sites/default/files/DrupalCraft-logo_0.png'
  );

$node = node_load(109);

$field_collection_value = entity_create('field_collection_item', array('field_name' => 'field_manager_update'));

// Attach to the node
$field_collection_value->setHostEntity('node', $node);

for ($i = 0; $i < sizeof($images); $i++) {
    $file_info = system_retrieve_file($images[$i], 'public://pictures/', TRUE, FILE_EXISTS_RENAME); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      //$node->field_prop_land_image[LANGUAGE_NONE][$i]['fid'] = $file_info->fid; //assign
      $field_collection_value->field_prop_update_image[LANGUAGE_NONE][$i]['fid'] = $file_info->fid;
    }
}
// Save field-collection item.
$field_collection_value->save();  ?>

Hope it helps :)


Boostrap dropdown menu only working on parent page

Can you please try this:

Go to structure and then open your menu link
Enabled the "Show as expanded" option for your parent menu item.(in your case it is info menu item).

I hope it will work for you.


The whitelist that we used (which seems to work fine) is as follows:

master.drupal.org
master2.drupal.org
ftp.drupal.org
ftp-osl.osuosl.org
git.acquia.com  <-- we are using this repo for Drupal core, you may not need it

They may not all be needed, ftp-osl.osuosl.org in particular may be required by another part of our stack, but this represents a working list of required domains.


Drupal 7 Is the a way to programmatically know the Fields in a Content Type?

field_info_instances(); will get you a list of all field types on a specific entity/bundle.

For example:

$fields = field_info_instances('node', 'movie');
print_r($fields);

Will give you a list of all available fields on the node type of movie.


Need to sort views block by current node first

A quick solution might be using the module Views PHP.

As far as I understand your problem, you want to sort a list but have the current student at the top.

I used a Content Type name 'Students' with a integer field 'Rank', representing the field to sort the students.

Create your view and a block and set up your view as follows:

Format: as you like, no grouping
Show: Fields, no special settings
Fields:

Content: Nid (exclude from display)
Content: Title
Content: Rank

Filter Critera

Content: Published (yes)
Content: Type (= Student)

Sort Criteria:

Content: Rank (asc)
Global: PHP (asc) -> this is from the Views PHP module

Configure the Views PHP filter similar to this:
Sort Code (no php tags!):

$nidFirst = arg(1);
return $row1->nid != $nidFirst;

That's it. Embed the resulting block on your students page and navigate to one of those pages.

Sort criteria 1 gets the result into the default order, e.g. best rank is on top.
Sort criteria 2 fetches the current students node id (nid) from the url (assuminf it realy is the first argument), compares it to each row and returns true, if the rows nid is not equal to the current students nid.
As the sort direction is ascending, all rows with a comparison result of true will be moved below the row with the result false, so the current student ends up at the top of the list.


How do (or should) two separate modules implement the same external library using the Libraries 2.x API?

The Libraries module provides libraries_load which allows on-demand loading of libraries that are in sites/all/libraries. Libraries are defined by using hook_libraries_info.

It's a good idea to have a single module that defines hook_libraries_info() for a given library. For many modules, this is the primary module for Drupal. Take for instance Mailchimp or one of many commerce modules.

Alternatively, if you know that this module will be used by one or more modules that have no dependency on each other, you can define just a single module which defines the library and then have each module depend on that one.

As far as hook_requirements go, that is entirely up to you. I will say that if you do decide to put a requirement in each individual module, please namespace it. Lots of payment modules require the cURL extension and drop that requirement into $requirements['curl'] instead of $requirements['MYMODULE_curl'] this will cause a problem since requirements do not have an alter hook and a key collision will cause errors. So make sure you do the latter and not the former. However, if you're doing a single module, this wouldn't be a problem as you'd just do hook_requirements in it.


Menu links can come from 3 sources:

Views module (these can be exported when the view config is exported)
.links.yml file in a module (not possible to export)
Created menu links (Is content entities, like nodes, users, etc and is not possible to export)

I'm guessing you are creating menu links via interface, which is content. The config system can't export content, which is by design. If you wanted to synchronize content, you would need to look at the Deploy module suite. I'm not sure how well this is working atm, since it's still in alpha.


Getting a custom view of Twitter and Facebook posts

I have clients who require exactly the same feature, and the best method I have found so far is using Feeds and Feeds XPath Parser.

I create two Feeds importers that import from the RSS feeds of the client's Twitter and Facebook profiles. I set Feeds to create a node for each update (content type 'Social update') and use Feeds XPath Parser to populate the correct fields (title, body, timestamp, etc). I also set Feeds to automatically purge imported nodes after two weeks, and set it to schedule import on cron every hour.

Now I have each new post in a node, and I can display them however I like using Views.

This works ok, BUT I'm not convinced it's an optimal solution. I've looked at modules that interface with the Twitter and Facebook APIs for a better solution (e.g. Twitter Pull, Facebook Pull, Feeds Facebook Parser, Twitter) but they don't seem to provide a method for pulling Tweets and Facebook posts together in a single view or block. I'd love to get some more ideas on this.


Site building process: what is the relationship between CCK, Views, Panels, Blocks and Taxonomy?

Taxonomy and CCK are both used to customize content types. This first thing you usually want to do when building a site, is to figure out how the content types should be defined. With Drupal 7 you have entities instead which provides a more flexible way of defining data structure, but the idea is the same.

Once you have defined your content types, views, panels (or context) comes into play. Views is really good at making listings of different types, like the latest articles, nodes post by user X etc.

Panels can be used to piece things together, but as it's a very complex tool, it can also be a bit overkill to use. It was originally created out of a frustration with the Drupal block system, with all it's limitations. It if you want to use panels to manage blocks, you might consider using context instead as it provides the same functionality but is more lightweight. What panels is good at making lots of pages with very different layout. It has one advantage over context, and that is a more tight integration with views, allowing to use views not defined at blocks as blocks (panel panes).

So to sum up.

Define content types.
Create list/displays with views.
Piece it together with panel/context.


Links do not allow any callback action, you can not set a variable on click event.

Instead you can either make it a custom form, where submit button is themed to look like a link instead of link and on form submission set the value in session.

Or other way would be, if its not secured information, you can pass it as query parameter in URL.


You're probably not printing something required by the form since you are printing items individually. To start debugging, you can comment your entire form twig out and just use {{ form }} and see if it triggers validation.

At the same time, you are copy pasting the wrong thing in each error case:

      $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red')));
      $response->addCommand(new HtmlCommand('#email-valid', $text));

This will always apply to elements with .form-email class and #email-valid id.

You're trying to evaluate $lastname but that variable is never set. If the email validation error always shows, then validate that you are using the right key in $form_state->getValue().

Since you are applying it to the same id, you are going to overwrite your own message each time as well. Check the documentation on HtmlCommand. It implements jQuery's html(string):

  When .html() is used to set an element's content, any content that was
  in that element is completely replaced by the new content.

You need to provide different divs to print these errors for the users sake, or rethink how you are doing this.


Twig whitespace controls have no effect on fields

Although the whitespace control modifier is supposed to work for all {{ … }} prints, {% … %} statements and {# … #} comments I'd expect to make your sample work it needs to be put directly into the print like that:

{% for item in items %}
  {{- item.content -}}{{- not loop.last ? ', ' -}}
{% endfor %}

Alternatively you could try to use the {% spaceless %} tag. But again, I'd expect this only works right when placed inside the loop:

{% for item in items %}
  {% spaceless %}
    {{ item.content }}{{ not loop.last ? ', ' }}
  {% endspaceless %}
{% endfor %}

  As of Twig 1.38, use the |spaceless filter instead.


How to remove link from around the rendered entity inside view header

Here's the How:

 {% set headline %}
   {{ label }}
 {% endset %}
 {{ headline|striptags }}

as found here


Navigate to admin/config/development/logging and set "All messages, with backtrace information".


Using drupal 7 block from another website luckily on same server

Here's a Shared Blocks module for that purpose written by well known drupal community members.

  Features:

  Allows publishing and subscribing of Drupal blocks
  Changes to published blocks are updated on sites with subscription blocks
  Published blocks provides a JSON endpoint at sharedblocks/{module}/{delta}
  Block subscriptions are updated on cron with an adjustable refresh interval


Migrate Organic Groups from a Drupal 6 database to Drupal 7

The migration classes that come with Organic Groups are for doing a full site upgrade only. In other words, if you were to drag Drupal 7 files over top of your Drupal 6 site and run an upgrade, the migrate classes that come with OG would be helpful.

However, in your case (and mine) you are doing a full migration from an old Drupal 6 site to a fresh, empty Drupal 7 site. The classes provided by OG will not be helpful here, nor even show in your migration list.

What I'm currently doing is working on a manual migration path for OG groups using migrate_d2d to pull all the group nodes over. Then I'll write another migration to add users to these groups by injecting them into the right database tables. THEN as each of my other node types are migrated over, they will add themselves to the OG tables that track which content are part of which group.


How do I change/modify an update content message

On Drupal 6 you have Status Messages Alter, a port for D7 sits in the issue queue.

  Status Messages Alter provides developers with a new hook called
  "hook_message_alter." This hook enables developers to alter the text
  that is displayed in status messages before the messages are themed.


How can I construct an HTTPS POST with drupal_http_request?

You should only need to set it in the protocol.

$result = drupal_http_request('https://somewhere.com', $options);

Parameters

$url:
A string containing a fully qualified URI.

array $options:
(optional) An array that can have one or more of the following elements:

headers: An array containing request headers to send as name/value pairs.
method: A string containing the request method. Defaults to 'GET'.
data: A string containing the request body, formatted as
'param=value&param=value&...'. Defaults to NULL.
max_redirects: An integer representing how many times a redirect
may be followed. Defaults to 3.
timeout: A float representing the maximum number of seconds the function
call may take. The default is 30 seconds. If a timeout occurs, the error
code is set to the HTTP_REQUEST_TIMEOUT constant.
context: A context resource created with stream_context_create().


Drupal 7 change default user login functionality

I had a similar functionality in a project a while ago and I solved it by adding a validation handler and doing the check in that.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Replace the drupal authenticate function is it's used as validation.
  if (isset($form['#validate']) && is_array($form['#validate']) && ($key = array_search('user_login_authenticate_validate', $form['#validate']))) {
    $form['#validate'][$key] = 'mymodule_login_authenticate_validate';
  }
}

function mymodule_login_authenticate_validate($form, &$form_state) {
  // Set
  $account = mymodule_authenticate($form_state);
  if ($account) {
    $form_state['uid'] = $account->uid;
  }
}

function mymodule_authenticate($form_state) {
  // Your magic code here
  // In my project I either created a new user or updated an existing user and set $account as that.

  // And if everything went well in your code, finalize login and return account
  user_login_finalize($form_state['values']);
  return $account;
}


Drupal 7 ubercart roles assignment ineffectual

In case this happens to anyone else, when using the sandbox if configured so output becomes payment pending, role assignments will logically not work.

You just need to login to your developer paypal site and click on the test account you are using in settings and switch payment review to off.


I got it.
I used this code to alter the query and it worked.

$query->where[1]['conditions'][0] = array('field'=>"materials.ID","value"=>'1',"operator"=>"LIKE");


How do I mark translation strings as non-customized?

Based on 4k4's suggestion, I was able to do this with SQL:

drush sqlq < "UPDATE mydb.locales_target SET customized = 0 WHERE customized = 1;"

Warning: This will unset the customized flag for all strings on your site, but leave the customized translations in place.  This is what I wanted, but make sure it's what you want too before running the command.  Always make a backup, etc.


The insert block module implements an "input filter" via the core Filter module. A text format is a collection of enabled input filters. So when enabling a module that provides an input filter, the next step would be to configure the text format to use the input filter.

The Full HTML text format does not have that input filter enabled by default.

In addition the module has a Drupal 8 development release, but the code underneath still seems to use PSR-0 for its class loading and has not been updated in 3 years. It may be broken for other reasons as well.


How to prevent article titles to become links

To remove link from Title, what you have to do is click on the title field in views, and there is a checkbox Link to the Content. To unlink this, you have to uncheck this field. I am attaching a screenshot to it :


admin/structure/views/view/globalsearch/edit

Filter criteria > type maybe?


Display custom text if there is no comments

In your node.tpl.php you could check the $comment_count variable to see if there are comments. If so, render the comments, if not display your alternet text.

Example:

<?php if ($comment_count > 0 ): ?>
  <?php print render($content['comments']); ?>
<?php else: ?>
        <strong> 0 comments yet</strong>
        <?php echo l('Be the first','commentpath'); ?>
<?php endif; ?>


Can I add a description for Ubercart catalog categories?

In the catalog view, enable a Global:Text area in the Header, and set the input filter to PHP code.

The following code will print the term description and any associated taxonomy image in the view header.

<?php
$view = views_get_current_view();
$tid = $view->args[0];
$description = "";

if ( is_numeric( $tid ) ) {
  $term = taxonomy_term_load($tid);

  $description = $description . "
";

  if (isset($term->uc_catalog_image['und'][0]['uri'] )) {
     $description = $description . "uc_catalog_image['und'][0]['uri']) . "' class='term-image' /> ";
  }

  if (module_exists('i18n_taxonomy') && i18n_taxonomy_vocabulary_mode($term->vid) == I18N_MODE_LOCALIZE) {
    $description = $description . i18n_string("taxonomy:term:$term->tid:description", $term->description);
  } else {
    $description = $description . $term->description;
  }
  $description = $description . "
";
  print $description;
}
?>


If the only purpose is to have a a dev/test/live environment, you should just go with a service like Pantheon which provides all of those for you with an ease of maintenance.

If you want to host it yourself, here's the gist of what you do...

Make sure you only have one Drupal root. Can't stress this enough. If possible, also be on version control (git) as this will help immensely.
Create 4 separate MySQL databases. Would go with a naming convention of like CODE_dev, CODE_test, etc.
Inside of your sites directory, create 4 directories, each with their own settings.php and files directory. You can name them whatever, just keep it consistent for ease of use. ie, dev.example, test.example, etc. Add their database credentials to their settings file.
In your sites directory, you will create a file called sites.php. In there, you will assign a directory name to a URL. So if you used dev.example as the name of your development site directory, and your subdirectory URL looks like dev.example.com, the format will look like this:

$sites['dev.example.com'] = 'dev.example';

Do that for each directory/site.
In your registrar for your DNS settings, point all of the subdirectories to the same IP or path as the top level domain (example.com), which should be the Drupal root directory. From there, Drupal will take care of the rest.

I think that's it, but anyone feel free to correct me. As far as the themes go, put it in sites/all/themes so all sites will have access to them. If you want a site to only have access to a specific theme/module, put it in THAT site folder.

For example: sites/dev.example/themes/THEMENAME


How to add two extra buttons in a form to do extra actions with form data

Rather than write submit function for each button use $form_state['triggering_element']. This will provide you the which button is clicked with form data in default hook_form_submit


How to set a page level variable that views has access to

I must be addicted to Drupal because it is Christmas and I'm working on this, but here goes.

Delete the page display of your view so that only the master display is left. Then create a custom module with this code in it. (I created a module 'custom', my view is called 'zurb', and my path is 'zurb').

In custom module:

function custom_menu(){
  $items['zurb'] = array(
    'page callback' => 'custom_zurb_callback',
    'access callback' => true,
  );
  return $items;
}

function custom_zurb_callback(){
  $view = array(
    '#theme' => 'render_view',
    '#view' => 'zurb',
  );
  return $view;
}

function custom_theme(){
  return array(
    'render_view' => array(
      'variables' => array(
        'view' => NULL,
        'display' => 'default',
        'args' => array(),
        'regions' => array(),
      ),
    ),
  );
}

function theme_render_view($variables){
  $view = views_get_view($variables['view']);
  $view->set_display($variables['display']);
  $view->set_arguments($variables['args']);
  $view->pre_execute();
  $view->custom_regions = $variables['regions'];
  $view->execute();
  return $view->render();
}

function custom_preprocess_page(&$vars){
    if (current_path() == 'zurb' && count($vars['page']['sidebar_first'])) {
      $regions = array();
      $regions[] = 'sidebar-first';
      $vars['page']['content']['system_main']['#regions'] = $regions;
    }
}

Now in your views template file or views preprocess function you can access $view->custom_regions.

Perhaps there is a better way to pass the $regions to the view than adding it as a member on the $view object, but I don't see it being a problem. If it is a concern you can always just use drupal_static

This code is also re-usable as it uses a theme function.


Upgrading to  Drupal 7.7 produces a fatal error: What can I do?

The database.inc file does contain the definition of the class DatabaseConnection.

/**
 * Base Database API class.
 *
 * This class provides a Drupal-specific extension of the PDO database
 * abstraction class in PHP. Every database driver implementation must provide a
 * concrete implementation of it to support special handling required by that
 * database.
 *
 * @see http://php.net/manual/en/book.pdo.php
 */
abstract class DatabaseConnection extends PDO {
  // …
}

It is probable the file was not correctly copied, or has been corrupted during the copy; that would explain why the class has not been found, but the class is effectively present in the file that comes with Drupal 7.


How to add tabs to a form without a module

You don't say what you want in the other tabs but if you want tabbed blocks I would recommend using the quicktabs module.

It will allow you to create a quicktabs block that contains your custom block as one tab, and any other block/view/node in other tabs.

It will be far easier than making it custom.
It is a very widely used and stable module.


$block = array(
      'content' => drupal_get_form('mymodule_theme_form'),
  );


How can I conditionally add a parameterized variable to my themes based on URL?

You're on the right track: it'll be much more straightforward to stick this in a module where you have access to the menu system, and the most straightforward way to expose the data to the node template is through preprocess functions.

First, create an implementation of hook_menu():

function example_menu() {
  // Only two things specific to your case is page callback
  // and page arguments. Other options taken from node_menu(): customize as
  // you see fit.
  $items['node/%node/animal/%'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'example_animal_view',
    'page arguments' => array(1, 3), // Pass node object and animal ID
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  return $items;
}

Then create your callback, which will display the node as normal (including using the node template) if your animal check succeeds:

function example_animal_view($node, $animal) {
  if (animal_exists($animal)) { // Replace with your own check
    return node_page_view($node);
  }
  // Return a 404 if the check failed
  return MENU_NOT_FOUND;
}

Now, to expose the animal ID to node.tpl.php; you could either add it to the node object via the Field API, but in this case—since you're just using it for theming purposes—it's much easier to just add it to the template variables in a preprocess function:

function example_preprocess_node(&$variables) {
  if (arg(2) == 'animal') {
    $variables['animal'] = arg(3);
  }
}

You could do this last part in your theme, but I'd keep it in the custom module to encapsulate the functionality so it's available in every theme.

Finally, in node.tpl.php, just reference $animal.


Is there any option to import my excel to Views?

You can do by using PHP Excel module. This module is for handling the export or import of Excel files.