What is the best way to set up demo for Drupal themes and live switch between them? I want to set up demo for Drupal themes and live switch between them with top drop-down menu.
Examples what i mean (navigate to the top bar and change theme live with a theme switcher):

http://themefuse.com/demo/wp/my-journey/

http://demo.themebrain.com/#anis

How can i repeat that with drupal, what is the best practice?
The problem is: if i develop a theme on my localhost, then install on the server drupal with this theme enabled - that is simle.
Then a develop second theme, and want to setup live preview with the same drupal installation BUT with another demo content.

So i need create another demo content BUT when the number of themes in development increase to 10-20 it will be a nightmare to remember what block or node is intended to appear with whith theme. Simple way is to setup different drupal each with one theme, BUT it's bad to accumulate the same code and db on the server.

In addition, i want to provide user with full drupal package (drupal setup with modules and database to import) to allow fast reproduce demo. So i don't want admin's interface clutter.

Possible modules i tried: http://drupal.org/project/themekey but it doesnot provide dropdown for switching
http://drupal.org/project/switchtheme but it shows the same content, i need it to show nodes and blocks for some theme only.

http://drupal.org/project/switchtheme is the one to use for that.

  Adds a block to allow users to switch between enabled themes.

  Themes can be given 'user friendly' names and access can be controlled
  by user role.

If you need to enable/disable blocks for certain themes, do so at Admin > Structure > Blocks for that theme.


Hand generate views relationship Here's the setup: the previous site builder linked a large quantity of assets to particular nodes.  Now that I'm on board, we want to expand those nodes into larger sections, but we need the linked assets to show up on all the pages.

Right now we have a view that uses a contextual filter to look at the NID.  Then, it refers to a relationship to see what assets are related to that NID.  Then, the view is filtered and displayed.

I need to come up with a way to display that same view on different pages that obviously don't share the same NID.  I've tagged all the pages within a section with the same taxonomy term.  I'd like to create a custom relationship that runs an equation that converts tid to nid.

  tid 62 = nid 15
  tid 63 = nid 47
  tid 64 = nid 153

I think you get the picture.  Any help?  If you have a better idea please let me know, thanks!
-JB

Here are a couple of ideas for you:

1) If there aren't too many nodes with assets - you could remove the contextual filter and create an "Or" Filter Group in the regular filter section of the view (based on NID). Then just list all of the NID's you want to filter by (NID 15 Or NID 47 Or NID153). That should pull in all of the assets from each of the Nodes without having to change the view much.

2) If you tagged the nodes containing the assets with taxonomy terms - you should also be able to use a regular taxonomy term filter instead of the contextual filter. I think in that case you would just need to add a Content: Taxonomy terms on node relationship to the view. That should open up a bunch of new taxonomy filter options in the regular filter section of views. You could then filter by term id or name.

You would just have to make sure you apply the Content: Taxonomy terms on node relationship to the term id filter when you set it up.


What is the relationship between field_data_field_ and field_revision_ tables? It seems that the field_data_field_ and field_revision_field_ tables contain exactly the same columns and data, except the revision table contains a row for every revision whilst the data table only contains a copy of the latest revision.

What is the point of having the 2 tables ?  Which table is accessed when a node is loaded ?

{field_data_[field_name]}

  Standard data storage for a field. It's recommended you use
  _field_sql_storage_tablename to get the name of this table.

  {field_revision_[field_name]}

  Standard revision storage for a field. It is recommended to use
  _field_sql_storage_revision_tablename to get the name of this table.

For more details


How to perform a Database API Inner query I have this Database API code, and I'm trying to add a sub-query to it:

$query = db_select('' . $base_table . '', 'n')
      ->extend('PagerDefault');
      ->extend('TableSort');

to turn this:

SELECT
FROM
taxonomy_term_data n
ORDER BY n.tid ASC

Into this:

SELECT
FROM
(SELECT * taxonomy_term_data LIMIT 10) n
ORDER BY n.tid ASC

I've tried passing a db_select statement into another db_select statement. I've tried query->addExpression() and db_query() to no avail.

You Can refer to this link

However you can try like below

$query->condition('<condition>', $subquery);


How do I reformat status messages? I'm trying to restyle the status messages block, and I just can't figure out how to do it.  I ought to be able to -- it's just defining a theme function, right? :) -- but it's just not happening for me.  I'm not sure if I'm not defining the function properly, or not registering it properly in hook_theme, or even if I need to register it in hook_theme.  Arggh -- can anybody out there clarify this for me?  Thanks very much!

the function you need to hook is:

themename_status_messages()

where themenameis your theme's name. You can see the status message theme docs here.

What specifically are you trying to restyle? Most of it can be done with CSS, without introducing a theme hook.


Webform file attachment I've been struggling with an issue today that I just can't seem to figure out.

I have a  webform that includes a file upload that I want to email upon submission.

The email sends correctly (using MIMEmail modules) but there is no attachment.

The webform is for job application.The user will upload the resume and portfolio. The hr and manager want to get mail along with attachment.How they can always be logged into site that is quite impossible. Now the issue is the who ever logged into the site only can see the attachment when click on the link. How to sent attachment from private folder as attachment not just in link(want proper attachment)

I'm running drupal 8. USed modules are webform, mime mail, mail system and also tried swift mailer.

But in webform module mail settings , there is "Include files as attachments" i checked that option. Still it is not working.

Out of the box Drupal 8 doesn't support file attachments. Take a look at this module and read the steps on the page: https://www.drupal.org/project/swiftmailer`

  The Swift Mailer module extends the basic e-mail sending functionality
  provided by Drupal by delegating all e-mail handling to the Swift
  Mailer library. This enables your site to take advantage of the many
  features which the Swift Mailer library provides, such as :

  Sending e-mails directly through a SMTP server of your choice, a locally installed MTA agent such as sendmail or the mail functionality
  provided by PHP.
  Sending HTML (MIME) e-mails.
  Adding file attachments to e-mails.
  Adding inline images to e-mails.

Also take a look at this: https://www.drupal.org/node/2821590


How to disable page link? I am new to drupal 7. I read the online documentation but, due to less programming skills, I could not figure out the exact solution.

I want to disable pager link. How can I do that?

I can understand, its hard for beginer to understand but drupal.org provides full documentation on it. Please, google before you post here.

probably, this would help you.

Drupal support forum page


Table doesn't render on ajax command I have a function that returns a render array for a table;

  private function _files_table($job_id){
    $files = $this->_query("
      select *
      from JC_Documents_Recent_Revisions
      where Job_ID=".$this->sqs($job_id).";
    ");

    $rows = array_map(function($row){
      return [
        (string)$row['Job_ID'],
        $row['Document_Name'],
        $row['Document_Type'],
        $row['File_Name'],
        ($row['Uploaded_Date'] != NULL ? $row['Uploaded_Date']->format("Y-m-d H:i") : 'Unknown Date'),
        $row['Uploaded_By'],
        new FormattableMarkup('show', [':link' => (Url::fromRoute('JobFileUpload.Serve', ['file_id' => (int)$row['FileID']]))->toString()]),
        new FormattableMarkup('revise', [':link' => (Url::fromRoute('JobFileUpload.Revise', ['file_id' => (int)$row['FileID']]))->toString()]),
        new FormattableMarkup('delete', [':link' => (Url::fromRoute('JobFileUpload.Delete', ['document_id' => (int)$row['DocumentID']]))->toString()])
      ];
    }, $files);

    $header = [
      t('Job ID'),
      t('Document Name'),
      t('Document Type'),
      t('File Name'),
      t('Uploaded Date'),
      t('Uploaded By'),
      t('Download'),
      t('Revise'),
      t('Delete')
    ];

    return [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows
    ];
  }

and two occasions where I wish to render the table. The first is in buildForm:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $job_id=NULL) {
    $jobs = $this->_query("
      select *
      from Active_Job_List;
    ");

    $formatted_jobs = [];
    $len = count($jobs);
    for($i=0; $i<$len; $i++){
      $formatted_jobs[$jobs[$i]['Job_ID']] = $jobs[$i]['Job_Name'];
    }
    natsort($formatted_jobs);

    $form['job_id'] = [
      '#weight' => 1,
      '#title' => t('Job'),
      '#type' => 'select',
      '#options' => $formatted_jobs,
      '#ajax' => [
        'callback' => '::showFiles',
        'wrapper' => 'ajax-wrapper'
      ],
      '#required' => TRUE,
      '#default_value' => $job_id
    ];

    $form['jobfiles'] = $this->_files_table($job_id);
    $form['jobfiles']['#weight'] = 2;

    if($job_id != null){
      $form['newfile'] =  [
        '#weight' => 3,
        '#title' => t('Upload new file'),
        '#type' => 'link',
        '#url' => Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id])
      ];
    }

    return $form;
  }

The second is in showFiles:

  public function showFiles(array &$form, FormStateInterface $form_state) {
    $job_id = $form_state->getValue('job_id');

    $output = $this->_files_table((int)$job_id);
    // $output['link'] = new FormattableMarkup('Upload a new file...', [':link' => (Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]))->toString()]);

    $renderer = \Drupal::service('renderer');

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax-wrapper', $renderer->render($output)));

    return $response;
  }

The buildForm method works just fine, and I get a table with the files in it. But when I call the same render array function on an output for the AjaxResponse (in ::showFiles), I don't even get an error, and the table does not show up. Anyone got an idea of what I'm doing wrong here?

I think the problem was not specifying an id attribute for my table when I first render it, so there was nothing to replace.

This seems to work:

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $job_id=NULL) {
    $jobs = $this->_query("
      select *
      from Active_Job_List;
    ");

    $formatted_jobs = [];
    $len = count($jobs);
    for($i=0; $i<$len; $i++){
      $formatted_jobs[$jobs[$i]['Job_ID']] = $jobs[$i]['Job_Name'];
    }
    natsort($formatted_jobs);

    $form['job_id'] = [
      '#weight' => 1,
      '#title' => t('Job'),
      '#type' => 'select',
      '#options' => $formatted_jobs,
      '#ajax' => [
        'callback' => '::showFiles',
        'wrapper' => 'ajax-wrapper'
      ],
      '#required' => TRUE,
      '#default_value' => $job_id
    ];

    $form['jobfiles'] = $this->_files_table($job_id);
    $form['jobfiles']['#weight'] = 2;

    if($job_id != null){
      $form['newfile'] =  [
        '#weight' => 3,
        '#title' => t('Upload new file'),
        '#type' => 'link',
        '#url' => Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]),
        '#attributes' => [
          'id' => ['new-file']
        ]
      ];
    }

    return $form;
  }

  public function showFiles(array &$form, FormStateInterface $form_state) {
    $job_id = $form_state->getValue('job_id');
    // $form_state->setRedirectUrl(Url::fromRoute('JobFileUpload.OverviewWithJobId', ['job_id' => $job_id]));

    $table = $this->_files_table((int)$job_id);
    $link = [
      '#type' => 'markup',
      '#markup' => new FormattableMarkup('Upload a new file...', [':link' => (Url::fromRoute('JobFileUpload.UploadForm', ['job_id' => $job_id]))->toString()
      ])
    ];
    $renderer = \Drupal::service('renderer');

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax-wrapper', $renderer->render($table)));
    $response->addCommand(new HtmlCommand('#new-file', $renderer->render($link)));

    return $response;
  }


How to force the canonical URL to use http? On our page we use the Metatag module to show a canonical meta tag. In the configuration we use the [current-page:url:absolute] token. This works fine, but the problem is, that whether the page gets accessed by HTTP or HTTPS this protocol is used in the canonical URL.

For SEO purposes we want the canonical URL to be the same and use HTTP for both protocols.

How can we achieve this?

Drupal 7

You can implement hook_html_head_alter() to change head tags; the following is untested but should do the trick:

function MYMODULE_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => &$tag) {
    if (strpos($key, 'drupal_add_html_head_link:canonical:') === 0) {
      if (strpos('https://', $tag['#attributes']['href']) === 0) {
        $tag['#attributes']['href'] = str_replace('https://', 'http://', $tag['#attributes']['href']);
      }
    }
  }
}


Display an image for the first item in a Views news list I want to create a view to display news like in this image:

The list shows an image only for the first news, the other news only display the title.

Views nodes split does exactly this:

  This module allows site administrators or builders to have a different
  view mode for the first nodes of a view result.

Source: Lullabot - Module Monday: Views Nodes Split


How to create one entity and assign the same entity as field to new entity programatically -I need to create one entity (need to do coding)- that I created already, now want to create  another entity, lets say "Entity 2"( term(taxonomy, param1, param2, description( it will have multiple values- multiple description).
Now I need to add entity 2 as field for entity 1. Entity 1 can have multiple entities of type "Entity 2"

Once you have the ID of the new entities, it's as simple as:

$new_entity->field_foo[LANGUAGE_NONE][0]['target_id'] = $other_entity_id;
$new_entity->field_foo[LANGUAGE_NONE][1]['target_id'] = $yet_another_entity_id;

I've assumed the field type is Entity Reference, YMMV for other types.


How to show number of a views return results without submitting the view? I have a view with some exposed filters.When selecting first exposed filter,I want to appear the Number of the view results without having submitting the view.Same thing for second exposed filter etc.
I have seen this to other sites and I am not sure how to do this with drupal.
thanks

How about triggering ajax call on key-press of that input field. In the ajax callback programatically call the view to get total count of results populate this count in field.


Live Inline Editing of Fields in Views I know Drupal 8 has the quick edit module for inline editing, but how do you turn this feature on for a View that has fields where you can just click to edit it inline?

Quick Edit of nodes in Views works. You can see this on the frontpage, which is a View.

However this works only for Views which show content.

If you have a View which shows content and want to choose the fields and customize the layout, you can create a custom viewmode, configure the fields there and put the layout in the twig files of the view mode.

Of course this does not provide all features of a View which shows fields and the module Editablefields. For this you would have to wait until this module is ported to D8.


Getting site-offline message when trying to drupal_bootstrap from command line I'm trying to bootstrap drupal from a standalone PHP script at the command line from sites/all/modules/mymodule/mymodule.php.

<?php
  chdir('/sandbox/mysite/');
  require_once './includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

I'm attempting to run it from the command line, but I get Drupal site-offline when I do (trimmed for brevity):

cd /sandbox/mysite
php sites/all/modules/mymodule/mymodule.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Site off-line | Pressflow</title>

The site is online and works fine from the browser. DRUPAL_BOOTSTRAP_DATABASE is where this fails, since I can bootstrap the DRUPAL_BOOTSTRAP_CONFIGURATION and DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE phases without a problem. Anyone run into this before? Thanks in advance.

An easy way of writing CLI code for Drupal is implementing your own drush (http://drupal.org/project/drush) commands. Drush itself commes wirh handy example code.


How i can increase the Block settings limit? We are implementing blocks through features and features extra module.

Here only 50 blocks are displaying in admin>structure>features>create Components. We want to increase that limit to 100. Please find the attached snapshot.

There are a couple of things you could do for increasing the limit on blocks that you can add to your site. For instance, have you tried increasing max_input_vars limit in your .htaccess or in your php.ini file? From 1000 to, let's say, 2000?

Or increasing your limit in your settings.php file if not?

See if this post here (its second half rather) can be of any help: https://www.optasy.com/blog/how-add-more-lot-more-blocks-your-drupal-site


How to insert field value programmatically after node is created? Let's say user creates a node of article type.There is a field called my_field which can be added multiple times to that node.If user creates or edits the node leaving my_field blank, a default value something like NA should be created in database and should be visible inside the my_field when user edits  node next time.

Tried so far:

Inside page.tpl.php

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);

  foreach ($nids as $nid) {

    $node = node_load($nid);

   if(empty($node->field_my_field))
   {
     $field_language = field_language('node', $node, 'field_my_field');
     $node->field_my_field['LANGUAGE_NONE'][0]['value'] = 'NA';

      field_attach_insert('node', $node);
   }
  }
 }

Note: I don't want to create default value inside field settings as my_field can be added multiple times which can go upto more than 20.

I am using drupal 7.41.

I suppose it is due to your field_attach_insert(). Usually one should save the entire node using node_save().
However it is a lot easier if you install the entity API module and utilize its Entity Metadata Wrappers.

And I'd really recommend creating a custom module. You will need something similar to this:

function mymodule_node_insert($node) {
  if ($node->type == 'article') {
    mymodule_update_empty_value($node);
  }
}

function mymodule_node_update($node) {
  if ($node->type == 'article') {
    mymodule_update_empty_value($node);
  }
}

function mymodule_update_empty_value($node) {
  $wrapper = entity_metadata_wrapper('node', $node);
  // No value?
  if  (empty($wrapper->field_myfield->value())) {
    $wrapper->field_myfield->set('NA');
    $wrapper->save();
  }
}


Compare two views that present two different content type and delete nodes this question is like this: How to delete a content in a view with view rules?

I didn't know why but i make this question with another account that i cannot got access now
So the problem is: I got two views. View A and View B. View A rapresent contents of type A (30 contents for example) and view B rapresent contents of type B (30 contents for example). By comparing the various nodes contained in these two views i want to found (among the nodes contained in the view B) contents with the same title of some nodes caontained in the view A and delete them. After this operation, View A got 30 nodes and View B got 3 nodes because got 27 nodes with same title of some nodes in the View A. I try to do this in a Rule with view loop but i didn't know how to delete nodes with the same title. I try with VBO but i cannot make this process i think, cause i need to delete nodes selectively

Thanks and sorry for the duplicate post (i need to do this cause i cannot reply with old account)

You can simply achieve that by using the Remove Duplicates module.

  This module helps the administrator to easily remove duplicate nodes according to one of the node fields.


Creation and display of song setlists I am using Drupal version 7.42 and a content type used for information regarding Concert setlists. It includes labels for:

Date.
Venue.
Location.
Setlist.
Description.
Lineup.

I will give you an idea of what I am looking to achieve in the end regarding its display. I also have a content type for the Songs.

Each performance listing will be different. I will have some listings that show Songs known to be performed yet the Setlist isn't complete. I will have some listings that show songs known to be performed in:

Set 1.
Set 2.
Encore.
etc.

Also, some performances may have more than one encore, so I also will have performances noted with Encore 1, Encore 2, etc. if the listing requires it.

How do I manage to get the display of the setlist to show a label above the songs indicating the song placement?

I thought having multiple fields in the content type (Set 1, Encore, Encore 1, Encore 2, etc) does the trick. But with time mulling over this one I am thinking is it possible to be achieved by just having one setlist field (Setlist) instead of multiple setlist fields in the content section?

Below is an example of the display I am describing for site viewers to see when visiting a performance page. Each song listed in a performance page at the moment uses Entity Reference to link to its unique song within the Songs content type.

Set:

Song 1
Song 2
Song 3

Encore 1:

Song 4
Song 5

Encore 2:

Song 6

Any suggestions?

Below is a possible approach you may want to consider. It's using "State" names (like Florida, Illinois, etc.) instead of "Set 1, Set 2, etc" and "Cities" instead of "Songs".
If I was to implement this in a Drupal site, I'd use either of these "displays":

Option 1 - Master detail with nested blocks
Have a look at this example, which shows 1 "block" for each "State", and within each "block" it shows the "Cities" (and one of its attributes) in that "State".

Option 2 - Report that filters based on some lookup
Have a look at this example, which shows only the data about a specific "State", together with all the "Cities" (and one of its attributes) in that "State". To switch to another state, select the desired state from the Parameter form near the top ("IL" is used as the default in this example).

If you wonder "How did you do that?!?!" ... then this is the answer: that's really a piece of cake using the Forena module. Checkout the Community Documentation for details, and/or the documentation that comes with the module. The above 2 examples are actually delivered with the module (out-of-the-forena-box), though you probably don't notice that it is even not a typical "Drupal database". It could be such database instead, but in this case it's an SQLite (sample) database (it could also have been Oracle, MS SQL, Postgress or any PDO compliant database).
Disclosure: I'm a co-maintainer of Forena.


Create a custom filter in Views related to a custom table I have a table where I keep some logs, for example, when a user visits a node, I record of the form:

The user 34 visited node 235.

Then I have a Views what show me the following fields:

NID
Title
Body

How to display only the nodes that the current user has visited or not?

EDIT:

Example of my custom table:

------------------------------------------------------
| UID | action                        | IP           |
------------------------------------------------------
| 34  | The user 34 visited node 235. | 200.54.21.24 |
------------------------------------------------------

UID = User ID

I would do the following to achieve this. In the custom table where you maintain log create a view handler using hook_views_data. Add the following code in your .module file

     function MODULENAME_views_api() {
       return array(
           'api' => '3.0-alpha1',
           'path' => drupal_get_path('module','MODULENAME'). '/views',
       );
    }

Then add a file with the name MODULENAME.views.inc in your module views folder and the following code.

    /**
 * Implements hook_views_data()
 *
 */
function MODULENAME_views_data() {

 $table = array(
    'custom-table-name' => array(  //  Custom table
       'table' => array(
          'group' => 'Custom Tables',      // Groupname
             'base' => array(
               'field' => 'id',  //Primary key
               'title' => '<your table name>',
            )
        ),
     //Description of id
        'id' => array(
           'title' => t(' Id'),
           'help' => t(' Id field'),
           // is mydons_custom_id field sortable TRUE
           'field' => array(
              'click sortable' => TRUE,
            ),
      //Filter handler for filtering records by mydons_custom_id
           'filter' => array(
               'handler' => 'views_handler_filter_numeric'
            ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           )
         ),

         'user_id' => array(
           'title' => t('User ID'),
           'help' => t('User ID referring to User for users table'),
           'field' => array(
              'click sortable' => TRUE,
           ),
           'filter' => array(
              'handler' => 'views_handler_filter_string'
           ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           ),
           'relationship' => array(
            'base' => 'users', // The name of the table to join with.
            'base field' => 'uid', // The name of the field on the joined table.
            'relationship field' => 'user_id',
            // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
            'handler' => 'views_handler_relationship',
            'label' => t('User'),
            'title' => t('Referenced USER entity'),
            'help' => t('Add USER Fields'),
          ),

        ),

         'node_id' => array(
           'title' => t('Node ID'),
           'help' => t('Node ID referring to Node'),
           'field' => array(
              'click sortable' => TRUE,
           ),
           'filter' => array(
              'handler' => 'views_handler_filter_string'
           ),

           'sort' => array(
              'handler' => 'views_handler_sort'
           ),
           'relationship' => array(
            'base' => 'node', // The name of the table to join with.
            'base field' => 'nid', // The name of the field on the joined table.
            'relationship field' => 'node_id',
            // 'field' => 'nid' -- see hook_views_data_alter(); not needed here.
            'handler' => 'views_handler_relationship',
            'label' => t('User'),
            'title' => t('Referenced USER entity'),
            'help' => t('Add USER Fields'),
          ),

        ),

      )
    );
    return $table;
}

Clear the cache and go to views page and create another view of your custom table. Add relationship to your node and users and contextual filters to show logged in users node.


add Solr search box in views filter I have succesfully installed solr and it is working fine, but my main search in my drupal site is based on views exposed filters, is there a way to add the solr search in views filters, so it interacts with them?

I am using views to setup an advanced search, by exposing filters, i want to add one that uses solr, so in total solr search is used together with views filter and i get corresponding results from files too.

You can try using Apache Solr Views module.

Project page says

  In order to get the facet blocks provided by the Apache solr Search
  Integration Project you need to set up either arguments or exposed
  filters for the blocks. For instance, you could set up an argument for
  node type and the Apache Solr Search: Filter by content type block
  will work.


Only override part of a theme function In Drupal 7 you can take a theme function and override it.

For example if I want to override theme_form_element, I would place it in  my template.php as MYTHEME_form_element.

The only problem is that I then have to copy the entire theme function into my template.
For example, for theme_form_element, there is over 60 lines of code.

This seems overkill, if I only want to do something simple as add a class to the attributes array.

Is there any way to only include the part of the theme function I want to override and tell Drupal to refer to the rest of the built in function?

If you need to change the content of the variables passed to the theme function, then you can simply implement a preprocess function for that theme, which in Drupal 7 is invoked for every theme function, including the ones not using a template file.
In the case of theme_form_element() the preprocess function for your theme is MYTHEME_preprocess_form_element().

You could also avoid duplicating the code of theme_form_element(), and call it before, but in that case you should call it directly as theme_form_element(), not as theme('form_element') (which would cause an infinite loop).

The problem with theme_form_element() is that it doesn't use $element['#attributes']['class'] to set the attributes of the form element. It uses a local variable that is initialized with the following code, which passes its value to drupal_attributes().

  $attributes['class'] = array('form-item');
  if (!empty($element['#type'])) {
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  }
  if (!empty($element['#name'])) {
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";

To add a new class to the form element, you have two alternatives:

Copying the code from theme_form_element() to your theme function, and editing it
Call theme_form_element() from your theme function, and add a new class to the output returned from theme_form_element() using preg_replace().


Using select list with Views exposed filter when it is a custom schema through hook_views_data I need to build a page in Panels that is composed of Views displays. The page that this will make will function as a kind of workstation for a staff member displaying bespoke information about readership details, demographics, products chosen etc. etc.

The problem is that I've inherited this project and the previous developer was hard-coding things, avoiding the Drupal API and trying to create his own CMS to handle this complex readership-type subscription system. I now have to make this something that will play nicely with Drupal rather than starting again due to time constraints.

I've used hook_views_data to expose his custom tables but because it seems to be data unmanaged by Drupal (i.e. he used nothing like nodes/ entities etc.) I don't think I'm able to exploit the node/custom field/select (https://drupal.org/node/391528) workaround I'm not sure of what I should start looking at.

Please do offer suggestions (possibly even on the wider context if it's relevant)

Unfortunately for me the project is too far gone to create the underlying design with entities, which seems to be the only way that I'm going to achieve that, so instead I am going to be using AJAX like forms which hopefully (in time) will output into Views (to save time and hopefully provide some flexibility). So for now I'm building Panels with blocks that I'm creating programmatically and then using drupal_get_form('mymodule_mainform') to add the content of those blocks with forms designed in different functions in my modules.
For that I'm using the Example module's 'block_example' module (block_example.module code pasted at the bottom here - find and replace 'block_example' with your module name if you want to paste it straight into your own .module file, remember though that you can't duplicate hooks, so copy the contents into any pre-existing functions or hooks with the same name).
To help out other people I've included the links that helped me here (may you have better luck!) "joshaust.in"'s .pdf was a brilliant explanation...
For conceptual understanding: http://joshaust.in/wp-content/uploads/2012/06/Entities-and-Bundles-in-Drupal-7.pdf
http://joshaust.in/2012/06/entities-and-bundles-in-drupal-7/
For attaching fields to your entity programmatically:
How to attach a field to an entity programmatically?
For programmatically creating your entities: http://www.phase2technology.com/blog/programmatically-creating-entities/
http://www.trellon.com/content/blog/creating-own-entities-entity-api
block_example.module
/**
 * Implements hook_menu().
 *
 * Provides a default page to explain what this module does.
 */
function block_example_menu() {
  $items['examples/block_example'] = array(
    'page callback' => 'block_example_page',
    'access callback' => TRUE,
    'title' => 'Block Example',
  );
  return $items;
}

/**
 * Simple page function to explain what the block example is about.
 */
function block_example_page() {
  $page = array(
    '#type' => 'markup',
    '#markup' => t('The Block Example provides two sample blocks which demonstrate the various block APIs.
            To experiment with the blocks, enable and configure them on the block admin page.', array('@url' => url('admin/structure/block'))),
  );
  return $page;
}
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function block_example_block_info() {
  // This hook returns an array, each component of which is an array of block
  // information. The array keys are the 'delta' values used in other block
  // hooks.

  // The required block information is a block description, which is shown
  // to the site administrator in the list of possible blocks. You can also
  // provide initial settings for block weight, status, etc.

  // Many options are defined in hook_block_info():
  $blocks['example_configurable_text'] = array(
    // info: The name of the block.
    'info' => t('Example: configurable text string'),
    // Block caching options (per role, per user, etc.)
    'cache' => DRUPAL_CACHE_PER_ROLE, // default
  );

  // This sample shows how to provide default settings. In this case we'll
  // enable the block in the first sidebar and make it visible only on
  // 'node/*' pages. See the hook_block_info() documentation for these.
  $blocks['example_empty'] = array(
    'info' => t('Example: empty block'),
    'status' => TRUE,
    'region' => 'sidebar_first',  // Not usually provided.
    'visibility' => BLOCK_VISIBILITY_LISTED,  // Not usually provided.
    'pages' => 'node/*', // Not usually provided here.
  );

  $blocks['example_uppercase'] = array(
    // info: The name of the block.
    'info' => t('Example: uppercase this please'),
    'status' => TRUE,
    'region' => 'sidebar_first',  // Not usually provided.
  );

  return $blocks;
}

/**
 * Implements hook_block_configure().
 *
 * This hook declares configuration options for blocks provided by this module.
 */
function block_example_block_configure($delta = '') {
  // The $delta parameter tells us which block is being configured.
  // In this example, we'll allow the administrator to customize
  // the text of the 'configurable text string' block defined in this module.

  $form = array();
  if ($delta == 'example_configurable_text') {
    // All we need to provide is the specific configuration options for our
    // block. Drupal will take care of the standard block configuration options
    // (block title, page visibility, etc.) and the save button.
    $form['block_example_string'] = array(
      '#type' => 'textfield',
      '#title' => t('Block contents'),
      '#size' => 60,
      '#description' => t('This text will appear in the example block.'),
      '#default_value' => variable_get('block_example_string',  t('Some example content.')),
    );
  }
  return $form;
}

/**
 * Implements hook_block_save().
 *
 * This hook declares how the configured options for a block
 * provided by this module are saved.
 */
function block_example_block_save($delta = '', $edit = array()) {
  // We need to save settings from the configuration form.
  // We need to check $delta to make sure we are saving the right block.
  if ($delta == 'example_configurable_text') {
    // Have Drupal save the string to the database.
    variable_set('block_example_string', $edit['block_example_string']);
  }
  return;
}

/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function block_example_block_view($delta = '') {
  //The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'example_configurable_text':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Title of first block (example_configurable_text)');
      // The content of the block is typically generated by calling a custom
      // function.
      $block['content'] = block_example_contents($delta);
      break;
    case 'example_empty':
      $block['subject'] = t('Title of second block (example_empty)');
      $block['content'] = block_example_contents($delta);
      break;
    case 'example_uppercase':
      $block['subject'] = t("uppercase this please");
      $block['content'] = t("This block's title will be changed to uppercase. Any other block with 'uppercase' in the subject or title will also be altered. If you change this block's title through the UI to omit the word 'uppercase', it will still be altered to uppercase as the subject key has not been changed.");
      break;
  }
  return $block;
}

/**
 * A module-defined block content function.
 */
function block_example_contents($which_block) {
  switch ($which_block) {
    case 'example_configurable_text':
      // Modules would typically perform some database queries to fetch the
      // content for their blocks. Here, we'll just use the variable set in the
      // block configuration or, if none has set, a default value.
      // Block content can be returned in two formats: renderable arrays
      // (as here) are preferred though a simple string will work as well.
      // Block content created through the UI defaults to a string.
      return array('#markup' => variable_get('block_example_string',  t('A default value. This block was created at %time', array('%time' => date('c')))));
    case 'example_empty':
      // It is possible that a block not have any content, since it is
      // probably dynamically constructed. In this case, Drupal will not display
      // the block at all. This block will not be displayed.
      return;
  }
}

/*
 * The following hooks can be used to alter blocks
 * provided by your own or other modules.
 */

/**
 * Implements hook_block_list_alter().
 *
 * This hook allows you to add, remove or modify blocks in the block list. The
 * block list contains the block definitions. This example requires
 * search module and the search block enabled
 * to see how this hook implementation works.
 *
 * You may also be interested in hook_block_info_alter(), which allows changes
 * to the behavior of blocks.
 */
function block_example_block_list_alter(&$blocks) {
  // We are going to make the search block sticky on bottom of regions. For
  // this example, we will modify the block list and append the search block at
  // the end of the list, so even if the administrator configures the block to
  // be on the top of the region, it will demote to bottom again.
  foreach ($blocks as $bid => $block) {
    if (($block->module == 'search') && ($block->delta == 'form')) {
      // Remove the block from the list and append to the end.
      unset($blocks[$bid]);
      $blocks[$bid] = $block;
      break;
    }
  }
}

/**
 * Implements hook_block_view_alter().
 *
 * This hook allows you to modify the output of any block in the system.
 *
 * In addition, instead of hook_block_view_alter(), which is called for all
 * blocks, you can also use hook_block_view_MODULE_DELTA_alter() to alter a
 * specific block. To change only our block using
 * hook_block_view_MODULE_DELTA_alter, we would use the function:
 * block_example_block_view_block_example_example_configurable_text_alter()
 *
 * We are going to uppercase the subject (the title of the block as shown to the
 * user) of any block if the string "uppercase" appears in the block title or
 * subject. Default block titles are set programmatically in the subject key;
 * titles created through the UI are saved in the title key. This module creates
 * an example block to demonstrate this effect (default title set
 * programmatically as subject).  You can also demonstrate the effect of this
 * hook by creating a new block whose title has the string 'uppercase' in it
 * (set as title through the UI).
 */
function block_example_block_view_alter(&$data, $block) {
  // We'll search for the string 'uppercase'.
  if ((!empty($block->title) && stristr($block->title, 'uppercase')) || (!empty($data['subject']) && stristr($data['subject'], 'uppercase'))) {
    // This will uppercase the default title.
    $data['subject'] = isset($data['subject']) ? drupal_strtoupper($data['subject']) : '';
    // This will uppercase a title set in the UI.
    $block->title = isset($block->title) ? drupal_strtoupper($block->title) : '';
  }
}


Webform POST handler, add API/header creds? Using the Remote POST handler in Webform 5, is there a way to add basic auth / API key to the request leveraging tokens or referencing a const? I'd like to find a way not to hardcode actual values.

Just adding an answer in addition to @Ryan Hartman's comment. Extend the RemotePostWebformHandler class and its ::buildConfigurationForm() method:
/**
 * Custom Webform submission remote post handler.
 *
 * @WebformHandler(
 *   id = "custom_remote_post",
 *   ...
 * )
 */
class CustomRemotePostWebformHandler extends RemotePostWebformHandler {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['api_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API Key'),
      '#description' => $this->t('The API key for basic auth.'),
      '#default_value' => $this->configuration['api_key'] ?? NULL,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    $this->configuration['api_key'] = $form_state->getValue('api_key') ?: NULL;
  }

  ...

Alternatively implement the form element provided by the Key module so you can securely store sensitive secret keys.


Add to cart button enabled if subscriber seller I want to create a marketplace. Each seller will be able to create a shop and products that will be displayed to all visitors.

A non-subscriber (free) will have on his product a button "Add to cart" not clickable. The products can not be ordered.
A subscriber (paid) will have on his product a button "Add to cart" clickable. The products can be ordered.

How to do this ?

How do I create subscriptions with an end date with drupal ?

My answer would be for Drupal 7 with respect to current code to your final question of functionality:
 - After making sure both the rest of your structure is in place, Add the Rules watchdog that will "listen" for the role or lack thereof
   and then do not only 'it' but perhaps other things for example display a popup message. It would be possible to change the look or color of the button as well. Requirement: Rules module. Rules UI will have it write the code for you, that you can then save to code if you want.
 - With a rule stating normal code behavior not having fired or reverting to normal behavior after logging in, then the button will do as it was coded to do.

Subscriptions with an end date in Drupal by marrying a subscription to a role by https://www.drupal.org/project/commerce_license not released for 8 production yet whereby you do all the magic of billing: Commerce Billing is an option in Drupal 7, method, cycle, grace period, and expire or downgrade the role as you wish upon expiration. From a step point-of-view, this step precedes the rules, as this will be the basis for rules. "commerce_billing" is only available for Drupal 7 at this time with respect to billing anyway, and the projects don't show a Drupal 8 version being started yet. That's why my answer is for Drupal 7 only at this time, except when one module may be ready but calls itself "dev", and the other is not yet started.


Why is smtp not sending emails via SendGrid? I am attempting to add SendGrid to a Drupal 7 site. I have been following the offical sendgrid.com documentation for this, and following the instructions for using the smtp authentication support module. (https://sendgrid.com/docs/Integrate/Open_Source_Apps/drupal.html)

After installing and activating the smtp Authentication Support Module using drush (for which I used version 7.x-7.x-2.x-dev because of a bug with the default version), I was able to activate the module without error and follow the instructions in the documentation.

Going to configuration > System > SMTP Authentication Support

Turn the module on
Make sure Email delivery is turned on
Adding a provier witht eh name sendgrid
SMTP server: smtp.sendgrid.net
SMTP port 587
User encrypted Protocol: No
username and password for my sendgrid account
set email from address and email name
save configuration (which went through without error)

I then filled out a test email address and saved the configuration again.

I got a confirmation message that the settings were stored without error and that the test email had been sent.

I received the test email, but when I checked the headers on the email I received I can see that it has not arrived via SendGrid, but has come directly from my server. I can also see no activity on the SendGrid account at all.  I have repeated the test sending system emails linked to user signup and I get the same result, I receive the email but it does not come via SendGrid.

I have also tried using port 465 and SSL as the encryption protocol, but while the the test email reported to have worked, I received no emails at all with these settings.  Also as before no activity is logged in SendGrid.

Just to be thorough I tested my SendGrid account using telnet and was able to send an email using the same setting and account username and password used in drupal, including port number. The email was sent without issue, registered in SendGrid activity feed and the received email header references SendGrid.

I have gone as far as I can think of. Can anybody suggest where I might be going wrong?

We use SendGrid with SMTP Authentication Support and have not encountered any problems.

SendGrid may not allow unencrypted connections on port 587, depending on your package. That is the port for TLS/STARTTLS, so if you want to use port 587, you should select use TLS under Use encrypted protocol. This is how all of our sites that use SendGrid are set up.

One trick that can trip you up is the configuration of Mail System. If you use Mime Mail or another system that requires Mail System to be installed, you must configure Mail System to use SMTP explicitly, or it will fall back to Drupal's default mailer (PHP mail())

For a quick out of the box, you need to configure Mail System  (/admin/config/system/mailsystem on Drupal 7) to use SmtpMailSystem for your module class (for example as the Mime Mail module class, or as the Site-wide default MailSystemInterface class).

For an alternative integration option, there is a SendGrid Integration module which uses the API rather than plain SMTP.


Create form for image selection from the content I have a content type with title and image field in it. Now, I want to show a form to the user which will show the image thumbnail, title and a checkbox below each image with the value of respective nid. So that user can select the image they like and submit it. Which will eventually take the nid and do some actions depending on the selected nid.

My question is how I will create such form from that content.

Like most things in Drupal there are a couple of different ways you could do this. A quick look into the challenge, reveals the Webform View module. Basically, it allows you to pull in a viw (list of your nodes) as selectable items, for a webform. Webforms are good if all you want to do is store (and email of course) the submitted values of a form for manually processing later. Webforms are typically used for feedback, survey, contact forms.

If you need to do something a little more flexible with the submitted values, alternatively you could use the Views Bulk Operations (VBO) module (add-on for Views) which provides this kind of functionality plus a lot more if you need it for other purposes too.

Basically, you would create a view listing your content items with the fields you want to display, and then add a "Bulk operations: Content" field, and select the "Pass ids as arguments to a page", and then specify the path you want the arguments sent to. The path could then be defined in your custom drupal module, and you could use the $arguments = func_get_args(); to get all the arguments sent through. e.g. in a sandbox_test.module

function sandbox_test_menu() {
  $items = array();

  $items['test-submit'] = array(
    'title' => 'VBO Test Submission handler',
    'page callback' => 'sandbox_test_vbo_test',
    'access callback' => TRUE,
  );

  return $items;
}

function sandbox_test_vbo_test() {
  $output = '';

  $args = func_get_args();
  if (is_string($args[0])) {
    $items = explode(",", $args[0]);
    $output .= '<pre>' . print_r($items, true) . '</pre>';
  }
  else {
    $output .= 'None found';
  }

  return $output;
}


views preview is different from actual view The preview of my view looks exactly how I want it to but unfortunately is different when I go to the actual page. Anyway to fix this?

This is using Drupal 8

This happens because Views UI is a part of administrative interface and uses the admin theme to render previews.

If you would use the same theme for admin and front end - you'd see the same style for your View. Although, you should be aware that not all front-end themes render administrative interface good enough - that is why there is an option to use separate themes for admin and end user interface.

To sum it up - there is nothing wrong with how your View's preview is rendered, because preview and the end result are using different themes.


Difference between Hook and function I have a confusion regarding the hook and a normal function, So can any one tell me what is the significant difference between a Drupal hook and a normal PHP function in Drupal.

This is a good question. To clarify it first, Hook is a function. But it is a function that is named in such a way, that other modules and themes can override it with their own versions.

For example:

Your module 'custom_node' has a function that adds information to
the custom node. That function is called 'custom_node_add_data()'.
Soon after you release the module, you realize, that other people
liked it, and they are asking you to implement a way for them to add
their custom data to a custom node, from their custom modules, so
that they dont have to hack yours.
So what do you do? You make your 'custom_node_add_data()' a hook.
You name it 'hook_add_data()', and then you add your own overrides
in 'custom_node_add_data()'.
Under the hood, Drupal finds the declared hooks, and searched for
functions in all code base that serve the hook formula, where the
'hook' is replaced by the module name.

Thus, profit! Custom modules can now override your hook function with their own code. They 'hook in' to what your module does, because now their hook function will be called.

Hooks allow to replace initial module's functionality with your own functionality in procedural code. In OOP code, like in Drupal 8, hooks are being replaced by subclassing and implementation of interfaces. Some hooks fill still remain in theming.


How do I get the UUID for a current logged in user? In the Drupal 8 user's table, there is a UUID field. I'm trying to figure out if there is some method to easily access the UUID for a current user like you would when you get a UID for a user.

Thoughts?

You can load the UUID from entities with the method uuid(). If you have an account from the current user service then you have to load the user entity first:

$account = User::load($account->id());
$uuid = $account->uuid();


How to group node comments using parent comment in views I have a content type that student users can comment on. Tutors can go to each comment and respond with an answer.

On each node, I want to display the comments a user makes ONLY. Each comment should be a thread though, showing the responses from tutors.

Right now I have tried views and seen the potential to use a parent comment as relationship then filtering on the parent comment's uid. This however, doesn't bring out the needed functionality.

How do you think I can accomplish this. Any pointers appreciated.

Hmmm, maybe this way:

Create Views that view only comments. and filter from all comments only those, that was made by the users with role "student".
With Display Suite module mark-up displaying of your content type - "screw" this view to your content type.
Edit what view that is checked id of this node and show comments only for this node


Translation does not work for promoted to front page nodes I've been trying to figure out how to have a translated node promoted on the front page to be displayed according to the visitor chosen language. So basically I have one article promoted on the front page. It has a french translation (which I also set as promoted on the front page).

I want my visitor to only see the english version of my article (node/1) when on mysite.com/en
I want my visitor to only see the french version of my article (node/3) when on mysite.com/fr

The problem:

The source node (en, node/1) has a translated version (fr, node/3). Both are set to be promoted on front page. But they are both showing up on the homepage whereas I would like to have the nodes being only displayed once on the related language (mysite.com/fr or mysite.com/en).

Everything has been set up using Internationalization.

UPDATE

You will think I was posting without googling first but I can ensure you I've been struggling with this for hours. Finally found the solution here: https://stackoverflow.com/questions/5168289/multiple-frontpages-in-mutiple-languages/6803625#6803625

I'm assuming this question is about D7 ...

The relative URL to display as the front page is specified within admin/config/system/site-information. If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

Refer to the community documentation about Variable translation for details about how to translate text and settings that are stored in Drupal as variables. Here is a quote from that page:

  The Variable translation module, part of the Internationalization (i18n) package, allows you to translate text and settings that are stored in Drupal as variables. These variables include text such as 'site name' and 'site slogan', as well as settings like 'Default front page' and 'Default 404 page'.

The Variable translation module has a dependency on the Variable module.

And these are the specific steps required to make a variable multilangual (mentioned on that community page):

Enable the Variable translation module included with the Internationalization package
Go to Administration > Configuration > Regional and language > Multilingual settings
Click on the Variables tab
Select the variables that will be multilingual
Click Save configuration button

Obviously, in this case in step 4 the variable to be selected is "Default front frontpage", within "Site information".

Finally, this is what remains to be done (another quote from that same page):

  Once you have the correct settings, they'll be marked with "This is a multilingual variable" when you go to the corresponding administration pages (Figure 2). You must switch the site language while in the administration pages to set the variables for each language. A language switcher link will appear at the top of each administrative page that has multilingual variables.

"That's all" what's needed to specify a language specific value for the frontpage of your site ...


How to show the data returned via hook_views_data() in a page? I have hook_views_api as follows :

function hook_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'faq') . '/views',
  );
}

and i have the hook_views_data() function in views folder as follows :

function hook_views_data() {
  // faq_questions table.
  $data['faq_questions']['table']['group'] = t('FAQ');
  $data['faq_questions']['table']['join'] = array(
    'node' => array(
      'left_field' => 'nid',
      'field' => 'nid',
    ),
  );
  $data['faq_questions']['question'] = array(
    'title' => t('FAQ short question'),
    'help' => t('The short question text for FAQ nodes.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );
  $data['faq_questions']['detailed_question'] = array(
    'title' => t('FAQ detailed question'),
    'help' => t('The long question text for FAQ nodes.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
  );

  return $data;
}

How can i show the results returned by the hook_views_data() in a page ?

You should be able to print the output to the page using print_r. Just add print_r($data) at the end of the function, before your return statement.

If you're just printing this data out so you can take a look at it for debugging purposes than you might want to use error_log instead. For error_log just add error_log(print_r($data, 1)) at the end of your function, before the return statement.


Display user role with the Advanced forum module I use the Advanced forum and the Author pane modules.

I want to show the role the user has, as in the following screenshot.

I looked everywhere, but I have not found a real solution.

NB: I'm not a PHP expert.

In advanced forum module edit advf-author-pane.tpl.php in your chosen forum theme and and below print $account_name; you'll need a similar line like print implode(', ', $account['roles'];. It should be wrapped in some HTML tag (span, p, ...) so you can style its display.


Translated menu items with menu_build_tree in drupal 7 I'm having an issue with menu item translations with custom rendering of menu tree.

I see all languages displayed at the same time whenever I change the current language. Items have translation set it works if I enable the built-in main menu block but not with my code.

I've tried adding 't($string)' and set 'language' in params; but no luck.

What am I doing wrong here ?

I have the following code in template.php for my theme :

function theme_preprocess_page(&$variables) {

    $params = array('max_depth' => 3, 'language' => 'fr');
    $menu = menu_build_tree('main-menu', $params);
    $main_menu_tree = menu_build_tree('main-menu', $params);
    $html = '
';

    if (arg(0) == 'node' && is_numeric(arg(1)))
        $nodeid = arg(1);

    foreach ($main_menu_tree as $item_menu) {//for each main element
        $isSecondLevel = isset($item_menu['below']) && !empty($item_menu['below']);
        $active = '';
        if ($item_menu['link']['link_path'] == 'node/' . $nodeid) { $active = 'active';
        }
        if ($isSecondLevel) {
            $html .= '
';
        } else {
            $html .= '
';
        }

        $html .= '';
        $html .= $item_menu['link']['link_title'];
        $html .= '';

        //is there any sub elements to display
        if ($isSecondLevel) {
            $html .= '
';

            foreach ($item_menu['below'] as $item_submenu) {//for each sub element
                $isThirdLevel = isset($item_submenu['below']) && !empty($item_submenu['below']) ? 'main-menu-third_level' : '';

                $html .= '
';
                $html .= '';

                $html .= t($item_submenu['link']['link_title']);

                $html .= '';
                $html .= '
';
            }
            $html .= '
';
        }
        $html .= '
';
    }
    $html .= '
';
    $variables['main_menu_html'] = $html;
}

Normaly I use i18n_menu_translated_tree function. For example:

$main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));


Drupal 7 Commerce Stock - Setup stock rules on purchase success for all line items? Currently im trying to setup the stock rules for drupal 7 commerce, but I'm not sure how to go about setting up the rules to deduct stock on purchase success. I have the following: http://prntscr.com/24d0b5

As for the following action: Decrease the product stock level, given a line item

I have this: http://prntscr.com/24d0u8

Currently it only applies to line-item:0 , But how do I make it apply to all line items? Can someone take a snapshot of how their configuration is for this stock rules setup?

thanks

Firstly, make sure there is a Line items loop(Data Selector -> commerce-order:commerce-line-items). Then While adding the action, please make sure it is added to the already added Line item Loop(you will find under the 'operations' tab) and NOT as a new 'Add action' at the bottom.


How to connect to MySQL with SSL connection I have Drupal 7.24 / PHP 5.3.27 and am using the PHP native MySQL drivers.  PHPinfo shows that SSL is supported.

I can't seem to get Drupal to connect to MySQL with SSL.  Works fine without it.
I did find a patch 726192-arbitrary-pdo-options-attributes.patch  that looked like it was committed back about 7.17.  However I did not see the patch in my 7.24 that I downloaded.  So I applied the patch.  Still doesn't work.   There are a lot of bad examples of configurations in others questioning how to connect.   My best guess is this configuration.  But again it does not work.  I have test these SSL certs and connection Navicat and it does connect fine

Any suggestions on what to try or where to look??

$databases = array (
  'default' =>
   array (
    'default' =>
     array (
       'database' => 'drupaldb',
       'username' => 'drupaluser',
       'password' => 'password',
       'host' => '192.168.10.100',
       'port' => '3306',
       'driver' => 'mysql',
       'prefix' => '',
       'pdo attributes' => array(
           PDO::MYSQL_ATTR_SSL_KEY => '/path/client-key.pem',
           PDO::MYSQL_ATTR_SSL_CERT => '/path/client-cert.pem',
           PDO::MYSQL_ATTR_SSL_CA => '/path/ca-cert.pem',
        ),
     ),
   ),
);

Finally got it figured out. It's "driver options", not "PDO attributes".

  $databases = array (
    'default' =>
     array (
       'default' =>
        array (
          'database' => 'drupaldb',
          'username' => 'drupaluser',
          'password' => 'password',
          'host' => '192.168.10.100',
          'port' => '3306',
          'driver' => 'mysql',
          'prefix' => '',
          'driver options' => array(
              PDO::MYSQL_ATTR_SSL_KEY => '/path/client-key.pem',
              PDO::MYSQL_ATTR_SSL_CERT => '/path/client-cert.pem',
              PDO::MYSQL_ATTR_SSL_CA => '/path/ca-cert.pem',
           ),
       ),
    ),
  );


Ajaxy entity reference views filter by entity reference view I have two content types that share a taxonomy (Size).

On content type A, I have an "entity reference" to content type B in the form of a checkbox widget.

What I want:
    On the node creation form, when I change the size (without saving), the entity reference filter gets updated appropriately.

What I currently have:
    The entity reference filter only changes when I save the node.

How I got there:

I'm using an Entity Selection views filter by entity reference view

In my entity reference view, the only thing I could come up with is to set a contextual filter of "content has taxonomy term ID"

Then use "provide default value" -> "taxonomy term ID from URL" and "load default filter from node page"

So, If I create a new node of type "A" and set "Size" to "Size X" and SAVE the node, the entity reference gets filtered properly.

What I want to happen is that on the node creation form, when I change the size it dynamically filters the entity reference without having to save the node.

There is no ajax option on an entityreference views display, and I"m not seeing any other modules that seem to solve this.

Can anyone point me in the right direction here?

I'm not sure this question has a good, Drupalish answer.  I've got a crazy idea, though, that you might try.

Instead of letting your users go straight to node/add/typeA, send them first to a custom page where they choose their size. That link will then send them to the node add screen with a TID tacked onto the end, like /node/add/typeA/34.

On the node creation page, your custom module will automatically select the right Size term based on the URL path, and disable the widget so the user can't change it.

In your Entity Reference view, when you provide a default value to your contextual filter, instead of "Taxonomy term ID from URL", simply choose "Raw value from URL" and set the Path component to 4. With any luck, the Entity Reference view will get the TID from your modified URL and show the right list.

When they try to edit that node after creation it gets a bit tricky. You could just forcibly redirect the path to node/[nid]/edit/34 and do the same thing, but now you've made it so the user can never change the category after they select it the first time, which is bad. Maybe you can hijack node/[nid]/edit and send them to your custom page again? I've never seen that done before.

This whole idea kind of craps up the usability of the site, but it's the best idea I can think of, short of writing your own custom AJAX stuff to provide your argument to the ER view manually, rebuild the form, etc.


Media module - CKEditor embed not working - jQuery is not defined I'm trying to use the media module along with CKEditor in a Drupal7 build.
I've enabled the modules, added the embed media button to the editor's toolbar and it works to a point - the image uploads, and styles/variations created. But I can't actually embed it as the final screen of the overlay (type in alt text, choose size etc) the buttons stay as 'fake' buttons.

Looking in console the error is Jquery is not defined.

Anyone have a fix for this?

I worked around this by changing the admin jquery version down to 1.7 using the Jquery Update settings.


How to translate Entityform type name I created a form using Entityform module. I'm not able to translate name of entity form type. How is it possible to translate name for each enabled language?

I found the answer! I was using latest stable release 7.x-2.0-rc1. It does not support i18n but they add a sub module which its name is entityform translation in dev version (7.x-2.x-dev). Once this module is enabled, a translate link appears on the table list of entity form types.


Disable field date and checkbox I'm trying to disable input fields of type date and checkbox in hook_form_alter with above code:

$key = 'field_name';

$form[$key]['widget'][0]['value']['#attributes']['disabled'] = true;
$form[$key]['widget']['#attributes']['disabled'] = true;
$form[$key]['widget'][0]['#attributes']['disabled'] = true;
$form[$key]['widget'][0]['target_id']['#attributes']['disabled'] = true;
$form[$key]['widget'][0]['#attributes']['disabled'] = true;
$form[$key]['#disabled'] = 'disabled';
$form[$key]['widget']['#attributes']['readonly'] = 'readonly';

Disabled all fields (type text or entity reference) but not work for checkbox and date fields.
Any ideas for solve this?

This is how to disable the field:

$form[$key]['widget'][0]['value']['#attributes']['disabled'] = 'disabled';


Adding Values to Header Drupal 7 + .htaccess Well, I'm new to Drupal, I was wondering if I can add values to header?

Note: this is the code for my mysite.com

I got this piece of code in mysite.com

<?php

    if (isset($_GET['code'])) {
    echo $_GET['code'];
    }

?>

So for example,

Drupal URL:

mysite.com/U2pVnWK

If I run that URL, it redirects me to PAGE 404

So I tried this, URL:

mysite.com/?code=U2pVnWK

Which it eventually works.

So I tried using RewriteRule thing in .htaccess and added this code

RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)$ index.php?code=$1

Even change it into

RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)$ ?code=$1

Also

RewriteEngine on
RewriteRule ^([a-zA-Z0-9]+)$ http://www.mysite.com/?code=$1

None of it works.

Plus I don't know where to put that piece of code in existing .htaccess that Drupal made it.

So to simplify, what I want is:

If I access mysite.com/U2pVnWK I would be able to retrieve and echo  U2pVnWK instead of redirecting to PAGE 404 PAGE

Any help would be appreciated. :)

There is something you can try with Drupal itself.

hook_url_inbound_alter

  Alters inbound URL requests.

The idea is to drupal_lookup_path and if nothing found you can do whatever with $path variable in  hook_url_inbound_alter


local copy of my drupal site doesn't seem to link I isntalled a local LAMP system and basically copied my site into /var/www/ for some local "experiments" (without messing around with the live site). I've mirrored the db and everything. Now when I go to http://127.0.0.1/ my home page is loaded well but all the links (e.g. http://127.0.0.1/content/lodge) won't load, I just get 404 Not Found. I assume I'm missing some kind of php or apache setting.

edit1

I did

sudo a2enmod rewrite
sudo /etc/init.d/apache2 restart

but this didn't seem to have made a change at all.
Now within /etc/apache2/sites-available/ I have two files 000-default.conf, default-ssl.conf.
000-default.conf contains:

ServerAdmin webmaster@localhost
DocumentRoot /var/www
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

and default-ssl.conf contains

ServerAdmin webmaster@localhost
DocumentRoot /var/www
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine on
SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-6]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown

and I'm not exactly sre where to add AllowOverride All, can you be a little more specific?

Oh and .htaccess is in /var/www/ too

edit 2

okay, now what I did, I installed a fresh copy of drupal in http://127.0.0.1/alternatives/Quaaout/ and if I use the original site folder with a new db, urls like http://127.0.0.1/alternatives/Quaaout/?q=user work just fine! But if I use my site/ directory from the live site, this url automatically leads me to a 404 at page http://127.0.0.1/alternatives/Quaaout/user and the difference makes which database I have setup in my settings.php - with the new db from the fresh copy, ?q=user works fine, with the live copy it doesn't. So I thought it may be the url redirections I have setup in table redirect but I cleared it and it still didn't work.  So it's not the redirections, what else would be causing this?

Make sure apache has mod_rewrite enabled, and that the drupal .htaccess file is there in your drupal root. If you're on debian/ubuntu, you should be able to do:

sudo a2enmod rewrite
sudo /etc/init.d/apache2 restart


Need guidance installing Drush I have successfully installed composer, but when i try to install drush and modify the .~/.bashrc file it returns Content-Type: text/html when i run any kinda of drush command.

Anyone seen anything like this? Sorry can't be more specific but can get you  any info you need to be helpful..

If you see Content-Type: text/html when running Drush commands, it means that you are running Drush with php-cgi instead of php-cli.

If you already have php-cli on your system, set the environment variable DRUSH_PHP to point to the full path of php-cli.  If you do not have it installed yet, try installing it and see if that clears up your trouble (sudo apt-get install php5-cli on Ubuntu).


Print image path in a View? I have a content type that has an image attached. In a View I need to print the full path to the image.

I thought this would be easy but for some reason I cant figure it out. I can find the image field in the view, but when I rewrite the output I cant see any patterns for the file path.

In my view Ive created a relationship to the image field to the node, but this doesn't provide me with any more rewrite patterns, or any fields that look like they could be the image path.

Found the answer here:
https://drupal.org/node/1051320

Create your view as normal.
Add your image field as normal.
Go to relationships
Add Relationship "File Usage"
Go back to fields section
Under groups, a new option "File" will appear
Selecting file will output the path for every file field on your site. If you want it just for one particular image field follows these steps:

Add the new "File" field
In file field, select "exclude from display".
Go back to your image field (created in step 2)
Select "Rewrite the output of this field"
Under tokens, use the token for the file field (created in step 6). (NB the file field must come before the image field, or else the token will not appear).

Hope this helps somebody!


Can I strip my form of some classes and DIVs? Can I strip my form of these classes and DIVs as shown in the code below?

<form action="/example/unsubscribe" method="post" id="exampleform-unsubscribe" accept-charset="UTF-8">

/** this div **/

/** strip these class and add my own class? **/
      E-mail address */** strip classes form-required from span **/
      <input type="text" id="edit-email" name="email" value="" size="60" maxlength="128" class="form-text required" />/** strip form-text and required class **/

    <input type="submit" id="edit-submit" name="op" value="Remove me!" class="form-submit" />/** remove form-submit class **/ <input type="hidden" name="form_build_id" value="formjKkl1KLWJLnv0hM4DSVd8-40boTgBQAzWWhUn44c15Q" />
    <input type="hidden" name="form_token" value="LB07DqsDXK9idWdOHLxUen7jKxm52JqTyHiR7-pNumA" />
    <input type="hidden" name="form_id" value="exampleform_unsubscribe" />

/** this div **/
</form>

Would it affect any form or ajax form functions of the form?

There are 2 Drupal theme functions which you need to override in your theme's template.php

You can paste this code in your theme's template.php and change "themename" to the name of your theme (Drupal 7 code):

It shouldn't affect any ajax form functions if you have a custom theme, however if you are using a contributed theme you should check the javascript files to see if there are any functions using the classes / selectors you have stripped out.

Override theme_form() to remove the div

function themename_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
}
element_set_attributes($element, array('method', 'id'));
if (empty($element['#attributes']['accept-charset'])) {
 $element['#attributes']['accept-charset'] = "UTF-8";
}
return '' . $element['#children'] . '';
}
Override theme_form_element() function to strip out the classes

function themename_form_element($variables) {
  $element = &$variables['element'];
  $element += array(
    '#title_display' => 'before',
  );
  if (isset($element['#markup']) && !empty($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  // Remove line below if you don't want a custom class
  $attributes['class'] = array('your-custom-class');

// Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '' . "\n";
  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element['#title_display'] = 'none';
  }

$prefix = isset($element['#field_prefix']) ? '' .   $element['#field_prefix'] . ' ' : '';

$suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';

switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

case 'after':
  $output .= ' ' . $prefix . $element['#children'] . $suffix;
  $output .= ' ' . theme('form_element_label', $variables) . "\n";
  break;

case 'none':
case 'attribute':
  // Output no label and no required marker, only the children.
  $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  break;

}

if (!empty($element['#description'])) {
    $output .= '' . $element['#description'] . "\n";
  }

$output .= "\n";

return $output;
}


need path of an image created using an image style <?php
  $node=node_load(3);
  $theme_img = file_create_url($node->field_theme_image[$node->language][0]['uri']);  //origional image path
  print $theme_img;
?>

I am trying to load an image in "page--front.tpl.php", which was created from a content of node value 3.
Using above code, I am able to get origional image url. But I need path of image created using image style (home_theme)

You can use image_style_url($style_name, $path)

Example:

$img_url = $node->field_image['und'][0]['uri'];
<img src="<?php print image_style_url("thumbnail", $img_url); ?>" />

Where you will be replacing thumbnail with the image style name you have in place


How do I stop automatic double break tags in ckeditor? After updating the ckeditor module i find that saving existing content results in adding another break tag following existing break tags. When i create new content and press enter and save the final result has an additional break tags.

This is what i should be seeing according to the source button on the editor:

The quick brown fox jumps over the lazy dog. The five boxing wizards jump quickly.

Pack my box with five dozen liquor jugs. Jackdaws love my big sphinx of quartz.

This is a second paragraphs made with two line breaks. Lets see if the editor decides to use two break tags or 4 break tags. These should also be enclosed with a paragraph tag instead of separated by two break tags.

This third paragraph is now being separated by three break tags. Lets see if the editor decides to make this as size break tags instead of just three break tags. This Should be wrapped around a paragraph but also have a break tag above it.

However what i see when i save the page ends up being:

The quick brown fox jumps over the lazy dog. The five boxing wizards jump quickly.

Pack my box with five dozen liquor jugs. Jackdaws love my big sphinx of quartz.

This is a second paragraphs made with two line breaks. Lets see if the editor decides to use two break tags or 4 break tags. These should also be enclosed with a paragraph tag instead of separated by two break tags.

This third paragraph is now being separated by three break tags. Lets see if the editor decides to make this as size break tags instead of just three break tags. This Should be wrapped around a paragraph but also have a break tag above it.

The answer in this post helped me out:
CKeditor adding an extra
 tag when a
 tag is encountered

basically go into
administration > configuration > content authoring > text formats.

then select the text format that's causing problems and unselect "convert line breaks into html" and save configuration.

Then clear all caches on Drupal and browser. The content should go back to normal just by visiting the page while you are signed in otherwise saving over it should fix the problem.


Is registering a controller as a service still frowned upon in D8 In the presentation given in Portland by Kat Bailey in May, registering a controller class as a service was highly discouraged, however a lot has changed since then and I wanted to check if this is still the case.

It is well supported in the code and you can route to actions in the controller you registered via reference to the service id, such as.

 defaults:
   _content: 'my.controller:myAction'

Rather than referring to the controller class directly.

I can foresee at least a couple of use cases, primarily at the moment it allows an easy option to override / extend an entire controller via replacing the service.

The only other way I know to do that at the moment would be to register an event subscriber to override all the routes to a particular controller which would be rather long winded. Views currently overrides individual routes controller actions this way to reset routes for views with paths (which makes sense as that is more of a path by path based surgical strike).

I don't won't to start down a path that turns out to be a big D8 anti-pattern, but if service controllers are bad, what is the alternative to allow simple replacement of a controller in another module?

From a Symfony docs discussion

fabpot commented

  @lsmith77 is right. I strongly believe that this is NOT a best practice. I don't recommend it at all. That's why it's not in the book and explained in a cookbook entry.

mahono commented

  It would be nice to understand why what is (not) best practice. @fabpot: could you give some more info why you think so (or is there more information about that somewhere else?) To me most important is to learn best practices how to make my bundles customizable.

fabpot commented

  The DIC mostly helps manage "global" objects. Controllers are not global objects. Moreover, a controller should be as thin as possible. It's mainly the glue between your Model and the View/Templates. So, if you need to be able to customize then, it probably means that you need to refactor them and extract the business logic from them.

With that said, here's a blogpost arguing for controllers as services: http://pooteeweet.org/blog/1947


Community website - User rating based on votes in Node + Statistics I am planning to build a community based website where users would be able to rate the content uploaded by others. I have gone through many blog posts and Stack Exchange questions too, but what I want could not be answered in any of it.

What I got:

User Points module: To associate points to author of a node (content) if the node (content) is up-voted or downn-voted - This, as I understand, can be done using Rules.
Rate module or Fivestar module - To provide rating mechanism for a particular node (content) provided by the author.

I would want to extract statistics like:

Highest rated article for a period of time - Like 1 month or between 'from' and 'to' date etc.
User who has accumulated highest points within a period of time
Etc.

This basically lets me evaluate and find out the most 'liked' or 'popular' user or most 'liked' or 'popular' article within a period of time to award them some goodies.

So, how can I achieve this?

I have done some homework, stumbled upon some threads but could not find what exactly I needed:

How to implement a reputation based system with badges in Drupal similar to StackExchange sites?
Radioactivity: http://www.webomelette.com/drupal-radioactivity-module

I haven't used User Points Module but for fivestar module or module based on Voting api you can create a view of content and add a relationship with vote results and you will get the aggregation you need i.e average/total number/total score  for that node then you can add a Vote results :Timestamp filter to get the results in between dates. You can add sort and limit to display the way you want.


Ubercart - Manual Credit Card Processing This has ALWAYS been the reason why I haven't used Ubercart...the lack of a module that allows for offline (manual) credit card information.

It has been a few years now since I looked last and I am wondering if this is STILL not an option with Ubercart. I did some searches and it still looks like there is nothing.

Anyone?

I believe this is more of a workflow question than, a lack of module(s) question.    You can setup Ubercart so that you accept an order without accepting a payment.   You can set the status of the order as non-processed.   You then process their payment manually (via phone, online, inperson, etc), then, manually, change the status of their order to process.


What's better to do when we create a new site project? I need an advice about beginning a new project layout in Drupal 7. Do you think it is better starting with a basic theme, or creating from zero the project with theme of mine?
I think it is probably better to begin with a basic theme also for the CSS styles that are compatible with all the browsers

What do you say?

It depends on your site and the needs of your client, but it is probably best to start with an easy base theme and then start theming on top of that.

Some good basic base themes are:
Omega - Best used for responsive HTML5 designs
Zen - Good basic starter theme
960gs - Good if you need to use a grid format.

Also, you might want to grab some other themes for administration.

Recommended administration themes:
Rubik - Clean administrative interface
Admin - Adds a toolbar at the top of the site, which makes Drupal easier to manage


Different Image on each Mainmenu entry in Drupal 7 there is a Logo and a variable picture in the header of my design. This picture depends on the current page.

Is there a plugin or even a build in setting, where i can configure this behavior?

You may try this module, which seems to do exactly that.


Problems with altering a form I'm wanting to alter the commerce cart page form.

By using var_dump($form_id) or chrome inspect I can see the id is id="views-form-commerce-cart-form-orange-default-42". If I write my hook as :

function module_form_views_form_commerce_cart_form_orange_default_42_alter

I can see that I am altering the form. But this has been altered in my theme hence the extra bit on the id orange_default_42. If I do :

function testingstuffs_form_views_form_commerce_cart_form_alter

I cannot alter the form.

How do I hook into this form correctly / is there  a correct way to find form ids?

The issue here is that there are probably two form IDs for the form. One is the form_id, and the lesser known one is the base_form_id. If a Drupal form is used more than once on a page, weird things come about. To get around this, form developers can set the form ID to be dynamic, so that each time the form is built, it's given a unique ID. Example:

class FooBarForm implements FormInterface {

  protected $id;

  public function __construct($type) {
    $this->id = $id;
  }

  public function getFormId() {
    return 'foo_bar_form-' . $this->id;
  }
}

class FooRouteController {

  public function fooBarForm(ContentEntityInterface $entity) {
    $form = new FooBarForm($entity->id());

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

Forms can also implement BaseFormIdInterface, which requires them to implement BaseFormIdInterface::getBaseFormId(). The form ID returned from this hook will be the same for all instances of the form, and NOT dynamic.

class FooBarForm implements FormInterface, BaseFormIdInterface {

  protected $id;

  public function __construct($type) {
    $this->id = $id;
  }

  public function getFormId() {
    return 'foo_bar_form-' . $this->id;
  }

  public function getBaseFormId() {
    return 'foo_bar_form';
  }
}

The relevance of this is that there are actually multiple form alter hooks called, in this order:

hook_form_alter()
hook_form_BASE_FORM_ID_alter()
hook_form_FORM_ID_alter()

Looking at your hook - module_form_views_form_commerce_cart_form_orange_default_42_alter, it would appear you are implementing the third hook. The ID of 42 is being appended as part of the dynamic Form ID.

To find out the base form ID (if one exists), you can call the following in your form:

$form_state->getBuildInfo()

This will give you the build info, which you can dump with kint() or however you do your debugging. In the build info will be the base form ID (assuming it's set). If it is, you can implement the second form alter hook above, using that base form ID.


How to disable a feature whose checkbox is grayed out? I would like to disable some features, but they are grayed out. What does that mean? I assume some kind of dependency? (I am using Drupal Commons and would like to disable groups.)

This is true for Module page and Features page:

The page should list out the dependencies and modules/features that are dependent on that module/feature so you would have to turn off those modules/features before you can turn off the one that is disabled, if you use drush it will tell you that you are turning off all dependent modules when you perform drush dis modulename

One thing to note: on some setups that dependency list may be collapsed. Certain developer/helper modules will collapse those options on the modules page so you may have to click to expand but the reason why a module could not be disabled is b/c it is a dependency for another module so unless you are using drush like mentioned above you will need to turn off all the modules listed as needing that module to operate first.


How do I create a calendar of events? I am needing a solution to add an event to a calendar, and the events are also displayed on a web page in order of the next event.

Similar to this Wordpress plugin:
https://wordpress.org/plugins/the-events-calendar/screenshots/

Any help is greatly appreciated.

As it stands, there are a few options from a module perspective.

Calendar
FullCalendar
Google Calendar

Calendar and FullCalendar are the popular calendaring options in Drupal - neither seem to have a stable Drupal 8 release yet but their dev branches may be workable. You'd have to try, and read through their issue queue to understand where they are at functionality wise.

Lastly, you could iframe embed a Google Calendar onto a page. But as you may have guessed, this means events need to be managed in Google Calendar itself, unless you set up a sync from Drupal to Google Calendar.

Other than that, there are no 'ready made' modules for this yet that are stable and production ready for Drupal 8. It looks like the others only have a Drupal 7 release or have been abandoned.


Bypassing Drupal's htaccess rewrite for static page I've created a site that is currently partly static while partly managed in Drupal.

I've managed to rewrite static HTML by specifying the /static directory in the following manner above Drupal's .htaccess code.

RewriteEngine on
RewriteRule ^about-us/(.*) static/about-us/$1 [L]

Though I now have a dilemma. I have a directory page which is static:

  website.com/products

but then the next level needs to go through the Drupal system:

  website.com/products/product-type

to add to complication the next level then should go back to the static directory:

  website.com/products/product-type/product

Is this possible? And if so how would you achieve it?

Notes

Please note that these do not need to be dynamic. Can easily declare 'product-type' as there will only be 3. It would be good if I didn't have to declare 'product' because there will be multiple under each 'product type'.

My temporary fix was to just use a different directory in the URL. I added 's' to 'product-type' (website.com/products/product-types) for that specific page, and then at product level went back to remove the s (website.com/products/product-type/product)

Look at Drupal's .htaccess, lines 110 to 113:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

It means if you create directory "products", every static file that's there will be served and all the rest will be directed to Drupal. Simple as this. If it's not working for you, you need to provide more details or fill a bug report.


setting default language in drupal multilingual module In my website, I have 2 language English and Marathi.
1st default language is English and I have added some content too.
but now my requirement is to set default language as Marathi.

I have gone to admin/config/regional/language setting and done default language as Marathi but not its working.

Please someone help to solve this prob.
I want default language on my site as Marathi.

Please check these steps as described on this link, How to Change the Default Language of a Drupal Site. You might come to know which step you are missing.


How do I set variables for variable_get()? I am trying to understand variable_get(). I read so far that you can set variables in the settings.php using the $conf array and retrieve them later in code by using variable_get(). I have read that you can also use variable_get() to retrieve values from the database.

How does this work?
Is there a table that is automatically built?
How would you set variables if this feature is possible?

Maybe you hope to learn that variable_set is the magical way to store all kinds of structured data in your database, and that variable_get is the way to get it out again. Unfortunately, it is not.

The "persistent variables", as they are often called, are meant for relatively simple key-value pairs that should persist across requests, users and sessions, often until a site admin changes the value. A good example is the site name.

So how does it work?

When Drupal is bootstrapped, all variables are read from the cache (if available) or from the variables table. (See variable_initialize for the exact code.) The variables and stored in the global $conf variable, a huge array. Drupal does this because it's more efficient than doing a database query every time a variable is needed. (It's also the reason why variable_set is not suitable for large blobs of data: they would be loaded on every request!)

Whenever you use variable_get('variable_name', 'default_value'), the variable name is looked up in the $conf array. If it exists, the value is returned; else, the default value is returned.

Finally, there is a third member of the family: variable_del. As the name implies, this deletes a variable from the variables table. This function is often used in hook_uninstall implementations, deleting variables when a module is uninstalled.

If you are looking for ways to store more complex custom data structures in the database, check out hook_schema and drupal_write_record, or use the Drupal entity system and Entity API.


Any D7 modules similar to the Project Issues module? Are there any D7 modules similar to the Project issues module?

There is a 7.x-2.x branch of the module in git.


How to show the content on ajax or Jquery lightbox I have created views custom template file for one of my view and works fine. And how can i show fields content(second in the below code) on Lightbox popup box when the user clicks on title field.

 <?php dpm($fields); ?>
   <?php print $fields["title"]->content; ?>

   <?php print
 $fields["field_availability"]->content; ?>

You should describe the problem you are facing ...
What 'lightbox-meme' are you trying to implement ?

If you are using the lightbox module for drupal, you should read the README.txt, that is pretty self-explanatory.

Hope this helps.


Is there a way to track or record users entered taxonomy? Is there a way to track, flag, or record a users entered taxonomy even if perhaps they may have changed it (tagging). So basically I am trying to set up a list of all the taxonomy tags a user created. The thing these tags can be changed and manipulated by the user so I am wondering if the originals can still be added to my list after they may have changed to a new tag. For example, a user recording places of employment.

You may want to take a look at the Community Tags project.  We have used it on a few sites.  From the project page:

  The Module has three main features:
  1. Stores who tagged what and when.
  2. Allows for this information to be exposed with views.
  3. Adds an easy AJAX interface for tagging nodes without going to node/edit.