Class Term missing sometimes when used in myTheme.theme Using my theme file, I created a theme/template suggestion for taxonomies. I load a term object so I can know its vid. This was working and still works most the time. However, occasionally I get fatal errors. Which is a big deal. Similar to:

  Fatal error: Class 'Term' not found in myTheme.theme on line 4.

I am not sure why the term class isn't found, and only sometimes? Any suggestions on how to prevent this error?

Most of the time rebuilding the cache would fix this but not always.

myTheme.theme

<?php
function myTheme_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

The error is caused from the fact you didn't fully qualified the class name, which means you forgot the namespace of that class.

Or you use \Drupal\taxonomy\Entity\Term::load($tid); or you add a use \Drupal\taxonomy\Entity\Term; line at the top of the file. In this way, PHP knows where to find the class you reference.


entity_metadata_wrapper question I'm using this piece of code to programmatically alter a node field:

    $node_wrapper = entity_metadata_wrapper('node', 93);
    $node_wrapper->field_field4->set("text");
    $node_wrapper->save();

This code works when I'm testing with hook_init: Eg:

    function cust_init()
    {
        $node_wrapper = entity_metadata_wrapper('node', 93);
        $node_wrapper->field_field4->set("text");
        $node_wrapper->save();
    }

But it does not work when being called via hook_node_update or hook_node_presave or from a form submit handler. For example, after running this code:

function cust_node_update($node)
{
        $node_wrapper = entity_metadata_wrapper('node', $node->nid);
        $node_wrapper->field_field4->set("hello");
        $node_wrapper->save();
}

I'm expecting to see a change in my node, but I don't.

Is the hook_node_update the right place where this code should be added? What I need to do is to update a field of a node after a node is being updated.

Thank You.

The difference between hook_init() and hook_node_update()/hook_node_presave() is that the node is already in progress of being saved when either of the last hooks are invoked.

Notice how the argument to cust_node_update($node) in your non-working example is a $node object. In fact, it's a reference to the very node object about to be saved. This is important because only the data actually in that node object will be passed on to the database.

Your first line calls entity_metadata_wrapper() with the id of that node to create an object oriented wrapper around it. The problem here is that since you're only passing the id of the node, entity_metadata_wrapper() has no choice but to fetch a copy of that node from the database (or perhaps a cache, but that is irrelevant to the discussion). This newly fetched and wrapped node will be an entirely new object representing the same node, with no connection to the node reference passed to hook_node_update() or hook_node_presave(). Altering this new node object has no effect whatsoever on the node object already in progress of being saved. Both objects represent the same node data, but the one you fetched from the database and wrapped with an object oriented interface is a copy of the original node data.

Calling $node_wrapper->save(), node_save() or entity_save() inside hook_node_update() or hook_node_presave() is a bad idea because it tells Drupal to save the node already in progress of being saved, which would again invoke those hooks - but this time with a reference to the node object you fetched from the database. Your hook implementation will then again fetch a new object representing the same node from the database, before it has actually been updated, wrap it in an object and try to save it. Endless recursion is a fact and you're likely to suffer the White Screen of Death.

So, how do we fix this?

Jupiter's answer is on the right track, but it also works with hook_node_update() if that's what you want to use.
Calling entity_metadata_wrapper() and passing in the entire node to be wrapped will let the wrapper reference and alter the actual node object instance you pass in - containing all the latest information - instead of loading a copy from the database.

Calling $node_wrapper->save() would still trigger a recursion (this time without creating node copies), but you don't need to care about actually saving things because you're acting on the node reference passed to the hook implementation, which is the very same object Drupal will store in the database once the hook implementation has returned and a few extra tasks have been performed.

There's at least one gotcha when using entity_metadata_wrapper() in these hooks though, depending on whether other modules use the same hooks - or one invoked later than the one you implemented - to reorganize the node structure into a form that can be saved to the database more easily. The node may, in other words, be structured differently compared to when it's loaded using node_load() or entity_load(), depending on which modules you use. The easiest way to find out the structure of the node being saved is to use Devel module's dpm($node, 'node to be saved'); and inspect the structure before actually attempting to modify it.


Conditionally remove / blank out field values in View using Views PHP I am trying to build a map (IPVGM) of locations which will be used as a block appended to all entities of type Person. Locations are stored in a taxonomy, with an extra field to hold the coordinates. There are multiple fields in a Person that reference the Locations taxonomy (Field:birthplace and Field:other_locs), and I am trying to plot all of them on the same map. IPVGM can handle multiple locations per row, but the view I've been able to construct so far duplicates the birthplace in every row. This means that IPVGM constructs a map with (in this case) 4 birthplaces.

I'd like to use Views PHP to remove values for birthplace and birthplace coordinates in every row but the first one. I've had some luck trying to do this in the Output Code of Views PHP, but I think it needs to be handled in the Value Code area in order for IPVGM to pick up on the field values (or hopefully lack thereof). Any help? I looked at Views Distinct, and using a Global:PHP filter, but both of these would remove the entire row, when I only want to remove the birthplace & birthplace coordinates components.

Try to use Views Conditional.

Views Conditional is a simple module that allows you to define conditionals with fields in views.

Conditions include:

Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

Views conditional allows you to output text based on the result of the condition.


Disable reaching a node by its internal path I want a node to be reached only by its alias but not its internal path. The reason behind this is that I will create a node type, allow anon users to create such nodes, but the alias will contain a random text, so that only the user with the actual url information can revisit this page. Example:
www.example.com/node/9 -> only accessible by admin
www.example.com/34h356hrgc35yh4geg -> only accessible to anon users with this information.

If an anon user tries www.example.com/node/9, they should see Forbidden error or Not Found.

You can do this if speed is important in a middleware, checking if the request has no session and then block right away or in a request event subscriber after authentication checking for the path. Or a bit slower after routing if you want to include if the route matched is the canonical node route and use the node entity in your logic.

The easist but slowest is in a page preprocess hook. You can even do this in a theme. The cached page is varied by path and user permission by default and so the not found exception:

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    if (isset($variables['node'])) {
      $node = $variables['node'];
      if ($node instanceof \Drupal\node\NodeInterface) {
        if ($node->getType() == 'article') {
          $path = \Drupal::request()->getRequestUri();
          if (preg_match('#/node/\d+/*$#', $path)) {
            throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
          }
        }
      }
    }
  }
}

Because the 404 response is cached by the page cache the performance should be OK for most cases.


different options per user I have the following situation. A content type called cities holds all the cities in my country. A second content type holds all sales per city.

When a user logs in, I need him to see just some cities to which load sales. this means that a second user will see other cities.

How is this doable?

Regards,
Martin

after adding the custom field to the user profile, i added a hook_form_alter() in seven theme template. (it should be added in administrative theme).

in this hook i read the user custom field using $user_full = user_load($user->uid)

setting global $user; is required to use $user in template.php

now i can modify other forms according to user custom field content

that's all


View filter - Show content that has 1 field matching another field in current node I have a content type called Specifications which has 4 fields

Engine Specifications
Features Specifications
Variation (exposable filter)
Model

I also have another content type called Cars which has 1 field called Model too.

I am created a  SpecificationsView which displays the content-type Specifications as a block in Cars.

Is it possible to show in each Car the Specifications  whose model matches the current ''Car'' node's model?

I have done it using entity reference module and some php code in views.
All you need to do is use entity reference module make a view that list model taxonomy terms as entity reference display.

Then you need to add a er(entity reference) field in both content type and input in that view you just made then make another view that list specification fields add a relationship to add entity reference model field add a contextual filter taxonomy term id in provide a default value choose PHP code and paste this code :

$nid = arg(1);
$node = node_load($nid);
$term  = $node->field_model['und']['0']['entity']->tid;
return $term;

Or refine this code by yourself.


How to style every element in a theme? I created a theme from scratch and I didnt make a lot of changes to the theme template files which listed as below:

  block.tpl.php
  html.tpl.php
  node.tpl.php
  node--article.tpl.php
  page.tpl.php
  page--front.tpl.php
  views-view.tpl.php
  views-view-fields.tpl.php

A lot of styling that I made with HTML/CSS was missed up when I start creating contents and didn't appear as I expected.

Below code is used for getting the whole content, but how am I able to break it into artic title, article meta, article content body?

print render($content);

So I would like to know how am I able to edit the PHP files and giving styles to each element? Also some of elements that are specific for home page and category pages are shown into the article pages, so how shall I fix that too?

EDIT:
here is title's code from page.tpl.php:

<?php print render($title_prefix); ?>
<?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
<?php print render($title_suffix); ?>

and that's the title code from node--article.tpl.php:

<?php print render($title_prefix); ?>
<?php if (!$page): ?>

<a href="<?php print $node_url; ?>"><?php print $title; ?>

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

But still all articles getting its title styling from page.tpl.php and it is staying outisde of the div that I specified for the node--article.tpl.php file. So how to fix that?

Your question is very broad. As I understand it, you want to know how the Drupal theming system works ;)

If you want to style the output of a node then have a look at the default node template in order to find out, what variables are available.

Before creating a theme from scratch I find it highly advisable though, to look through the default core themes and some more popular contrib themes in order to understand different approaches. If it's only about some styling changes, you could also use a minimalistic theme and change it according to your needs.

  A lot of styling that I made with HTML/CSS was missed up when I start creating contents and didn't appear as I expected.

Is it possible that you use a wysiwyg editor for content editing and that this interferes with the CSS in your theme?

Edit:
The title in node--article.tpl.php will only be printed if the node is not shown as a full node (but in teaser view), e.g. no visiting /node/NID. That's controlled by the $page variable. Once again, please look at the default node template: node.tpl.php to see what variables are available and what they mean. If you visit /node/NID then the default behavior in Drupal is that the page title (the one used in page.tpl.php is set to the node title and displayed in the page template, not in the node template. You can change that off course, but you have to adapt the display logic inside the templates to match your needs. You could try something like the following.

In page.tpl.php:

<?php if (!isset($node) || $node->type != 'article'): ?>
    <?php print render($title_prefix); ?>
    <?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
    <?php print render($title_suffix); ?>
<?php endif; ?>

This will print the page title only if you are not on a node page or if the node is not of type article.

In node--article.tpl.php:

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

<a href="<?php print $node_url; ?>"><?php print $title; ?>

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

This will always print the nodes title whenever node--article.tpl.php is used, regardless if the node is displayed as a full page or as a teaser view.


Adding JS and CSS Dynamically to Override Theme In Drupal 7 I'm trying to add JavaScript and CSS to dynamically modify the content in a theme. I've spent a good amount of time going over the Drupal documentation, several Drupal books, and the questions/answers on here. I'm trying to pull it all together, but I'm not sure how close I am and was hoping to get some feedback/help. What I have done so far:

(1) Created a CSS file with the code below called knitr.css and put it in the css folder

pre .operator,

pre .number {
 color: rgb(0, 0, 205);
}

pre .string {
 color: rgb(3, 106, 7);
}

(2) Created a JS file with the code below called jquery.knitr.js and put it in the js folder (note, to save space I have removed the js code)

var hljs=new function()
hljs.initHighlightingOnLoad();

 })(jQuery);

(3) Added the following code into the preprocess_node function of the template.php file. Important: responsive and page need to be changed to your theme name and the machine name for your content, respectively.

if ($variables['view_mode'] == 'full') {
$node =& $variables['node'];
if ($node->type == 'page') {
$path = drupal_get_path('theme', 'responsive');
drupal_add_css($path . '/css/knitr.css');
drupal_add_js($path . '/js/jquery.knitr.js', array('type' => 'file',
'scope' =>  'header'));
 }
}

(4) Placed the follwong in the basic content page with as full HTML text format

1 + 2

## [1] 3

Expected output:

I expect the output on the page to look something like the following at this point. The JavaScript and the CSS should be changing the font color of 1+2 to blue (wasn't sure how to change color for example below). I'm getting no errors from what I've done above, but it is not implementing as expected.

1 + 2
## [1] 3

If the style sheet is used on all your pages, there's no need to load it dynamically with drupal_add_js(). Just put your style sheet into the .info file of your theme. The Writing theme .info files guide has detailed descriptions and links to more docs about this.
Your JS script looks fundamentaly wrong to me. Remove the script tag alltogether.
To add the JS script just add scripts[] = foo.js to your theme .info file. Look at the above mentionded guide, or here to get more detials.
What do you mean with basic content page.


I'm getting a page not found error when trying to visit my custom form This is the form that I created using Drupal 8:

namespace \Drupal\lookup\Form\lookupForm;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class lookupform extends FormBase
{
    /**
     * {@inheritdoc}
     */
    public function getFormId()
    {
        return 'lookup_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $form['Username'] = [
            '#type' => 'textfield',
            '#title' => t('ULM Username'),
        ];

        $form['actions']['submit'] = [
          '#type' => 'submit',
          '#value' => $this->t('Save'),
          '#button_type' => 'primary',
        ];

        return $form;
    }

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

    }

}

Routing file:

user.form:
 path: '/lookupForm'
 defaults:
   _title: 'Lookup User Autocomplete'
   _form: '\Drupal\lookup\Form\lookupForm'
 requirements:
   _permission: 'access content'

Info file:

name: Form
description: This is a form.
core: 8.x
package: Custom
type: module

I am getting a page not found error. What could be the issue?

Problem 1: Incorrect namespace. The class name should not be included in the namespace. Your namespace should be:

Drupal\lookup\Form

Problem 2: The name of your class is not the same name as the routing file (capitalization).

Class name: lookupform

Routing file: _form: '\Drupal\lookup\Form\lookupForm'

(Capital F)

Problem 3 (credit: laymannx) - you're visiting the wrong path. Should be visiting /lookupform (after fixing the above problems).


Programing date custom field into content type I'm building a module that creates a content type when it installs. I already have my content type, let's call it MyContentType and I have a field body that I created based on Drupal documentation (https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type) and I could create the two additional fields but I can't find a way to add a field of type date, datetime or timestamp. I tried to replace 'type: text_default' to 'type: datetime' but when I did it all my fields disappeared! I know I should also have a file named field.field.node.mycontenttype.field_date.yml with the correct configuration but what is the way to tell drupal that the type is datetime ? And how can I set it to current time?

field.storage.node.field_date.yml

langcode: en
status: true
dependencies:
  module:
    - node
    - text
id: node.field_date
field_name: field_date
entity_type: node
type: datetime
settings: {  }
module: datetime
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

field.field.node.mycontenttype.field_brand_information.yml

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_date
    - node.type.mycontenttype
  module:
    - text
id: node.mycontenttype.field_date
field_name: field_date
entity_type: node
bundle: mycontenttype
label: 'Date'
description: 'Date'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  display_summary: false
field_type: datetime

And then I referenced it like:

core.entity_form_display.node.mycontenttype.default.yml

langcode: en
status: true
dependencies:
  config:
    - field.field.node.mycontenttype.field_date
    - node.type.mycontenttype
  module:
    - file
    - path
    - text
_core:
  default_config_hash: qZE-qJ04DTTNggVVQdVOPQmpE_I69GQ_LqB32kXivVg
id: node.mycontenttype.default
targetEntityType: node
bundle: mycontenttype
mode: default
content:
  created:
    type: datetime_timestamp
    weight: 2
    settings: {  }
    third_party_settings: {  }
    (...)

and

core.entity_view_display.node.mycontenttype.default.yml

langcode: en
status: true
dependencies:
  config:
    - field.field.node.mycontenttype.field_date
    - node.type.mycontenttype
  module:
    - file
    - text
    - user
_core:
  default_config_hash: Nfnv6VMugBKl6EOqi_U0I_LQ1ZQpbNDN3a9GXHWUBz4
id: node.mycontenttype.default
targetEntityType: node
bundle: mycontenttype
mode: default
content:
  field_date:
    weight: 101
    label: above
    settings: {  }
    third_party_settings: {  }
    type: datetime

Thank you.

Like 4k4 suggested, I used https://www.drupal.org/docs/8/api/entity-api/using-the-ui-to-export-the-code-for-your-custom-fields to create and export all my needed fields and it worked really well.

Note: With a lot of changes you may need to delete config for the already created settings.
Remove it with: drush config-delete field.storage.node.field_name
Found that here


Where is archive-dump for Drush 9? I have drush 9 installed (current dev release). I can't find the archive-dump command, despite the docs suggesting it should be there.

Executing it produces:

  The Drush command 'archive-dump' could not be found. Use 'drush core-status' to verify that Drupal is found and bootstrapped successfully. Look for 'Drupal bootstrap : Successful' in its output.

I can confirm that drush core-status (or status) states that Drupal is successfully bootstrapped. The problem is present for local and remote environments, and on any machine that it's installed on (I've tried 4 so far, a mix of MacOS and Ubuntu environments).

I've even gone so far as to grep drush's code for mentions of archive and ard (the alias that used to work and also should if the docs are to be believed. There doesn't seem to be anything pertinent in there.

So where's archive-dump gone?? If it's been removed, what's its successor?

Turns out it was removed in this commit to Drush 9 following this issue and follow up.

So archiving no longer exists, or at least not until someone has time to port the logic over to the Composer workflow.


Template naming /style questions Good Morning,

I'm using a custom template for an area where members are logged in.  I would like to have a specific template for all pages of the Member content type. I've been able to do this with a page template a la page--node--11.tpl but I don't seem to be able to change the node template to include all the details of the page template (a la the side bars)

Any suggestions for how I can do this with a content type template.  I have custom configs for the sidebars and footers for this content type so I'd like to be able to use a general template and not one for each node.

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

For more information see Page templates depending on node type.


Setup a Tabular View to Include Total Count of Nodes Need to create a Views page displaying tabular data.

Fields I need are:

1) Total count of nodes created from Content Type A, filtered by US State, and the 2) second field is the total count of nodes created from Content Type B, filtered by US state.

Create two block display of a view. The view should contain All content types. displays are block_1 and block_2. set content type:Content Type A as filter criteria for block_1 and content type:Content Type B as filter criteria for block_2. so block_1 and block_2 shows all of the nodes of A and B. This link shows how to count number of results. Now the following code

<?php print views_embed_view('YourView','block_1');?>
<?php print views_embed_view('YourView','block_2');?>

outputs the number of results and you can format them in any way you want.


Separate panels variants for 'edit' & 'add' nodes of same type [D7/Panels 3]

I have two different panels layouts - one for editing, the other for adding nodes of the same content type ("Contact Details").

A panel page for overriding 'edit' pages exists in Panels (in code), which I have activated. I've made a variant which works for 'edit' pages, but it is also overriding the 'add' page with the same layout.

I've added a context of 'Node add form' with 'Contact Details' as the 'Node type'. Also added a selection rule:

Node: type / Node add form is type "Contact Details"

Both forms still appear in the same panel layout (the one for 'edit' pages).

Help much appreciated :)

Try using String: URL path in variant Selection Rule.

Edit path: "node/*/edit"

New path: use your content type path (node/add/your-content-type)


Webform variants as blocks Drupal 8.9, Webforms 5.x
I have a load of forms that are all basically the same, except for the confirmation URL (a download link, essentially) and some minor tweaks to the handlers.
In an effort to reduce duplication, I've been looking into the possibility of using variants for this. I can create all the variants easily enough, but I'm at a loss as to how to include these on the correct pages.
The form itself is included in the layout of the content type as a block and I can specify a specific variant there via default submission data (as per image) but that's a single variant for the whole content type rather than a specific variant for a single page.

What's the best way to do this? Is it actually possible with variants at all? Or perhaps there's some other solution I've missed

You could create a hidden redirect URL element, which is then used as the confirmation redirect URL.  The hidden redirect URL element can be populated using the 'Default webform submission data.'


How to make a form with latest nodes listing with checkboxes same as in 'admin/content' page? I want to create a custom module for newsletter composer in drupal 7.
To create a newsletter I need to show latest 100 nodes in a form with a checkbox and a dropdown (Select box) to select the section user wants to show the node.

In admin/content page same node listing appears. I need a select box within that check box, So need two elements in a row.

Please suggest me how to achieve the node listing table in a form with two fields and a node title in a row.

First off all you can see how this realize in /admin/content page.
The file /modules/node/node.admin.inc has a function node_admin_nodes()
This function returns form which contain list of nodes. The file has clear description and you can read and copy-paste code from this function to your module with necessary modifications.


Profile2 template for profile type? I have alredy created profile2 type with machine name "user" and now i would to overide template, can someone explain me how i have to name my new tpl? i ve copied existing, and tried some rename variants, but i didnt find solution.

In google i didnt find solution too.

Here is link for module https://drupal.org/project/profile2

To theme a custom template for profile2, try the following:

copy profile2.tpl.php from your module folder, to your theme's template folder
rename the file profile2--machine_name.tpl.php (profile2--user.tpl.php)
adjust the template as desired
clear the cache


How to keep "active" css on menu item when clicking on other link on same page? I have an issue with my main menu.
When you click on the "Cases by Topic" menu item, you are taken to the "Cases by Topic" page. The "Cases by Topic" menu item is then given the css class "active". I set it up so if a menu item has "active" css it is dark blue, rather than light blue to indicate it is the current menu item.

The page it's self has a drupal block that has a bunch of taxonomy menu items. Each one of these taxonomy menu items also point to this page but will load a different set of information in the page (which is a drupal view).

When they click on a taxonomy link in the block it reloads the page, but then the "Cases by Topic" main menu item no longer has the "active" css class on it.

Here is a picture example:

The user clicks on the "Cases by Topic" main menu item and the page loads. At this point the "Cases by Topic" menu item has the 'active' css class.  The user then clicks on a taxonomy link in the drupal block ("Access to Information").

The same page reloads, but now the "active" css is on the taxonomy link and not the main menu "Cases by Topic" menu item.

I would really like to have the "active" css class stay on the "Cases by Topic" main menu item, even when people click the links in the taxonomy block.

At the very least I would not have the taxonomy link just clicked have "active" css and "Cases by Topic" should keep that css class.

Any ideas?

You could consider using jQuery client-side to set the class based on path. See this post on how to do that: http://www.itworld.com/article/2832973/development/setting-an-active-menu-item-based-on-the-current-url-with-jquery.html

or you could try using Menu Trail By Path module
https://www.drupal.org/project/menu_trail_by_path


Block with single image at top I want to display an image at the top of my block. My block is a dynamic Views block, and it displays the top 5 latest news items. Is there any module to do so.

Also is it possible to rotate image and content within certain time interval (Eg. 1 hour).

You can have another view which selects that image. Then on your existing view you can add a header and choose "Global: View area". Then you just select the view you created earlier and that's it.

Another solution would be to have just another views block displaying that image.

The third solution would be to add an attachment (under Displays click Add > Attachment) instead of a new view block. Choose the fields (image in your case) and attach this (look for ATTACHMENT SETTINGS section) to your existing one.


How do i use a template file for my content type? quite new to drupal here so forgive me if things seems evident for you.i'm building onto an already existing site in drupal 7. the site is a onepager frontpage and from the frontpage there are links to various content types.
now i created a new content type named article.
when i link to such an article from the frontpage i (arrive at an article and) cannot go back to the frontpage through the menu anymore, while it does work with the other content types. I have searched and searched and made sure every setting is the same as the other content types but the links just don't work (they do nothing).
I did see in the templates folder that there are template files for each content type except the one i made. I'm wondering if that is the problem? If so, i don't know what exactly to do to keep it working though. I duplicated a template file and renamed it after node-article.tpl.php, but i guess it doesn't suffice.
can anyone assist?

Thx

function THEME_preprocess_node(&$variables) {
  print_r($variables['theme_hook_suggestions']);
}

put this code into you template.php this will give you the suggestions to make your tpl file.

And for your answer you just can print anything in you page.tpl.php file it prints then you just have to change in your page.tpl.php file


Cannot deal with multiple iterations of same form on one page I am designing a site that has a variety of points in which I need to render "workflow" buttons that are used to send actions to an external application.

I used the form API to generate these buttons, and am using the #submit => option on my buttons to direct specific button types to custom functions. I am also using hidden fields to house data that I use to facilitate the action.

The problem I am having is that these buttons can and should show up multiple times per page, for different aspects of the application, and whenever I click one of the buttons Drupal attempts to submit all of the forms.

I guess what i am asking is, how can I have multiple instances of the exact same form on screen at any given time, and know with certainty that the submit buttons are only going to trigger actions for the specific instance of the form they belong to?

thanks in advance!!

Edit

So here is the crux of the problem - it appears that the getFormId needs to return a unique value, but I cannot figure out how to pass unique values into it.

You could also add something like this to your form class

 /**
  * Keep track of how many times the form
  * is placed on a page.
  *
  * @var int
  */
protected static $instanceId;

/**
 * {@inheritdoc}
 */
public function getFormId() {
  if (empty(self::$instanceId)) {
    self::$instanceId = 1;
  }
  else {
    self::$instanceId++;
  }

  return 'my_form_id_' . self::$instanceId;
}


Better Exposed Filters I have created a view block to display filter options. But in BEF settings I dont get check box options. Can anybody help me out.

Thank you in advance
embeeke

I tried on my local with

drupal 7.30-dev
views 7.x-3.7
better exposed filter 7.x-3.0-beta4

Added term reference field in article content type. Created a view, added this term reference field as exposed filter i was able to get the checkboxes for tid.

Make sure the term reference field setting is set to "Dropdown" and Use Ajax options is set to "yes".

After setting term reference field setting to "Dropdown" i was able to see the "Checkbox/radio buttons" options in better exposed filter setting.


How to modify Parent Item under Menu Settings to display current language links only? We have a multilingual site where the menu links are based on the current locale. If 100 nodes are created in English and 50 nodes are created in Italian, for example, then when the locale is set to English, then the English menu link should display, but if the locale is set to Italian then i should only see the 50 nodes set to Italian.

The locale/language detection is based on URL so if the URL has ".com/en/" then the locale should be English, but if the URL is ".com/it/" then the locale should be Italian. As a result, the menu will display based on that locale.

The issue we are having is that on the Italian pages under menu settings, when i view the Parent Item Dropdown, i am seeing all the English menu links (whose language=en) displays with "(disabled)" next to it. All Italian links display as normal without "(disabled)".

Current example with language in parenthesis:

Parent Link (en)
Child Link1 (en)
Child Link2 (en)
Child Link3 (disabled) <-----this is an it (Italian)
Child Link4 (disabled) <-----this is an it (Italian)

The ideal scenario would be when i click on "Parent Item" dropdown that i only see links based on the current node's language (not other links assigned to a language that is different than the current node's language).

Expected behavior (if node's language = it):

Parent Link (IT)
Child Link3
Child LInk4

Expected behavior (if node's language = en):

Parent Link (en)
Child Link1
Child LInk2

I am not sure about settings, but I can suggest you way to do it programmatically.

You can use TEMPLATE_preprocess_menu_tree (replace TEMPLATE with your theme name) in your template.php of theme folder. Inside the function you can loop through the tree & validate it's translation with current site language & reset or set access deny if it doesn't match.


How to append a Value in cck field in a for loop? I want to keep a progress field in my content type so i can update value in it. But it doesn't take the previous value if saved in for loop.

for($i = 1; $i<=5; $i++) {
    $mynode = node_load(6);
    $myprevious = $mynode->field_progress[0]['value'];
    drupal_set_message("My Previous".$myprevious);
    $mynode->field_progress[0]['value'] = $myprevious." ".$i." ";
    node_submit($mynode);
    node_save($mynode);
}
$mynode = node_load(6);
drupal_set_message("My Value".$mynode->field_progress[0]['value']);
$myprevous_progress = $mynode->field_progress[0]['value'];
$mynode->field_progress[0]['value'] = $myprevous_progress.' end.'.$myprevous_progress;
node_save($mynode);

Output on page :

My Previous
My Previous
My Previous
My Previous
My Previous
My Value

Solved It by using

$mynode = node_load(6); //Load the node before for loop
for($i = 1; $i<=5; $i++) {
    $myprevious = $mynode->field_progress[0]['value'];
    drupal_set_message("My Previous".$myprevious);
    $mynode->field_progress[0]['value'] = $myprevious." ".$i." ";
    node_submit($mynode);
    node_save($mynode);
}
drupal_set_message("My Value".$mynode->field_progress[0]['value']);
$myprevous_progress = $mynode->field_progress[0]['value'];
$mynode->field_progress[0]['value'] = $myprevous_progress.' end.'.$myprevous_progress;
node_save($mynode);


Twig_Error_Loader error I have been running a Drupal 8 site with Pixture Reloaded theme, based on Adaptive theme
(in my .info file, the corresponding lines are:

'base theme': at_core

'subtheme type': adaptive_subtheme)

and suddenly, without having done any changes in the site code (just entered content), I get errors of type:

  The website encountered an unexpected error. Please try again later.

  Twig_Error_Loader: Template
  "themes/adaptivetheme/at_core/templates/layout/html.html.twig" is not
  defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to
  find template
  "themes/adaptivetheme/at_core/templates/layout/html.html.twig" in the
  Drupal theme registry.). in Twig_Loader_Chain->getCacheKey() (line 115
  of vendor/twig/twig/lib/Twig/Loader/Chain.php).

Also, I get similar error when trying to login in the admin, so I cannot clear any cache (if this could help). The site was working the same day earlier and the only thing I have done is enter new content (after having created a new view).

I would appreciate any help.

Eventually, I found out that some updates had been implemented in the theme and some modules and the problem was with the cache, not having been updated, so I run rebuild cache from Drush and the problem was fixed.


How do I hide the submission button basing on some conditions? I have a webform with a mandatory Yes/No button. I want to hide the submission button if No is selected.
How can I set up the logical condition for achieving this?

I just figured out that there is the 'Submit' element at the end of the webform elements under webform build tab and I can apply the conditions on that 'Submit' element.


How do I execute code when a module is installed or uninstalled? Currently, I manually have to add terms one by one every time a module gets installed, and that's not efficient. I'm writing a simple module that needs to automatically install 2 terms every time the module gets installed, and remove them every time the module gets uninstalled.

From Create taxonomy term programmatically on Drupal 8, I learned how to add terms. However, I simply don't know where to put the code. What must I do to achieve it?

Needs to go inside of mymodule.install file

<?php

/*
 * Implements hook_install()
 */
function mymodule_install() {

  // code that creates terms

}

/*
 * Implements hook_uninstall()
 */
function mymodule_uninstall() {

  // code that deletes terms

}


How to find which content types have comments enabled? I just want, quickly, to know which content types have comments enabled, without having to go from content type to content type and view the configuration page of each, especially if there are more than fifteen.

I searched but I found nothing relative, so I take the initiative to answer my own question.

MySQL seems to be the answer:

mysql> select type from comment c, node n where c.nid = n.nid group by type;
+------------------+
| type             |
+------------------+
| my_content_x     |
| my_content_y     |
| my_content_z     |
+------------------+

This can be equally used:

mysql> select entity_type, bundle from  field_data_comment_body group by entity_type, bundle;
+-------------+-------------------------------+
| entity_type | bundle                        |
+-------------+-------------------------------+
| comment     | comment_node_my_content_x     |
| comment     | comment_node_my_content_y     |
| comment     | comment_node_my_content_z     |
+-------------+-------------------------------+

All nodes which at least have one comment:

mysql> select type, n.nid from comment c, node n where c.nid = n.nid group by n.nid  order by type;
+--------------+------+
| type         | nid  |
+--------------+------+
| my_content_x |  115 |
| my_content_x |  90  |
| my_content_y |  521 |
| my_content_y |  295 |
| my_content_z |  127 |
| my_content_z |  11  |
+--------------+------+


Errors when trying to send e-mail when using Ubercart I am aware of the many other:

  Unable to send e-mail. Please contact the site administrator if the problem persists.

Questions that have been asked however, I believe my situation to be a bit different.

Situation:

I have been tasked to make some updates to my companies website. They are hosted and use cpanel for management. I have been working with the Drupal portion of the site and have been getting the Unable to send e-mail error when trying to do any of the following:

Create a user account
Retrieve lost password
Use any of the e-mail functions in Ubercart (order confirmation ect..)

Question:

Are there any settings that I should be looking to change or is this something that needs to be configured in a config file. I have set and e-mail up for (Home » Administration » Store » Configuration) in Ubercart.

Things I have tried:

I have set and e-mail up for (Home » Administration » Store » Configuration) in Ubercart. I have also set up the site e-mail (Home » Administration » Configuration » System).

So after much searching I came across this post:

http://shutterfreak.net/blogs/olivier-biot/2010-06-24/configuring-smtp-server-sending-mail-drupal

Apparently issues with the default SMTP are quite common. This post explains how to install and configure "SMTP Authentication Support module" and PHPmailer to basically override the default.

Worked great for me.


Is it safe to connect to another server to send form data? I have a standard D7 installation and I was wondering if it's safe to connect to another server to send form data. The way I see it, I'll need to make a page--<path>.tpl.php file and add my PHP at the very top of it. Are there any issues I should know about before doing this? Is this ok to do?

The form is for Anonymous users so no registration is required, it's just that the data needs to be sent elsewhere (another server). Yes, I've tried the Webform module but it's just not what I'm looking for. I'm thinking of using AJAX to send the data.

Any tips/suggestions before I go about this or should I just wing it? :-)

If you clear your required flow then a better solution can be suggested.

It is not a good practice to perform at page--path.tpl.php

Use hook_init in your custom module and check arg(1) to confirm your path.

Data can also be posted using drupal_http_request($server_url, $headers, 'POST', $data);


What's the best way to add an element to a form AFTER submission? I have a form that I'm trying to build that is semantically identical to billions of others on the net:

First GET request returns an empty form with no results displayed.
Submitting the form POSTs all data to the same page.
Server collects information from the database/other service based upon the submitted data.
Final response contains the same form with the fields still filled out, and a results table at the bottom.

But implementing this classic workflow seems to be impossible in Drupal 8.

I have been reading outdated documentation on the D7 Form API for what seems like forever, and have decided that it's probably best for me to implement a form that submits via AJAX and adds the results table to the page dynamically. But I'd like to know whether this would be the best approach, as well as other methods of doing what I want whether they're "better" or not.

I'd love to give you guys an idea of what I've tried, but the appropriate project files, as well as my brain, are so scrambled right now that I can't figure out what to show. So just some general pointers in the right direction would be very much appreciated.

Expanding that comment into a minimalist example code answer:

public function submitForm(array &$form, FormStateInterface $form_state) {

  // get the submitted data
  $foo = $form_state->getValue('foo');

  // call any other service to process your form submission values
  // (you can replace this with dependency injection of course)
  $bar = \Drupal::service('other.service')->baz($foo);

  // add results element to the $form

  $form['results'] = [
    '#type' => 'table', // or markup, or whatever you want to build your results
     // could also do #theme for a custom theme hook.
     // Use $foo, $bar etc however you want here
  ];

  // rebuild the form with your newly added results element,
  // and prevent drupal from redirecting to a separate GET page,
  // so that the populated form remains visible above the results.
  $form_state->setRebuild(TRUE);
  $form_state->disableRedirect(TRUE);
}


How to set the node ID to start with 100,000? I am running a new site with Drupal 7.

I want the node ID to start with 100,000.

How do I set it? I don't want the node start with node 1.

To make node IDs start from 100000, in a new site (which I assume doesn't have any nodes created yet), all that's needed is to run this SQL statement (assuming you're using MySQL, PostgreSQL or SQLite):

For MySQL or SQLite:

ALTER TABLE node AUTO_INCREMENT = 100000;
For PostgreSQL, and inspired by the accepted answer to "Reset auto increment counter in Postgres", it should be something like so:

ALTER SEQUENCE node_nid_seq RESTART WITH 100000;

Change the 100000 value in this SQL to any other value (like 123), to make node IDs start from that other value (like 123).

Caution when applying such change in an existing site, whereas the new node ID (like 123) is less then the highest node ID used already in your site. Because in that case you may get all sorts of effects you may not want/like ... Though in a new site (as in this question here) those effects don't apply.


Override user pages with a view Is it possible to override a user page with a view? I would like to override the user page to show all the nodes created by that user.

Views is not the right tool to use here, as views is for listing of content.

What you probably want is to use panels to take over the user page and display anything, like a view in it.


How to migrate one node into two nodes I have a D6 installation with a very large content type (i.e. a lot of fields) called field_data. I need to migrate the field_data nodes out of D6 and into a new D7 instance. This D7 instance has two content types called field_data and accomplishments. The accomplishments content type has a field that is a node reference to the appropriate node of the field_data type. Essentially I am exporting one content type and need to import each node as two nodes that reference each other. I have looked into the feeds module and don't see a way to do this. What is the best way to do this?

This will not be simple, as it is a requirement which is probably unique to your site. I know of no modules designed for this scenario. In general terms, you need to do the following.

Import the field_data content WITH all the fields into your D7 field_data type.
Create your accomplishments content type, and clone each field_data type to an instance of the accomplishments type, recording the nid of the source instance (field_data). Look at the Node Clone module to see how it is done. (Note: This module will not do this out of the box. You will have to hack it to do what you want.) You can probably use hook_node_presave to change the bundle and move the nid to the term reference field, then blank $node->nid to create a new node. Using Feeds or Backup and Migrate will not give you the nid for the node reference.
Delete the unwanted fields from the D7 field_data type.

You might also be able to accomplish this through direct manipulation of the database, but it is probably best to do it 'the drupal way' to avoid any artifacts which you might introduce in the direct query method.

Good luck.


why the search result shown in default language only ? i have a multilingual site with 2 languages and i have a search view , the search view works well in (english) and give me the result but when am changing the language to the second one ( arabic ) its give me the same result that i want but in english !!

English version:

Arabic version:

any suggestion to solve this problem ?

You should add a filter "Indexed node: language" and set it to "Current user language". This should be enough to ensure the results are shown in the current language.


Doing a global OR with the db abstraction layer I have a function that makes a db query using db_select. The problem I'm having is that in a function elsewhere, the query object is applied a couple of conditions, and I want to add an OR clause but the final query ends with an AND instead of an OR.

Simplified example:

function a() {
    $q = db_select('table', 't');
    $q->addField('t', 'field1');
    b($q);
    // Here I want to add an OR so that the query
    // Selects the conditions applied in b()
    // or something else
    $q->execute();
}

function b($q) {
    $q->condition('t.field1', 'some val', '=');
    $q->condition('t.field2', 'some val', '=');
}

The way this example is, it would compile to something like

SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val'

I want to make it so that it compiles to

SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val' OR t.field3 = 'some val';

And the OR should be added in place of my comment in a(). How would I go about that in a proper way?

Right now I'm solving it with

$q->where(' 1 = 1) OR (t.field3 = :v', array(':v' => 'some val'));

which compiles to:

SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val' AND (1 = 1) OR t.field3 = 'some val';

but I feel that is just ugly, not to mention potentially buggy.

Using db_or instead of the line above results in this:

SELECT field1 FROM table AS t WHERE t.field1 = 'some val' AND t.field2 = 'some val' AND (field1 = 'some val');

That because the db_or crease some sort of combo, and you have to add more than one condition:

$or = db_or()->condition(...);
$or->condition(...);

Finally, it would be great to go a step further and create a query like

SELECT field1 FROM table AS t WHERE (... AND ...) OR ...

Edit: The example here is very simple, compared to the actual code, and I can't really modify the b function. I need to do the OR right where the comment is in a()

It is possible to nest db_and() and db_or() calls, and pass the result into a condition() call. See Conditional Clauses documentation page for more information.

  The first parameter of condition() can also accept another conditional
  object. That inner conditional object will be incorporated into the
  outer conditional, surrounded by parentheses. The inner object may
  also use a different conjunction than the outer object. That way, one
  can build complex nested conditional structures by creating and
  building up conditional objects "bottom up".

  The db_condition() helper function will return a new conditional
  object. It takes a single parameter that is the conjunction that
  object will use. In general, the helper methods db_and(), db_or(), and
  db_xor() will cover almost any expected case. That allows conditionals
  to be inserted inline in a query for a very compact syntax.

function a() {
  $q = db_select('table', 't');
  $q->addField('t', 'field1');
  $q->condition(db_or()->condition(b($q))->condition('t.field3', 'some val', '=');
  $q->execute();
}

function b($q) {
  return db_and()
    ->condition('t.field1', 'some val', '=');
    ->condition('t.field2', 'some val', '=');
}

This should produce the query SELECT field1 FROM table t WHERE ((t.field1 = 'some val' AND t.field2 = 'some val') OR (t.field3 = 'some val')).


Custom form from scratch in template I have a paragraph that I fully themed into a contact form with the necessary  tags etc... Now my question is: How do I add the actual functionality to this? Because right now it's just plain html in a template without any logic handling the form submit.

You can use Drupal's default contact form and customize the fields as per your need which will have all the required logic for form handling. Then you can check and apply the theme as per your need to it.


Using node variables in another block? I'm trying to create a block which would include informations on the displayed node like author picture, name, and points (using Userpoints module), the creation date, and some other infos contained in created fields for certain types of nodes.

The thing is that I want to display this block in my sidebar-second (my theme is based on bartik, except that sidebar-second is included in the

).

But I don't manage to use variables available in files like node.tpl.php. For instance, when I try to display the author picture in the block, I write <?php print $user_picture; ?> but nothing appears...

Here's what I created on photoshop and I'd like to translate into Drupal (if it can help, and yes it's in French ^^) :

Thks !

EDIT : I'm using D7.

EDIT by nyoz :
Ok, so it seems like Multiblock is a good beginning. README.txt says the following :

  DEVELOPING MULTIBLOCK-ENABLED BLOCKS:
  Multiblock should successfully clone
  any regular block created with the
  block API. However, if you clone a
  regular block that implements a
  hook_block_save or
  hook_block_configure hook, the custom
  block settings of one block instance
  will overwrite the settings of
  another. To get around this, you can
  make a block "multiblock enabled." To
  do this, you should add a 'mb_enabled'
  key with a value of true in
  hook_block_info to each multiblock
  enabled block you are creating. Next,
  add an optional $edit argument to your
  hook_block_view and
  hook_block_configure functions. Once
  you do this, the instances you create
  will get the block instance ID passed
  in the $edit variable for the view,
  configure, and save $ops. This will
  let you save and load different data
  to different instances based on this
  instance ID. It is passed in with the
  'multiblock_delta' key with the
  following format:
  $edit['multiblock_delta'] = array(
            '#type' => 'value',
            '#value' => $block_id
        );

  Example implementation of
  hook_block_info: function
  hook_block_info() {
  $blocks['powered-by'] = array(
      'info' => t('Powered by Drupal'),
      'weight' => '10',
      'cache' => DRUPAL_NO_CACHE,
      'mb_enabled' => TRUE,   );   return $blocks; }

... So, I created a custom module containing :

function hook_block_info() {
  $blocks['content'] = array(
    'cache' => DRUPAL_NO_CACHE,
    'mb_enabled' => TRUE,
  );
  return $blocks;
}

I've also tried $blocks['main'] $page['main'] $page['content'] -with return $page-. BUT NONE OF IT WORKED (the block is still not multiblock enabled when I look in the instances list).

DO YOU HAVE ANY CLUE PLEASE ? Thks!

Try MultiBlock module.

  MultiBlock module solves this problem by allowing you to create
  multiple Block Instances of already existing blocks. Please read the
  README for more information.


How to use text from a block view as a prefix to a node title What I would like to do

In Durpal 7, I am using a block view to display our manufacturers name above our node titles. We added a custom region above content, and that is working fine. However, I would like the manufacturer to be display inline with the node title.

  How I handled it in Drupal 8

In this related question I asked about a Drupal 8 solution.The drupal 8 solution was a little simpler in that we migrated all manufacturer fields into 1 manufacturer field. which made things much easier to code. In my drupal 7 site, the manufacturer fields are separate making it a little messier to handle with code in that there would need to be an instance of the code for every manufacturer/node combo.

  My question

For drupal 7 is it possible to render a block view as an inline prefix to a node title? Placing a block view in this circumstance seems like it would be a much simpler and more front end Drupal approach. Especially since I can have all of the manufacturer fields in the one block view, and they will render according to Taxonomy term ID contextual filter.

So this is what I did, in case anyone wants to accomplish the something similar.

You first have to add a new region just above the content region in your MY_THEME.info file which in my case was:

regions[manufacturer_prefix_title]    = Manufacturer Prefix Title

Then I overwrote the page.tpl.php which contained:

  <?php if ($title): ?>

<?php print $title; ?>

  <?php endif; ?>

to each node instance I needed page--MY-NODE.tpl.php which now contains:

  <?php if ($title): ?>
    <?php print render($page['manufacturer_prefix_title']); ?>
  <?php endif; ?>

(The above required a preprocess_page hook.)

Then I created a block view, with the contextual filter set to NID. I also added filter criteria to get only the desired content types.

I added the 3 Content: Manufacturer fields, ticked exclude from display on each, and ticked rewrite the output of this field on each so that I could use the replacement pattern for those fields and wrap each one in the span class I wanted:

[field_MY_FIELD].

I also made sure to tick hide if empty under no results behavior so that the span class would not get rendered when the field was empty, as these fields  are not required.

I then added the Content: Title field once, and ticked rewrite the output of this field  and used replacement patterns for each of the manufacturer fields, leaving one space in front of the title:

[field_MY_FIELD_1][field_MY_FIELD_2][field_MY_FIELD_3] [title]

Since the contextual filter was set to NID, the title will only grab the appropriate taxonomy reference field, as only one is allowed per node.

Then all that was left was to simply place the new view block @admin/structure/block into the new region that was created in the MY_THEME.info file. I also configured the block to only show on the same content types that i defined in the filter criteria of the block view.

Hope this helps someone! :)


Theme specific taxonomy page I cant seem to find a proper way to do this, I found ways for d5 but nothing on d7 so I am asking how can I edit a specific taxonomy page in d7?

You can use template suggestion to override page.tpl.php for specific taxonomy term page. For this to work template suggestion file should be named page--taxonomy--term--[ID].tpl.php., where [ID] - ID number of taxonomy term for which you want to edit the page.

More on template suggestions: http://drupal.org/node/1089656


Using menus anywhere on page - how to stop them expanding by default when not used in menu region ( e.g. in a block or panel)? I am trying this with superfish but the menu options are expanded by default.

What would I need to do to get it to behave like it does in a menu (i.e. collapsed by default).

I want to use the menu drop down within the content (Edit i.e. within a panel or a block so that I can have drop-down menu functionality anywhere on the page (hence the tags).

The solution I chose in the end was to hand-code a drop down, based on the HTML markup output by a Views Exposed Filter form that I am already using (this also means that the look and feel is consistent).

So I created a block in the usual way and added the code shown below, and then in my 2-column minipanel added this block to the 2nd column and then added my minipanel to the panel page. The other column, 1st, of the columns contains the views exposed filter as discussed. See screenshots below, after the code:

<form>
<select name="field_type_value" class="form-select" onChange="document.location = this.value" value="GO">
<option value=""  selected="selected" disabled="disabled">Add something to our map!</option>
<option value="node/add/local-resource">person</option>
<option value="node/add/local-resource">organisation</option>
<option value="node/add/local-resource">project</option>
<option value="node/add/local-resource">wifi hotspot</option>
</select>
</form>

Other features in the code above:

Dropdown Form, when click on element, go to link without hitting a submit button - credit: https://stackoverflow.com/questions/4347080/dropdown-form-when-click-on-element-go-to-link-without-hitting-a-submit-button
Call-to-action "Add something to our map!" is not a selectable item in itself, so made this unselectable - credit: http://www.lattimore.id.au/2005/06/18/disable-options-in-a-select-dropdown-element/

Remaining thing to do:

The URLs each to call a different add content type form for each of the subtypes of content - I'll need to work out how to select a certain template from a URL or otherwise, but will be basing my customised content type form off this answer: How do you theme a content type's create/edit form in Drupal 7?


How do I migrate a Kickstart site from one server to another? I created a site using Commerce Kickstart.
Then I added all the products and stuff. Now I want to move this site on a new server as it is.

I have downloaded all the files from the original site. Also exported the database.

Is it possible to use these files and database to migrate the site on new server with different domain name as well as different database name?

If no, what should I do?

drush ard
(https://drushcommands.com/drush-7x/core/archive-dump/)
copy backup file to the new server
drush arr (https://drushcommands.com/drush-7x/core/archive-restore/)
done


Rewrite HTML title tag in Drupal 7 I want to change the title and title head html element. I have tried with drupal_set_title() but Drupal insists on adding the site name to the title output. How can I override it so the title reads exactly as I want?

You can change the page header title in template.php by adding the below code in template_preprocess_html().

 function my_theme_preprocess_html(&$vars) {
   if (current_path() == 'you_path') {
     $vars['head_title'] = t('header title');
   }
 }


How to show Forms in nodes stored in the node tables Mine is shared hosting account with limited CPU usage so I want to minimize CPU and mysql usage.
I'm generating 100,000s of nodes which contain some information. I also want to add a form in those pages. Since these nodes will be stored in node table how can I generate form on the fly? I think using filters but that'll not use Drupal caching hence it'll affect the shared hosting CPU quota due to this performance issue.

I don't want to use _menu to generate those pages on the fly because 1) it will slow down my site 2) It'll be difficult to use Drupal Taxonomy to classify "these" generated pages on the fly. Generating pages from the node table will be faster and also cacheable.

Another way is to insert the Form code in the nodes at the time of generation with the option that it won't contain/verify dynamically generated tokens(eg without #token) but it'll be security risk for my site.

What is the best way to handle this case?

What do you mean "generate form on the fly"? As in: the form for page "page/form" doesn't exist in a canonical state but is generated based on variables such as date/url/taxonomy? Or is it just the default values for the form etc?

In anyway: the options to have a form on a page are:

Hardcode HTML into the node content, e.g. <form><input> etc
Use hook_menu to create the page and use the form API
Use hook_menu to create the page and use the straight HTML
Use hook_nodeapi to add a form to the content with the Form API
Use hook_nodeapi to add a form to the content using HTML
Use a module such as webforms to add the forms

I would suggest either 2 or 4. When you say that hook_menu generates these plages "on teh fly": that's not true. hook_menu is only run on cache clear, and assuming you're using caching then the generation of forms isn't going to make much difference to your server. This may be a case where you're sweating about optimisation unnecessarily.

Using Form API gives you a load of tools that you'd otherwise have to handle yourself - validation, submission, sanitising, standardising, etc.


Clearing the cache_block in Drupal 8.x I'm currently porting a Drupal module from 6.x -> 8.x. One of the lines in that module:

  cache_clear_all('##NAME_OF_THE_BLOCK##', 'cache_block', TRUE);

The cache_clear_all method does no longer exist in Drupal 8.x. I cannot find now where the 'cache_block' is situated. I'm looking for a way to flush this cache - and I don't want to flush 'all' cache ...

Any idea's what the D8 equivalent of this line is?

The D8 equivalent is cache tags and it kind of works in the reversed way.

What exactly is changing that requires you to invalidate the cache? Identify that, if it has a cache tag (e.g. a config object or an entity) then just make sure your block adds the cache tag for it and you're done.

To figure out if a cache tag invalidation happens, you can truncate the cachetags table, then make the change and check that table for new entries.

If there is no cache tag yet for that event, then you can define one yourself, add it to the render array or getCacheTags() of the block plugin and invalidate it with Cache::invalidateTags().

I would not recommend to do what @Clive suggested because unlike 7.x, your  block plugin (assuming it is a plugin not just one specific block instance) can be re-used many times, even with page_manager/panels.


is it possible to search for user names with solr? I'm trying to allow users to be able to search and find their friends on my site.  I'm not sure how to do this. Could someone guild me please?

I read that solr is not able to search usernames so instead you must convert their profile to nodes..I installed Content Profile, and migrated but still no luck.  Not sure how to do this.

please help!

Thanks!

Regarding the Content Profile module, as long as anonymous users have access to view the profile nodes, the content should be able to be indexed by Solr.  You can use the Automatic Nodetitles and Token modules to ensure that the username is set as the Content Profile node's title. You might want to set the field bias for the title to a higher value so more importance is placed on it when ranking search results.

Normal users probably can't see the core User search because they don't have the "access user profiles" permission.  If they are granted that permissions they should be able to use the core User search.


Where are temporary files created? I want to know where Drupal (or its modules) create temporary files. Are they put in sites/default?

I'm especially talking about Drupal 6.

Files are created in the directory whose name is returned from file_directory_temp() which returns:

The value of the Drupal variable "file_temporary_path," which is set from the setting page on admin/config/media/file-system (Drupal 7) or admin/settings/file-system (Drupal 6).
If that Drupal variable is not set, then the function checks one of the following directories; if one of those directories exists, then it is returned (and used).

the directory returned from ini_get('upload_tmp_dir')
on Windows, the directories "c:\windows\temp" and "c:\winnt\temp."
on OSes different from Windows, the directory "/tmp."
on PHP version 5.2.1 or higher, the directory returned by sys_get_temp_dir().

If the variable "file_temporary_path" is not set, and the directories I listed in the previous point don't exist, or are not writable, the function uses the value of the Drupal variable "file_public_path"; by default that directory has the value conf_path() . '/files' that is the directory "files" contained in the directory containing the setting.php file used for the Drupal site.

The function set the variable "file_temporary_path" to the directory it found.

As far as I know, any module opens temporary files using a path starting with "temporary://" (available only in Drupal 7 and higher) or uses file_directory_temp(). The directory returned from file_directory_temp() can change from system to system, but modules always use that directory.

Drupal modules don't have the permission to write the directory containing the modules; it's quite difficult a module uses that directory to create temporary files. If you find a module that uses the directory containing the modules (or any sub-directory of that directory) report that as a bug.


How do I change language for a page? How do I change language from <html lang="en"> to <html lang="en-GB">?

Change default language to English on this page /admin/config/regional/language


Backport of hook_library() for Drupal 6? I've come to love the hook_library() of Drupal 7 as an extremely clean way of including assets etc. I'm fully aware of the many different ways to include assets intelligently (including the context_addassets module) but I'd love a near exact drop in backport for the hook_library() that Drupal 7 provides.

Note: Using mymodule_library() essentially defines a list of css/js (and their dependant libraries) which can be added in one simple call to drupal_add_library()

The module that originated the patch that introduced hook_library() in Drupal 7 is the jQ module (see Allow to add JS/CSS libraries (sets of files, settings, and dependent libraries). The hooks used by that module are different, but that is the module that is closer to what you are looking for. That module requires you to call a different function, but using drupal_add_js() would require you to hack the Drupal core, which is something it is never suggested to do, in the cases where you want absolute compatibility between Drupal 6 and Drupal 7.


Using Rules to publish nodes depeding value in Field I have been trying to figure out how to publish multiple nodes using Rules.

I have content type Parent and content type Child. When Parent is published then Child will be created/published too. This is what I have managed to do with Rules right now.

But now I have created field (list integer) to Parent. Choosing from list (value from 1-9) example value 4. Then Rules should create 4 Child nodes.

This does not work. It creates Child nodes randomly. Example choosing 9 from list it creates just one Child. And sometimes when choosing 4 from list it creates 2 Child nodes.

Apparently there is something that I dont figure out. What would it be? Any help would be appreciated.

Here is what I have in Rules right now:

  Rule to publish Child nodes when Parent is published

  Event:

  After saving new content

  Conditions:

  Content is type of. Parameter: Content: [node], Content types: Parent

  Actions:

  Fetch entity by property. Parameter: Entity type: Node, Property:
  Choose how many Childs, Value: [node:field-number-of-childs] Provides
  variables: Number of Childs (number_of_childs)
  Loop. Parameter: List: [number_of_childs]
  List item: Current list item (list_item)

  Create a new entity. Parameter: Entity type: Node, Content type: Child, Title: [node:nid], Author: [node:author]
  Provides variables: Created entity (entity_created)
  Save entity Parameter: Entity: [entity-created], Force saving
  immediately: true

Any help with this? Thanks!

Rules actually can loop based on array, and you have a integer only. Try Rules Array Create. Here is a issue about that.


drupal 7 users blog address selection I installed the blog module.
Now I want that each user before posting first blog, choose their blog address.
I want that they can choose their own blog address.
For example user A can select that his blog be on http://mydomain.com/myblogaddress.
How to achieve this ?

You should be able to do that adding a field to user, say Blog address field_blog_address. Then you can use tokens in pathauto pattern configuration page to set the blog path as [user:field_blog_address].


How To Assign Breadcrumb To Commerce Kickstart Omega Collection Or Category? How does one assign 'Collection' or other Taxonomy vocabularies to the Crumbs that Kickstart Omega uses. They give examples for Content Types but not for taxonomies.

So any pages based on taxonomies just show 'Home' as the breadcrumb.

I've looked in admin/structure/crumbs and the text pane seems to be correct for some tests I ran with the Debug tab. (ie. the item appears to be in the key menu.link_title.menu-specialties) but I don't know what to -do- with that information.

Maybe there is a -straightforward- tutorial on how to configure this text file?

Below is a screen cap of the crumbs screen I'm seeing.

Version:
First, i usually work with the latest Crumbs version from the 7.x-2.x branch.
If you have problems with the latest version, you should report them in the issue queue. But then you can downgrade either to 7.x-2.0-beta13 or to the 7.x-1.x branch.
Upgrade and downgrade should work fine (I think), but you should clear the caches if you do. Also I don't guarantee if your Crumbs settings are all kept or some of them are lost. Let me know in the comments :)
(Probably this paragraph will soon be obsolete)

Entity parent settings:
I don't remember how much of that is in the 7.x-1.x branch. But in the recent versions, you go to admin/structure/crumbs/entity-parent/taxonomy-term and configure the parent path. That's it.

Plugin weights:
The plugin will be available as crumbs.entityParent.taxonomy_term.categories on the weights configuration form. But probably you don't need to do anything there, the plugin will already be enabled through the general wildcard "*".


Restrict block to specific pages is broken when using view pagination I have a block I want displayed on a view page, which has filtering and pagination. The block shows fine when you change the filter, but if you go to page 2 (or any other page than the first), the block disappears. In the block config I have the following under "Only the listed pages":

myview
myview/*

How do I make it appear on all the pages in the view?

It turns out since my block was itself a view, it received the page param from the url, and since pagination was turned on, it just went to other pages, which happened to be empty.

I fixed it by turning off pagination on the block view.


Create a file programmatically I am working on a cron job that is creating a backup file.  I want to move the file to the private file directory but I am having trouble figuring out how to do this.  The cron job creates a file in a folder called /temp in the root of my site.  I've been trying to use file_save_upload to move the file, but this isn't working

$gzip_file = $_SERVER['DOCUMENT_ROOT'] . '/temp/myfile.gz';
$private_file = 'private://myfolder/myfile.gz';
$drupal_file = file_save_upload($gzip_file,array(),$private_file,FILE_EXISTS_REPLACE);

I am not getting an error and $drupal_file equals false.  The private folder exists and I can write to it with PHP.  Is file_save_upload the wrong function?  What do I need to do instead?

If it's an 'unmanaged' file, i.e one that doesn't have a database entry, you can use either

file_unmanaged_move or
file_unmanaged_save_data


Only show title of referenced node in a view if the node contains files in another field? Content-type-A has files attached. Content-type-B has a node reference to multiple Content-type-A's.

I making a view which is attached to Content-type-B. It needs to show each Content-type-A title that is referenced and also the files attached to each Content-type-A.

This is easy to do with relationships however I need the Content-type-A title to not be shown if there are no files attached to it.

So if I have this:

NodeB has a node reference to NodeA, NodeA2 and NodeA3.

NodeA and NodeA2 have a file attached but NodeA3 does not.

Then I need my view to just be this:

NodeA
-File from NodeA
NodeA2
-File from NodeA2

But its currently this:

NodeA
-File from NodeA
NodeA2
-File from NodeA2
NodeA3

Your view has all the info you want (and then some); simply override the view template or use hook_view_preview() to unset/hide the result you dont want.

There are many examples of this on the web and in documentation.


Displaying multiple child-grandchild-relationships properly through Views I am using the most recent versions of Drupal (7.14), Views (3.3) and the Entity reference module (1.0 rc3).

I have three content types. The first of them (parent) contains a node reference field to the second (child), which has a node reference to the third (grandchild). Each of these reference fields have unlimited values.

I have set up a block view, with relationships for both node reference fields, and have defined a contextual filter for the parent node id.

This is what I want to display in the parent node, each with summaries and a few other fields from the referenced nodes:

Child 1
Grandchild 1
Grandchild 2
Grandchild 3

Child 2
Grandchild 4
Grandchild 5

With displaying an unformatted list of fields, I get the following result (aggregation doesn't help at all):

Child 1
Grandchild 1

Child 1
Grandchild 2

Child 1
Grandchild 3

Child 2
Grandchild 4

Child 2
Grandchild 5

Any suggestions for how I can get the display that I want?

So you've tried going into your 'Settings' for the unformatted list style and setting a 'Grouping field' already?

If not, try the following, and make sure to check the box I've checked here as well:


How to hide certain links in forum? I am wondering what is the best way to preserve viewing certain url patterns in forum posts only for authenticated users? So that guests can see something like "please log in to view the link", as per most stand-alone forums?

Im not finding a module for that but what I would do is use jQuery to convert all links tags and their content in the "Content area" to [Please login to view this link] this is only loaded if the user is anonymous.

The function .replaceWith() http://api.jquery.com/replaceWith/ can be used


Disable user registration in /user/register, but allow registration during commerce checkout? Only users who paid can finish registration and they get a role applied to their user.

Problem is that, users can still register through default registration form.

Disabling registration for in Account settings will disable the registration globally everywhere?

How to disable it only in /user/register? But allow during commerce module checkout process?

You can do that with hook_menu_alter() by changing the access for that path:

function MYMODULE_menu_alter(&$items) {
  $items['user/register']['access callback'] = FALSE;
}


Change user field value to value of another user field I manage a basketball league site with two main user roles, "commissioner" and "player". Every player on the site is assigned to both a Tuesday team (field_team) and a Friday team (field_team2) via a user field, which is editable by commissioners. Because of player absences and other variables, the teams are usually different by the end of the week, so there are also two additional fields, Tuesday default team (field_tuesday_default) and Friday default team (field_friday_default).

See below for an example of what my Tuesday games page looks like to commissioners:

We start each week with a clean slate, i.e., every player back with their default team. Currently, at the end of each week our commissioners have to manually edit every player's user account to get their Tuesday/Friday team values back to the default.

See below for what a player's edit account page looks like to commissioners:

The problem is that it takes a long time and it is very tedious for commissioners to manually edit every player's user account to make their team values equal to their default team values.

Is there a way to programmatically change every user in the "player" role's Tuesday team and Friday team field values to equal their Tuesday default team and Friday default team values? All my research thus far has come up empty and I'm really at a loss at this point. Ideally, I would like to put a nice, big reset button on the Tuesday/Friday games pages that will perform the reset. Any help would be appreciated! Thanks.

Yes

Programmatically you have to create a custom form with submit button as the only field, now inside the submit handler it will be 2 step process something as below

following code I have written just to give an idea, and assuming field names in a way you can relate. You have to do the tweaks to make it work for you

/**
  * Form Builder
 */
function _my_module_reset_team_selection($form, &$form_state) {
  $form = array();
  $form['reset_options'] = array(
    '#type' => 'select',
    '#title' => 'Reset Options'
    '#options' => array(
      'both' => 'Reset Both Teams',
      'ft'   => 'Reset Friday Team',
      'tt'   => 'Reset Tuesday Team',
    )
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Reset',
  );
}

/**
 * Submit Handler for your custom form.
 * 2 step process 1. Find Users to Update. 2. Update :)
 */
function _my_module_reset_team_selection_submit($form, $form_state) {

  // Logic to decide if to reset both or any one
  // possible values as 'both'/'ft'/'tt'
  $reset = $form_state['input']['reset_options'];
  // Step1. Get All the Users who are part of any team.
  $users_to_reset = _my_module_get_users_to_reset($reset);
  if (is_array($users_to_reset) && count($reset)) {
    // Step2. Update to Reset.
    switch ($reset) {
      case 'both':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_tuesday[$user->lang][0]['value'] = '';
          $user->field_friday[$user->lang][0]['value'] = '';
          user_save($user);
        }

        break;
      case 'ft':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_friday[$user->lang][0]['value'] = '';
          user_save($user);
        }
        break;
      case 'tt':
        foreach ($users_to_reset as $user_to_reset) {
          // For better performance you can use field_attach_api here**
          // I am using user_save() process
          $user = user_load($user_to_reset);
          $user->field_tuesday[$user->lang][0]['value'] = '';
          user_save($user);
        }
        break;
    }
  }
}

/**
  *  Helper Function to get list of users to reset.
  *  Allows you to reset any of two Tuesday Team or Friday Team or both.
 */
function _my_module_get_users_to_reset($reset='both') {
  $get_tt_users = array();
  $get_ft_users = array();
  if($reset != 'ft') {
    $get_tt_users = db_select('field_tuesday_team','tt')
                 ->fields('tt',array(entity_id))
                 ->condition('tt.entity_type','user',"=")
                 ->execute()
  }               ->fetchCol();
  if($reset != 'tt') {
    $get_ft_users = db_select('field_friday_team','ft')
                 ->fields('tt',array(entity_id))
                 ->condition('tt.entity_type','user',"=")
                 ->execute()
                 ->fetchCol();
  }
  $users_to_reset = array_unique(array_merge($get_tt_users,$get_ft_users));
  return $users_to_reset;
}


Grouping Node Comment in Views I am trying to set up the following in Views:

Review 1
-Example Field
-All Comments of the Review

Review 2
-Example Field
-All Comments of the Review

I'm pulling in the comments from a relationship. However, rather than grouping all the comments under the review, it duplicates the Review:

Review 1
-Example Field
-Comment 1

Review 1
-Example Field
-Comment 2

And so forth. How can I group all the comments to not duplicate the node, and just appear in order and grouped for the review node?

I know an old post anyway. There two solutions to this, here is one, but for this you need to define the type of the view as comment view right from the start, However another solution is that (Assuming Review 1, Review 2 are nodes being pulled and a relationship is set on the comment and node), right below the Title block you have the FORMAT configuration block, set it to Unformatted list and to display the fields (Notice: I have not tested on other formats such as table etc), click on Settings after the |pipe symbol and you can see Grouping field Nr.1  with a drop down, choose nid as your grouping method. In other cases there might be Grouping field Nr.2/3.. and so on. This should be able to group all your comments together for a node.


Feed Import Products ( Commerce ) and Products Category ( Node Page ) I need to create a CSV feed importer to import both Commerce products and products category node using single table and I am using Commerce Feed Module... when I create it using two different tables I can easily achieve it using Feeds Tamper Module (using explode plug in)

But when I implement single table structure as mentioned in the image... since the title is not unique it creates multiple nodes for each product... Is there any other table structure to implement this..

But what I actually need is:

Display1- A, SKU1|SKU2|SKU3

Display2- B, SKU4|SKU5|SKU6

Display3- C, SKU7|SKU8|SKU9

Is there no one familiar with this or done this before.. ??  or else I have to refine the question.. ??

The following CSV template and Feed Import settings will import 1 Product Node with multiple Product Entities being referenced.

Step 1 - Creating The CSV

The following example provides the title and product_variation headers...

title: Mapped to the Node Title field in Feed Import

product_variation: Mapped to the Commerce Product Referenced field. Field limit should be greater then 1, so multiple entities can be imported.

title,product_variation

Product Example,"product_sku-1|product_sku-2"

Step 2 -Import Node

The "|" is used to create a unique entry using the Feeds Import Explode plugin.

The Feed Tamper product_variation field should have a single Plugin called Explode with the String separator set to "|".

Essentially, the Feeds Tamper Module will prepare the column values into an array, so Drupal can handle the request all awesome like :)


Main Menu vs Navigation Menu Is there a commonly accepted "best practice" for how to use the "Main Menu" vs the "Navigation Menu"? The descriptions in Core add to my confusion:

"The Main menu is used on many sites to show the major sections of the site, often in a top navigation bar."

vs

"The Navigation menu contains links intended for site visitors. Links are added to the Navigation menu automatically by some modules."

I don't intend to start a debate. I'm curious if there's a best practice for how to use these, or is it entirely subjective?

My personal opinion is that this is pretty subjective.

We typically just use the main menu for just top level section links (ie, all links are at the top-level and don't have children), and then will have a menu per site section.  We will also typically have a sub menu for extra header links and extra footer links.  Our theme will take care of displaying the proper menu on pages.

Keep in mind that we also do highly custom themes for large sites, so this scheme may not apply for your needs.


How can I add previous and next controls to the views slide show? I have the photo slider on home page using views-slideshow. Now I need to add previous and next controls to that slider. How can I?

I done it through css code, just follow this steps

#views_slideshow_singleframe_prev_gallery-block_1, #views_slideshow_singleframe_next_gallery-block_1 {   width:71px;   height:0px;   padding-top:71px;   position:absolute;   top:100px;   overflow:hidden; }

#views_slideshow_singleframe_prev_gallery-block_1 {   background:url('images/left-button-on.png');   left:0px; }

#views_slideshow_singleframe_next_gallery-block_1 {   background:url('images/right-button-on.png');   right:0px; }

 #views_slideshow_singleframe_playpause_gallery-block_1 {   display:none; }

And also take a look at https://drupal.org/node/691984


Why is access to some of my product displays denied for anonymous users? I think I have some database corruption and a number of commerce display nodes have have become access denied for anonymous users. I am not using any access control modules and the problem persists even after allowing anonymous users to bypass content access control. Clearly there is something badly wrong.

I have clear caches etc, to no avail.

What could be causing this and were should I start looking for a fix?

Following the suggestions given in comments, I have tried rebuilding permissions and this does not help.

I have the same problem. It`s because product entity was unpublished.
After publishing entity all warks correct.


'Any' result set for Exposed Filter w/ limited list is not limited I have an exposed filter for a taxonomy vocabulary. The filter settings are

Single Filter
Operator: Is one of
Limit list to selected items: On
Selected vocabulary terms: a subset of the full, flat (non-hierarchal) vocabulary

Assume selected terms term1, term2, term3
Assume non selected terms non1, non2, non3

The filters UI appears and is accurate, and it is functional when a filter is selected. However, when the - Any - option is selected, all objects from the vocabulary are displayed - all of the term# objects are displayed along with the non# objects.

I've tried adding a second (non-exposed) filter that does is one of for each of the term# terms. With this, the - Any - option is correct but none of the other selected filters in the drop down work.

How do I get only the selected term# elements to show when the - Any - option is selected?

For the second non-exposed filter change the operator to is none ofand assign the terms accordingly (inverse to what you have now). If not otherwhise specified filters in views are AND filters.


Site stuck on maintenance mode only for a single page On a live, multilingual (fr/en) client site, I've just update Drupal 7 to its latest version (along with a few modules). Everything went fine, except that, even though the maintenance mode has been disabled, the maintenance page still shows up on ONE specific URL of the public site.

www.domain.com/ -> OK
www.domain.com/fr -> !!! maintenance page
www.domain.com/fr/ -> OK
www.domain.com/en -> OK
www.domain.com/en/ -> OK

(All the other pages are OK, as far as I can tell.)

I've tried clearing all caches multiple times, and I tried running update.php again, with no effect.
Following other answers, I've also checked the database (cache_bootstrap and variables), but as far as I can tell, everything is normal there too.

What's wrong?

UPDATE
Problem solved, although I haven't done anything in particular. Maybe it was caused by some third-party caching mechanism (e.g. from the hosting provider). Will look into that if the problem occurs again.

I came across this scenario a few days back. In my case, the site was displaying maintenance page only on registration related pages in dev server.

After several hours of struggle, it was identified to be a huge secondary database (from PROD) which was connected only on enrollment related pages. I emptied the huge tables and the pages started loading seamlessly.

Hope this might help someone.


Adding dynamic markup to menu items In Drupal 7, how can I add additional dynamic markup to a menu item?  As an example, I'm trying to show the number of nodes 'needing attention' to the right of link in my primary navigation as noted in the attached graphic.

It seems like a theme function would be appropriate here, but I'm struggling to find which hook I should be implementing.

Hope this will help you,

As answered theme_menu_link OR theme_menu_tree wil help you to do this. If you go through the above links you can get an idea to change the html of required menu item.

On page load:

for example im using theme_menu_link in template.php refer this code. Node count will be update on every page load, if any changes.
I have updated l() for you requirement. For example I have used a simple function , modify the function as per your requirement.

$output = l($element['#title'] . ''.get_node_count($parms).'', $element['#href'], array('html'=>TRUE));

function get_node_count($parms){
    //you code goes here for get node count
    return $node_cnt;
    }

If you don't want on page load, it can also be done using ajax callback, but not preferable to make ajax callback again and again.

If you want to do refer ajax callback, then the only change has to be done in the l(). Add the unique menu id, which is used to show the node count for the corresponding menu id.

$output = l($element['#title'] . '', $element['#href'], array('html'=>TRUE));

On sucessfull ajax callback you have to update the node count for each menu.
using
...
success: function(data) {
// Change node count
$('#menu_title__node_count').html(data);
}
You will get the class for each node count, you can style as required. And also you can add a common class for common style, based on your requirement.


How can I make the label text on a Views Exposed Filter inline? In Views 3, it's easy to make the labels of fields appear inline by adjusting the settings at Format: Show: Settings.

However, there appears to be no corresponding setting for Exposed Filters.  I tried to do it myself in CSS,  but adding:

#edit-field-acc-gender-value-wrapper label

gives me the horizontal alignment but not the vertical alignment, as you can see below:

How can I fix my CSS, or is there a better way to make the labels for Exposed Filters inline?

You may give a top margin to the label:

#edit-field-acc-gender-value-wrapper label{
margin-top: 5px;
}

It is not the best way but it will work.


how to style navigation sub-menu? I need to display dash (-) in front of each sub-menu element. For example, the output should be

Home

About

- Process

- Process 101

- Compnay

Useful Links

I tried the following:

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
     $sub_menu = drupal_render($element['#below']);
   }

   $output = l($element['#title'], $element['#href'], $element['#localized_options']);
   return '
' . $output . $sub_menu . "
\n";
  }

You can do this with CSS

ul.menu ul.menu li a:before {
  content: "- ";
}

Or, you can do something similar with list-style-image or a background-image.

Keeping stuff like that out of markup makes things cleaner.


How to provide default value with PHP code for a field in Views 3 So I'm trying to create a View, displayed in a Block, that will show a list of nodes that reference the same parent node as the node I'm currently in. The reference is a custom field using the References module. I'm on Drupal 7 with Views 3.

I figure I'll setup a Contextual Filter on my custom field (field_ref_photo_gallery) and I need to provide a default value via PHP code.

How should I write that PHP code in the most Drupal 7-ish way?

Should I go with something like:

return node_load($nid)->field_ref_photo_gallery['und'][0]['value'];

(I'm not even sure that would work. I just threw that together in this post)

Or is there a field API function I should be calling?

You can pass currently viewing nodes id in contextual filter without using any custom code.

In contextual filter settings, under When the filter value is NOT in the URL select Provide default value option. Then there is a dropdown will show. Then select Content ID from URL. See the image:


Altering button title it becomes inactive The override function I use in my bootstrap sub-theme template.php:

function subtheme_form_titles_node_form_alter(&$form, &$form_state) {
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Activate'),
  );
}

I use this, so I could replace a default 'Save' title of the button to 'Activate'. Funny thing is that it does replace the button title, but then when using the form and trying to save it by pressing 'Activate', nothing happens, the page just refresh, but content doesn't get created.

Also for some reason it change button class from btn-primary to btn-default. This shouldn't be happening. I just want to replace button text and keep default btn-primary class.

Your mistake is this line:

$form['actions']['submit'] = array(

It replaces original button with your own brand new array. Nothing in it, except what you put there. Original node form have submit function connected directly to a button, but you destroyed that with this line.

Instead of deleting original array and creating new one, consider simply altering values you need altered, like:

$form['actions']['submit']['#value'] = t('Activate');


Overriding radio button rendering I have a List (text) field on a comment type. This field is required and only one option may be chosen, so a radio button is how it will be rendered. I would now like to change the way the radio buttons are rendered to allow for additional necessary styling. I have never done this before.

Currently each element is styled as such:

  <input data-drupal-selector="edit-field-list-1" type="radio" id="edit-field-list-1" name="field_list" value="1" class="form-radio">
  Item #1

But, let's say that I wanted to add an HTML element inside this
 or move one around. I have created a module which adds a widget for this field type. Once this widget is selected, I have tried modifying the field using a number of different methods, but to no avail. I have been making sure to regularly clear the cache since I have been using the .module file and a template.

I've tried using a template file, radios.html.twig and adding it using various hooks, such as hook_theme_registry_alter() and hook_theme(). I've tried using hook_form_alter().

I have never modified the rendering of an element like this before and the documentation all seems to be different enough from what I am trying to do so as to only add confusion.

Could anyone please tell me how to accomplish this? I'm happy to add clarification as needed.

Additionally, is using a Field Widget the best way to accomplish this? It seems the correct way to me, since I only want it to affect the input element on the comment creation/edit form, but I'm open to being wrong.

Additionally, is using a Field Widget the best way to accomplish this?

I would say yes, it's more work than a hook, but it makes things configurable most times hidden in a form alter hook. The result is the same. You can add to the form array additional render elements like div containers or attributes to the input element itself. Based on this add a theme suggestion, in case you want to add more markup in a template. See this answer from @Kevin.


There was an error with the file in gathercontent module of Drupal I am importing content from gathercontent platform using the GatherContent module.

All the fields get populated except media type which gives a warning that states :

"There was an error with the file"

Any ideas what might be causing this?

It might well be that your problem is caused by what is described in issue 1908144.

That issue also mentions CURL (as in the comment to your question).

Curious to hear if this somehow helps ...