Integrity constraint violation: 1052 Column 'uid' in on clause is ambiguous I am using migrate module to transfer data from one site to another here is my query

$query = Database::getConnection('db1', 'db1')
        ->select('users', 'u');
$query->leftjoin('field_data_field_user_insti_name', 'insti_name', 'insti_name.entity_id = u.uid and insti_name.bundle = \'user\'');
$query->leftjoin('users_roles', 'ur', 'ur.uid = u.uid');
$query->fields('u', array('uid', 'name', 'mail', 'pass', 'status'));
$query->fields('insti_name', array('field_user_insti_name_target_id'));
$query->condition('u.uid', '1', '>');
$query->condition('ur.rid', '6', '!=');
$query->distinct();

than I am getting this error

  Integrity constraint violation: 1052 Column 'uid' in on clause is ambiguous

I found a solution for this problem that i have to add line

$this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));

After this error is solved, but don't know what this line do, is it safe to use this line

You have to add alias in MigrateSQLMap

$this->map = new MigrateSQLMap($this->machineName,
   array(
       'uid' => array(
           'type' => 'int',
           'not null' => TRUE,
           'alias' => 'u',
       )
   ),
) ;


How do I restore the comment body field I deleted from a content type? I deleted the comment body from the content type settings, and replaced it with  another field. When posting comments, I get this error:

  Notice: Undefined property: stdClass::$comment_body in function comment_submit() (line 2201 in file /modules/comment/comment.module).

Can this error be avoided?

It was needed to delete the field comment_body becase field permissions are inherited for all the content types and that is why another field was created and this one was deleted.

Create a random content type
Restore the comment_body field from existing field`s, because it's existing now
Delete the random content type


Which type to use for checkbox fields in hook_field_schema? Task:

Create a custom field which contains a single checkbox by implementing hook_field_schema etc.

Question:

Which data type is (or should) be used to define the corresponding database column to save checkbox values?

Sample code:

function field_test_field_schema ($field)
{
    $columns = array();
    switch ($field['type']) {
        case 'test':
            $columns = array(
                    'value' => array(
                            'type' => '???',
                            'not null' => TRUE
                    ),
            );
            break;
    }
    return array('columns'=> $columns);
}

Update:
node_schema uses int for boolean columns. e.g. :

'status' => array(
  'description' => 'Boolean indicating whether the node is published (visible to non-administrators).',
  'type' => 'int',
  'not null' => TRUE,
  'default' => 1,
)

A tiny int would be most appropriate in my opinion:

$columns = array(
  'value' => array(
    'type' => 'int',
    'not null' => TRUE,
    'size' => 'tiny',
    'default' => 0,
  ),
);

A 'standard' int would be overkill for a field that will only ever hold a 0 or 1 value.

See the Data types docs for an overview of the different types available to you.


Users can't use a name in comments that is equal to the username of a registred user I have a Drupal 7.7 installation for which I'm activating comments using the standard Comments module. Everything works just fine except for a annoying quirk.

The admin username is "Christoffer", and for some reason anonymous users can not use the name "Christoffer" for their comments. If I add an additional character or change the spelling it works but it seems that an anonymous user cannot have the same name as a registred user. Can I allow it somehow?

Thanks

It is not possible. The form validation handler for the comment form (comment_form_validate()) doesn't allow to the anonymous users to choose a username that has been already used by a registered user. The function contains the following code:

  elseif ($form_state['values']['is_anonymous']) {
    // Validate anonymous comment author fields (if given). If the (original)
    // author of this comment was an anonymous user, verify that no registered
    // user with this name exists.
    if ($form_state['values']['name']) {
      $query = db_select('users', 'u');
      $query->addField('u', 'uid', 'uid');
      $taken = $query
        ->condition('name', db_like($form_state['values']['name']), 'LIKE')
        ->countQuery()
        ->execute()
        ->fetchField();
      if ($taken) {
        form_set_error('name', t('The name you used belongs to a registered user.'));
      }
    }

The code avoid the confusion there could be between anonymous users that reports the link to
their homepage and an authenticated user, when the anonymous users would use a username already in use.

To remove that limitation (which I don't think it's a good idea), you should implement hook_form_comment_form_alter() to add your own validation handler (with $form['#validate'][] = 'mymodule_comment_form_validate', or similar code. Your form validation handler should be a copy of the one used from the Comment module, except the part that reports an error when an authenticated user is already using that username.
There is another problem, though; the form validation handler used by the Comment module contains the following code:

  if (!empty($form_state['values']['cid'])) {
    // Verify the name in case it is being changed from being anonymous.
    $account = user_load_by_name($form_state['values']['name']);
    $form_state['values']['uid'] = $account ? $account->uid : 0;
    // …
  }

In your case, if an anonymous user would use "Christoffer" as username, and that is already used by an authenticated user, the code would load the user object for the authenticated user, and the comment would be attributed to the authenticated user, not the anonymous user.

There could be also other code in the Comment module that takes the assumption there cannot be two users with the same username, which is a restriction present in Drupal.


Drag & drop upload plugin, how to make it multiple I am trying to use this module to upload multiple files into a schemma that I created (in a separated module),

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

$form['file'] = array (
'#type' => 'dragndrop_upload',
'#title' => 'Test',
'#description' => 'Test',
// This settings allows to drop multiple files at once.
'#attributes' => array (
        'multiupload' => '1',
'cardinality' => '10')
);

Seems to work great but it seems to ignore the 'multiupload' and the 'cardinality' arguments,

Any idea what am I missing?

It suggests you need this module; from the README file and project page;

  Multi-upload support will be enabled if Multiupload Filefield Widget
  module exists.


Views: Use like operator in exposed search filter (Search: Search Terms) In a view, I am using an exposed filter of keyword search (Search: Search Terms). The default behavior of the filter is to select exact matches. I need to have similar words also selected. For instance when the visitor searches for "paint", she should see "painting" or "painter" too.

Similar to the "LIKE" operator in mysql.

When you set a new filter in views on a field (for example node title), you can set the Operator to contains which is the equivalent of SQL LIKE.
You can also expose the filter and the operator to the visitor.
If you want to see the SQL query in the preview, check the option Show the SQL query in view setting.

Instead of Search: Search Terms, use Global: Combine fields filter; it will allow you to search multiple fields using the operator you want.


Can I add a link to the node reference when using the autocomplete widget? I love the autocomplete widget for the References module in Drupal 7, but I find it odd that it doesn't include either a link to the referenced node (view or edit)?

Is there some way in hook_form_alter that I can add this somehow?

I can do this:

$form['field_lessons']['und'][0]['#suffix'] = 'Edit';

And the autocomplete field has an edit link underneath of it, but this doesn't work:

foreach($form['field_lessons']['und'] AS $lesson) {
  $lesson['#suffix'] = 'Edit';
}

And also loops 10+ times even though I only have 1 node reference currently :s

I don't necessarily like it but I can do it in Javascript like this and the Drag & Drop still works:

$('#edit-field-lessons .form-item').each(function(i) {
  var lesson_nid = $(this).find('input[type="text"]').val();
  lesson_nid = lesson_nid.substring(lesson_nid.indexOf('[nid:')+5, lesson_nid.indexOf(']'));

  $(this).append('View');
  $(this).append('Edit');
});

This'll do the trick (I've tested it this time ;) ):

foreach($form['field_lessons'][LANGUAGE_NONE] as $key => $lesson) {
  // If we have a default value for the nid, we have a populated node reference
  if (isset($lesson['nid']) && is_array($lesson['nid']) && $lesson['nid']['#default_value'])) {
    // Get the nid
    $nid = $lesson['nid']['#default_value'];

    // Create an edit link
    $link = l('Edit', "node/$nid/edit");

    // Add it to the element
    $form['field_lessons'][LANGUAGE_NONE][$key]['nid']['#suffix'] = $link;
  }
}


Google Analytics Marketplace I'm running Drupal 7 along with the Google Analytics module. I have an eCommerce Marketplace setup with store fronts and unique products per store. I'd like to have analytics per store so that each store owner can see the traffic coming to their page/products.

I'm using Organic Groups to setup the stores with Group Type: Store and Group Content: Products. I have custom variables setup relating to the Group Reference.

My question is:

How can I filter page requests in Google Analytics to specifically those relating to a certain group/store so that when a store owner views their analytics they are only seeing the requests for their "pages"?

One option may be to simply bring the Google Analytics data into your website, where you can then leverage the power of views to display the view statistics for the exact pages you want.

If you use the Google Analytics Statistics module, you should be able to set it up to download view stats either for the past 24 hours, 48 hours, week, month, etc and it'll do that as you run cron.  The config page is at /admin/config/system/ga_stats.  After connecting it to your Google Account by typing in your Google Login, the module setup looks something like this:

Then - you can view your Google Analytics statistics on your site (rather than through the Google Analytics interface) and can create any number of views for your different page groups as you want.  The module integrates with views...

Let us know if that works for you.

I've only recently found out about this module and started using it, so I'd be interested in any others chiming in here...


How to make field label as node reference link? If I have field label as Links and type is a node reference link to Page Title. And its displayed like this:

Links: Page Title

How to make the label is the link to the node without showing Page Title like this:

Links

I propose to do so (if you have a module Display Suite):

Go to ../admin/structure/ds/view_modes

Add a view mode: name is "label" and entities: "Node"

Then go to ../admin/structure/types/manage/your-content-type/display and on "Custom display settings" tab check the "Label" mode

Now go to ../admin/structure/types/manage/your-content-type/display/label select "Reset" (ds_reset) Layout, then make visible only the "Read more" and customise it: "Link text" - "See details" for example...

Then on referenced content type select "Rendered entity", and "View mode" - "Label"

Done!


hook_form_alter help (almost there!) There are two parts of a third-party module that I am trying to alter.

When the user clicks submit
When the user clicks reset

This is the function from that module.

function linkedin_user_settings_form($form, &$form_state, $account) {
  // Just fetch forms from submodules.
  $form['linkedin']['elements'] = module_invoke_all('linkedin_user_settings_page', $account);
  // We will need the account at submit
  $form['#account'] = $account;

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
  );
  $form['linkedin']['reset'] = array(
    '#type' => 'submit',
    '#description' => t('Click here to unlink your LinkedIn account.'),
    '#value' => t('Unlink'),
  );

  return $form;
}

This is the code in my module.

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'linkedin_user_settings_form') {
    $form['#submit'][] = 'my_module_form_submit';
  }
}

function my_module_form_submit($form,$form_state) {
  // on submit do this
  drupal_set_message(t('You Saved'));

  // on reset do this
  drupal_set_message(t('You Reset'));
}

How can I check which button on the form has been clicked from the users?

You should be able to just copy what that linkedin code is doing in it's own linkedin_user_settings_form_submit submit function:

$op = $form_state['values']['op'];
if ($op == $form['linkedin']['reset']['#value']) {
 drupal_set_message(t('LinkedIn preferences have been reset'));
} else {
  drupal_set_message(t('LinkedIn preferences have been saved'));
}


D7 views list of nodes with node reference count I have two content types A and B. The content type B has a node reference to A.
I would like to create a views list which show nodes of A with no. of node count of B.
It is very similar to a list of nodes which comment count for each.

I am not too up on D7, but the Nodereference Count module has worked for me in D6 and there appears to be a D7 version.


Drupal Default Language Fallback I have a multilingual website in Drupal 7. It has a menu bar with 10 menu items. Among them I have translated 5 menu items to Dutch. When I switch the language from English to Dutch, only the translated menu items appear. I would like to display those 5 menu items in Dutch as well as those items which are not translated in default English Language.

Could someone propose me a solution or a module to implement the same.

Most solutions are for individual content or entire Menu and not for individual menu items.

Thanks in advance for the help rendered :D

Multilingual menu's are quite nasty sometimes. I suppose you use i18n menu? Then have a look at the following:

Make sure the Menu link enabled only for the [LANGUAGE] language, on the menu tab of the node edit page is disabled. That makes sure the entry is shown on all pages.

Also make sure the menu entry is language neutral by going to admin > structure > menu's > [MENU NAME] > [MENU ITEM] and check the language drop-down.


How to return a DatabaseStatementBase object I have a method that extends the execute() method used in the Drupal 7 database abstraction layer.

When used with db_query, such as:

$result = my_extended_db_query("SELECT * FROM {node} WHERE nid<100")->execute();

$result holds a DatabaseStatementBase object, whether there are resulting rows or not. However, following:

return $result;

the calling function receives an empty array if there had been no query results, instead of a DatabaseStatementBase object. Because of this, ->fetchAll() fails because it is attempting to operate on a non-object.

How do I get my return to arrive as the same object is started as?

The method:

public function execute() {
$sql = $this->sql;
switch ($this->function) {
  case 'db_query':
    if ($this->args) {
      $args = $this->args;
      uksort($args,"si_stats_sort_by_length");
      foreach($args as $name => $value) {
        $sql = str_replace("{" . $name . "}",$value,$sql);
        if (is_array($value)) {
          $sql = str_replace($name,"('" . implode("', '",$value) . "')",$sql);
        } else {
          $sql = str_replace($name,"'" . str_replace("'","''",$value) . "'",$sql);
        }
      }
      try {
        $query = db_query($sql);
      }
      catch (Exception $e) {
        // log the error
        $msg = $e->getMessage() . "\n";
        $msg .= $e->getTraceAsString() . "\n";
        mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
      }
      return $query;
    } else {
      try {
        $query = db_query($sql);
      }
      catch (Exception $e) {
        // log the error
        $msg = $e->getMessage() . "\n";
        $msg .= $e->getTraceAsString() . "\n";
        mylog($msg . PHP_EOL . PHP_EOL . $sql, debug_backtrace(), LOG_ERROR);
      }
      return $query;
    }

Bandaid fix, instead of return $query; test to see if the class of $query is of DatabaseStatementBase or else create a new empty instance of that class and return that ... Eg:

if (is_a($query, 'DatabaseStatementBase')) {
   return $query;
} else {
  return $empty = new DatabaseStatementBase(Database::getConnection());
}


Redirect from one module to another I have form in one module.

  public static function validateForm(array &$form, FormStateInterface $form_state) {
      $url = \Drupal\Core\Url::fromRoute('test.route');
      $form_state->setRedirectUrl($url);
      $form_state->setRedirect('test.route');
  }

Trying to redirect the route of another module.

It's not redirecting from one module to another.

An example

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

Its not working in Form validate.

Its working un submitform

public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = Url::fromRoute('route.path');
        $form_state->setRedirectUrl($url);
}


Field access for specific nodes I have a node type called 'basic' with 10 nodes and a bunch of fields. However, I want to add a field that is specific to only one node. What is the best way to do that?

At the moment I've got a custom field and I'm hiding it using hook_form_alter() ['#access'] = FALSE (and hiding visibility via the UI), so it's not editable or visible for the other 9 nodes, which works but I'm worried this isn't the best way performance wise. Aren't those field tables then being joined for every node call?

Using the Form API isn't an option because I want to take advantage of the field widgets (using unlimited values etc).

Any ideas?

Dealing with such a limited number of nodes, my first reaction would be to clone the content type, say 'basic_extra', and add the field to the clone. Just make sure to change the scope of any views including 'basic' to include both. It would eliminate a lot of work for only one node.


How much server-side resources does the Omega theme use? Is the Omega theme scalable? The omega theme is pretty 'fat'.   Currently its probably the biggest theme on drupal.org.  You can do anything and everything in the GUI. You can completely customize the layout, turn responsive design on/off...I could go on for awhile.

My question is,  do all of the extra settings eat up server resource to serve a page to the client? If I have a website that receive 100,000+ page visits a day,  should I use omega, or create my own theme?

Yes there is some extra overhead involved (especially at the templating level); how much this will effect your response times will completely depend on the setup of your server. An easy test would be to enable the basic Garland theme, profile the site, then enable the Omega based theme and do the same. You should get a pretty good idea of how much extra overhead you're likely to get for a single page load.

If you're able to, go further. Stress test your server (using something like ab) with both themes enabled. That'll give you an even better idea.

If you've got a site with 100,000+ visitors per day though, your efforts might be better spent setting up a decent caching strategy, both in Drupal and on the web server. That will help to offset a lot of the overhead that Omega/Alpha can add.


Hide an entire View Block when query returns no data I have a view block and - because of the filters being applied - it may show data or may not. If the view's query returns no results, I need to hide the entire block - the .block - not just the .view or .view-content. I've seen several other questions and pages that offer solutions but all either don't hide the entire .block or just flat out don't work.

The solution that appears to be most discussed uses the Global: Null contextual filter, but that always hides the entire block regardless of any other condition. In fact, it doesn't even run the query when this filter is active. I need the block to be hidden if and only if the query returns no results.

I have the default, barebones Drupal 7 installed with only Bartik, CTools and Views so I am sure there aren't any other conflicts coming in from the theme or other modules.

One of the solution is:

Under FIELDS: click each field and in the "No results text" area, check the "hide if empty" box.

This will allow the field not to show if there is nothing actually there to show. But will not affect how the block itself displays on the page.

Another solution for this is :

  Go to the advanced tab of you view
  Add contextual filters
  Select Global: Null
  When the filter value is NOT available: Select 'Hide view'


Multivalue entity reference synchronization I have node type A with Entity Reference multivalue field that can reference other nodes of type A (existing). Is there a simple way/module/workflow/ruleset/other to do synchronization as follow:
after saving new node of typa A (ie. nid=112) referring two nodes (ie. nid 66 and 77) I want node 66 and node 77 automatically have references to 112.

Two way references are described in this drupal.org issue

Corresponding Entity References seems to be consensus solution there, but if it's no good for you, read whole thread, it provides interesting ideas and alternative approaches.


Upgrading Drush from 4.4 to 7.1 Following instructions here, I used the command drush dl drush to install the newer version of Drush. Then, when I attempted drush omega-export (the reason I was upgrading was to have access to these newer omega commands) I received a message indicating that drush was still pointing to the older version of drush.

If the server was based in my home computer environment (win7) I would change the PATH variable to point to the newer version. However, since the server I am working on is remote (onyxServers, typical LAMP stack) I am unsure how to make the drush CLI point to the new version.

Can anyone point me to  a resource? If it was my own linux machine I would be able to figure it out but being hosted confuses things a bit.

UPDATE: I have examined the output of the 'env' command, and noticed that the location of drush, new or old version, is not listed in the PATH variable:

  PATH=/usr/local/jdk/bin:/home/dukkha/perl5/bin:/usr/kerberos/bin:/usr/lib/courier-imap/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/home/dukkha/bin

Is it possible that the path to drush is stored within the drush shell or something?

Aha! I guess I posted this question a little too quickly! The path to the drush command can be altered through editing the .bash_profile file.


Loading specific bootstrap mode in hook_menu There is a way to define a specific bootstrap mode for a hook_menu URL (MENU_CALLBACK)?

I just want the request returns to me a result of a simple query in JSON and for that, I don´t need load the Drupal bootstrap in full mode, damaging the response performance.

Thanks!

It's not possible, because hook_menu() is invoked when Drupal is completely bootstrapped, also because only when Drupal has been completely bootstrapped, all the modules are loaded; only in this case all the menu callbacks defined in hook_menu() are available.

If you really need to limit the bootstrap to a phase, then you can write a file that is similar to index.php, for example.

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

An example of file used for a specific task is cron.php.

define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  drupal_cron_run();
}

Generally, there isn't the need to limit the bootstrap, only to serve data in JSON format. Creating a file like cron.php should be done for a dedicated task that is time consuming, or for limiting the pages being served, as with install.php.


Commerce / Rules: How to update node that references a given product when the product is updated I am trying to follow the Commerce Product model of Node Display that references each product.

When I create a product, Rules automatically creates a Node with the same title, and references the product in the node.

However also using Rules, I would like to perform the following:

When product is updated, update the referencing Nodes Title / Published attribute
When product is deleted, delete the referencing Node

I can't figure out the way to fetch the Node Entity in Rules at all.

Thanks!

EDIT:

As per @rfay's comment below, I've attempted to go down the Bi-directional reference route, which means installing the References module and create a node_reference field in the product that points back to the node.

Unfortunately however it seems Rules is not providing the means to fetch the node entity, as it is not recognizing the existence of the node_reference field on the product by which to fetch the node from.

If you want to delete the product display node, you need to hook the entity update (e.g. on node update). If the product reference field is empty, you can delete the node. But the product reference field must be a required field.

When the Drupal commerce module deletes a product, it needs also to delete all the references from the product display.


Unauthorized : CSRF validation failed issue for Logged in user I need to hide button for Logged in user. For that I have written the following code in dashboard.js file.

Code working fine for anonymous user. But not working for Logged in user.

$(document).on("pageshow","#user_login",function(){
      try {
            $.ajax({
              url: "example.com/?q=drupalgap/system/connect.json",
              type: 'post',
              dataType: 'json',
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('page_dashboard - failed to system connect');
                console.log(JSON.stringify(XMLHttpRequest));
                console.log(JSON.stringify(textStatus));
                console.log(JSON.stringify(errorThrown));
              },
              success: function (data) {
                var drupal_user = data.user;
                //console.log(data);
                if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
                alert(drupal_user.uid);
                }
                else { // user is logged in, hide the login button, show the logout button
                  alert(drupal_user.uid);
                }
              }
            });

      } //try end
      catch (error) { alert("page_dashboard - " + error); }
    });

For logged in user getting popup like : .

Added X-CSRF-Token in beforeSend like below everything works fine now.

$(document).on("pageshow","#user_login",function(){
      try {

        $.ajax({
              url:"example.com/?q=services/session/token",
              type:"get",
              dataType:"text",
              error:function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
              },
              success: function (token) {

                        $.ajax({
                          url: "http://192.168.0.6/site_name/?q=drupalgap/system/connect.json",
                          type: 'post',
                          dataType: 'json',
                          beforeSend: function (request) {
                                request.setRequestHeader("X-CSRF-Token", token);
                            },
                          error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('page_dashboard - failed to system connect');
                            console.log(JSON.stringify(XMLHttpRequest));
                            console.log(JSON.stringify(textStatus));
                            console.log(JSON.stringify(errorThrown));
                          },
                          success: function (data) {
                            var drupal_user = data.user;
                            //console.log(data);
                            if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
                            //alert(drupal_user.uid);
                             // $('#button_login').show();
                             // $('#edit-user-login-form-name').hide();
                            }
                            else { // user is logged in, hide the login button, show the logout button
                              //$('#edit-user-login-form-pass').hide();
                              alert(drupal_user.uid);
                             //$('#button_logout').show();
                            }
                          }
                        });

                    }
        });

      } //try end
      catch (error) { alert("page_dashboard - " + error); }
    });


Drupal 8 correspondence to node_access function on Drupal 7 I feel like asking a silly question, but here it is anyway: I need to test if a given user (in my case, the logged in, current user) has access to a given node for one of the existing operations (view, create, edit or delete).

In Drupal 7 you could test this by using node_access function (https://api.drupal.org/api/drupal/modules!node!node.module/function/node_access/7.x) and it would be as simples as this:

if(node_access('view', $node, $account)) {
  // Perform something
}

Return value would be TRUE or FALSE. How can I achieve the same result on Drupal 8?

I will be running this code from inside a _custom_access check for a specific route I am setting for my custom module.

Thank you!

You want Node::access():

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


When using Zen and Zen grids, where do I put SASS variables? I am trying to use Zen Grids with the Zen ver. 5 starter theme.

The Zen starter theme comes with a lot of .scss files (in the sass/ subdirectory).  I am trying to use Zen Grids to set up a simple layout.  I've read up on Sass and think I understand the concept, and I've Compass installed and working.

I've read everything on the Zen Grids website. On the front page of that website, below the promising headline: "Using Zen Grids is easy!", there is a nice introduction to Sass and Zen Grids followed by: "And here’s the complete Sass code:".

The example is strightforward enough.  What I am not able to figure out is where (as in "in what file") you put the statements used in the example.

(My setup is a Zen sub-theme created from the Zen STARTERKIT, straight out of the box.)

In the Zen theme structure there are several main style files: pages.scss, nodes.scss, blocks.scss, forms.scss. Depend on which part of website that you want to make styles. You have to choose the correct files for changing. In order to use the sample code in the Zen Grids . You can go to pages.scss and make changes here . Make sure that your website will generate the same HTML markup structure like the sample by creating new pages.tpl.php.


How do I use hook_theme() in a module? I need help in using hook_theme in my custom module. Any good examples is much appreciated. I have created a CCK input form and I want to theme the input form using hook_theme. The content type is created using hook_install().

I have used hook_form_FORM_ID_alter() to alter the theme of the input form. Following is the code for that.

 function footer_menu_form_footer_menu_node_form_alter(&$form,&$form_state,$form_id) {
   theme('footer_menu_node_form', array('form' => $form));
 }

 function footer_menu_theme($existing, $type, $theme, $path) {
   return array('footer_menu_node_form' => array(
     'arguments' => array('form' => NULL),
     'template' => 'footer-menu-node-form',
     'render element'=> 'form',
   ));
 }

I have also created a footer-menu-node-form.tpl.php file inside the module, and the following is the code in the template file.

 <?php print drupal_render($form['title']); ?>

Menu Tree

 <?php print drupal_render($form['title']); ?>
 // this one is for rendering all the remaining items, like hiddens:
<?php print drupal_render($form); ?>

When I load the footer menu content type. The content within the
 tag is alone printed and then I get the following error:

  Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 40961 bytes)

Can anyone tell me what I doing wrong, or could anyone suggest me an efficient way to use hook_theme() in modules?

The proper way to assign a theme function to a form using hook_form_alter() is like this:

function footer_menu_form_footer_menu_node_form_alter(&$form,&$form_state,$form_id){
  $form['#theme'] = 'pz_footer_menu_node_form';
}

I can't tell if you're using Drupal 6 or 7; you're using the arguments property in your theme declaration which is only valid in Drupal 6, and also the render element property which is only valid in Drupal 7.

Judging by the out of memory error I'm guessing Drupal 7. As you call drupal_render() on the the $form object in your template file, it runs that variable back through the same theme function, and you end up with an infinite loop.

Try changing the last line in your template file to this:

<?php print drupal_render_children($form); ?>

That should stop the error from happening.


Are there two identical .htaccess files in a Drupal installation? I run a Drupal Commons site and I'd like to set it up on a new server. When I set this particular site up, I need to replace Drupal's base .htaccess file so that it runs in my server environment.

However, this answer states that the .htaccess is present in two places:

  The .htaccess files (which are present in at least two places) should have the permission 644.

Is this true? If so, where is the second one? Is it the one in sites/default?

There are actually 1+n .htaccess files in any given Drupal directory, where n is the number of working sites:

In the Drupal root
One for each site's files directory

The contents of the files directory .htaccess file is the following:

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

This was done as part of a security update to Drupal 4.6.x and 4.7.x, and has been there ever since. The relevant security advisory, SA-2006-006, explains why:

  Certain -- alas, typical -- configurations of Apache allows execution of carefully named arbitrary scripts in the files directory. Drupal now will attempt to automatically create a .htaccess file in your "files" directory to protect you. This line references SA_2006_006 to lead Apache administrators to this announcement.

Thus it's not advised that you replace or remove that file.


Add user edit form in a block D8 I'm trying to add the user edit form in a block.
I created a custom module

use Drupal\Core\Block\BlockBase;
use Drupal\user\ProfileForm;

class EditUserBlock extends BlockBase{

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm(ProfileForm::class, \Drupal::currentUser());

    return $form;
  }
}

but it doesn't render the form.

Sorry but I'm pretty new to D8.

This is an entity form and you need EntityFormBuilder::getForm() to build this form. After you have injected the entity form builder and the necessary user storage and current user services in the block plugin:

<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Profile Block.
 *
 * @Block(
 *  id = "profile_block",
 *  admin_label = @Translation("Profile Block"),
 * )
 */
class ProfileBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

  /**
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $userStorage;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFormBuilderInterface $entity_form_builder, AccountInterface $current_user, EntityStorageInterface $user_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityFormBuilder = $entity_form_builder;
    $this->currentUser = $current_user;
    $this->userStorage = $user_storage;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.form_builder'),
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

you can build the profile form for the current user with two lines of code:

  public function build() {
    $user = $this->userStorage->load($this->currentUser->id());
    return $this->entityFormBuilder->getForm($user);
  }

}


How can I style the webform submissions table? Using Drupal 9 and Webform, I'm unable to find the twig template used to output /contact/form/submissions.  Is there a place in the documentation that lists the twig templates?  I see there is a View created that looks like it has submissions, but disabling it doesn't break the page.  If there is a better way to style it, that could also work.

Check out Is there a "best practice" for overriding a contributed module's controller in Drupal 8?
If you override the WebformSubmissionListBuilder, you can do almost anything you want to the results, including custom theming.


A Rule to copy the user's picture In Drupal 7.. I'm trying to create a rule that copies the user's profile picture into an image field on another content type.
How can I select the 'picture' from a user's account, as a source for copying?
The event is after updating an existing account, which provides the source 'account'.
The File Field Rules module provides the copy action, but it requires a source field, and the user-picture isn't a field.

Another approach I tried is with the file URL. The FileField Sources module allows the use of a remote URL in an image field, but if I try to set the value of the image field with the token [account:picture:url]  Rules doesn't allow it.

There is a similar question here Rules: Copying field from user's account to field in content type  but the solution is with an additional field attached to the user, not with the default 'picture' one.

thanks,
d

Install views rules module, make a views-rule of users, if you need UID as a contextual filer add it as always, then in middle column set your UID as an integer in parameters settings, add user pictures as a field, now in middle column settings, set user-pictures as an file entity. then in your rule, fetch entity by id with your variable UID, now you have user picture avilable and can be copied to your content type file field. Done, cheers.


Video captions below video field I'm expanding my language learning site and need a bit of help if it's possible.
I am wanting to link to YouTube videos (that's easy). But I would like to have a captions field. As the video plays the captions would appear in the field. I need to do this so that the user can copy and paste the caption and there will be two lines of captioning "Language 1" and "Language 2." I might in the future add a second field below the captions that would give a grammar explanation to the caption being displayed as well.

The only thing I have found while searching around is: https://www.drupal.org/node/1927080 but it puts the captions into the video.

+---------------------------------+
|                                 |
|              VIDEO              |
|                                 |
+---------------------------------+
+---------------------------------+
|                                 |
|           LANGUAGE 1            |
|                                 | <= Changes based on video time
|           LANGUAGE 2            |
|                                 |
+---------------------------------+
+---------------------------------+
|                                 |
|            GRAMMAR?             | <= Changes based on video time
|                                 |
+---------------------------------+

I have been unable to find any existing module to do this and would be quite surprised if one existed. You will very likely have to develop your own module.

Here is a brief rundown of how such a module might work:

Implement a new field type providing either a form for the user to create the subtitles or upload a subtitle file in one of the many subtitle formats. https://support.google.com/youtube/answer/2734698?hl=en
Parse the input from the form and store it. You'd likely want to store it as JSON or something else that will be easy to work with in JavaScript
Write code to pass the data to the browser
Use Javascript to update the Language 1 and Language 2 content to match the data in your stored subtitle file. You can use the YouTube API to get the current time of the video https://developers.google.com/youtube/iframe_api_reference#Playback_status

I think it would be a lot easier to just use YouTube to do this but I'm sure you've already thought of that.


Change Views Display Title Programatically I had a similar question recently, related to changing the path on a Views Display. Following this reasoning (as well as other examples I've seen), I assumed I could follow a similar approach. Unfortunately, that doesn't seem to be the case.

Related question for reference: Change Views Path Programatically

What I currently have:

$view = \Drupal\views\Entity\View::load('custom_view');
$display =& $view->getDisplay('page_1');
$display['display_options']['title'] = 'My Custom Title';
$view->save();

However, this does not seem to alter the title of the Display. I've attempted a method of changing the Display title in a Views hook, at that works correctly, but I'd like to be able to change the title without relying on actually viewing the View to utilize its hooks. In addition, I believe this would set the title for all Displays, which I don't want. Working example:

function my_moudule_views_post_render(ViewExecutable $view) {
    $view->setTitle('My Custom Title');
}

Following this approach, I attempted to utilize the \Drupal\views\Views::getView() method, but was unsuccessful.

Your code is working I believe, but it could be that "page_1" is not the correct page variant name...I had to use 'default', that was what I ran into when creating a test View and attempting to try your code out... in my case to verify, I enable kint, do a ksm($view) and check the 'display' array to verify the variants. You may need to alter 'default' to see the intended results. Also make sure to cache rebuild just in case drush cr afterwards, you may want to programmatically empty the cache bin for this View depending on the use case.

Also, you mentioned the hook affecting all the Views. That is true, but you could add some more granular logic to the hook to make it only affect specific View, by specifically drilling down to the ID (the 'machine name" in the Views GUI) and performing logic only if the machine name matches, e.g. if my View machine name is "foobar_view_custom", then you can do:

/**
 * Implements hook_views_post_render().
 */
function mymodule_views_post_render(ViewExecutable $view, &$output, CachePluginBase $cache)
{
  $display = $view->getDisplay();
  $id = $display->display['id'];
  if ($id === "foobar_view_custom") {
    $view->setTitle("PROGRAMMATICALLY CHANGED");
  }

}

The difference here is you are altering the actual data in the database for the title of the View entity in your first implementation, versus in the hook, it would only change it during rendering, so really depends on use case (if the title was dynamic based on date or something, the hook might be better. Long term alteration, like in an update hook or something, probably would want to alter the actual data with the entity method) Both implementations should cache just fine.


How do I show only 3 of the latest posts for each term in a view? With the help of another question: Show newest nodes for each taxonomy term in Views I have been able to create the view I require, except that it displays all posts for each term (grouped by term)? How do I limit each term to display only 3 of their latest posts.

e.g.

Term 1
 - Post 1
 - Post 2
 - Post 3

Term 2
 - Post 1
 - Post 2
 - Post 3

Term 3
 - Post 1
 - Post 2
 - Post 3

If you need only one node you can use “Representative node” relationship. But if you need three nodes per each term, use something like Views Field View.

1) Create "child" view for content. Something like this:

Add taxonomy term argument, pager limits, sorting and etc:

Now you can attach this view to another one.

2)  Create taxonomy view:

Add hidden term ID field and then add “Global: View” field:

Don't forget to configure caching. From Views Field View page:

  It's highly recommended to use this module in conjunction with views caching.
  Views Content cache and Cache Actions are good ways of caching views.


adding the field tokens while creating the component I created the component, in body of the message i added the token based on machine name but i am unable to fetch the data of the fields of content i,e when email triggers to user in the body of the email field data is not showing based on the content created, i have followed this method Get the field data in email body. please give suggestion why is this happening?

In Rules you need to use - not a _

Try

[node:field-working]
[node:field-remoz]

EDIT

Click on replacement patterns, it will show you all the fields that you can use. Look for your field on the list, and then use the code that is given there, and copy and paste it into the message body.


Sort content of views with drag and drop I use Drupal 8, but I can not figure out how to sort views with drag and drop.
The client needs to sort the items of the views in a very personal way.

Do you know some way?

The Draggable Views module might be what you need. There is a version of the module for Drupal 8.

According to the module description,

  DraggableViews makes rows of a view "draggable" which means that they
  can be rearranged by Drag'n'Drop.

I tried the following instructions in the documentation page on a vanilla Drupal 8.2.6 installation, and it worked fine (see screenshot below).

  Activate the module and navigate to the edit-page of an existing
  view.
  Now go to the Format section and choose Table.
  Make sure you have the "Content: Title" field, place it as your first field.
  Add the field "Draggableviews: Content" at the Fields section, place it after the "Content: Title" field.Make sure not to check
  "Exclude from display"; if you do the view will permit drag and drop
  but the changes will not be saved.
  Add "DraggableViews: Weight" at the Sort criteria section and place it as the first Sort criteria. Save the view and you're done.


How to change term reference field according to role? I have the following challenge: I have 4 roles, let's call them Group1 ... Group4. I have different content types and I segregate access of those types using the Taxonomy Access Control module. So users from Group1 can only view and edit nodes that have term Group1.

Now, I have the challenge to change a term reference field of these content types automatically. So if a user from role Group1 creates a new node, that node will have a term reference field with term Group1.

I don't want users to edit on their own to avoid human errors.

All you need to do is create separate fields for respective roles. Use Field permissions module. Or if you want to have role wise access like from editor -> moderator -> pulisher etc. Use workfolw module.


getting line breaks in tinymce wysiwyg   On a new drupal 7 installation, I'm trying to get line breaks to show up correctly when saved. I have wysiwyg and tinymce installed through using the panopoly distribution. When I try to do more space after a paragraph (by hitting enter twice), it will generate two empty paragraph tags, such as

. This however won't provide the needed space as they are empty. In an earlier (drupal 6) project, when I tested this behavior it would insert paragraphs with &nbsp; in them which correctly displayed the line breaks. For example:
&nbsp;

&nbsp;

Is there any way to get this behavior back in Drupal 7?

I've played around with the wysiwyg settings, and text formats, but I can't find a combination of settings that will work.

It turns out this has something to do with the "WYSIWYG filter" under text formats (admin/config/content/formats). Disabling this gave my non-breaking space back. You would probably want to adjust the configuration rather than just turning it off.


Getting body of a node to display in a block using PHP code I've created a block and put some php in it to display the body of a node using the code form here: http://drupal.org/node/300910#comment-4183142

<?php
//get the ID from the URL
$node_id = basename($_SERVER['REQUEST_URI']);
echo $node_id;
//Load the node object.
$node = node_load($node_id);
//Get the node array into memory.
node_view($node);
//Now you can parse only the body value into a variable.
$node_content = $node->content['body']['#value'];
//Printing content.
echo $node_content;
?>

The page I've tried this on prints the ID in the block (as expected) but not the body of the node with that ID.

My hunch is that $node_content = $node->content['body']['#value']; can't be used in a block.

Any thoughts?
Thanks!

I found out how to do this:

$node_id = basename($_SERVER['REQUEST_URI']);
$node = node_load($node_id);
echo $node->body['und'][0]['value']

I have also found out that there is probably a better way to do this using field_view_value(),
but I am not quite sure how that works.


How to open nodes in Lightbox? Goal here is to just open my Nodes in a Lightbox.
Following is what I have tried at it is not working for me, any clue would be great:

In my View, I am rewriting the node title as following:

[title]

All I see that the title is output as a link to the node. Clicking on the title just opens the new node.

I followed the instructions at https://drupal.org/node/252260

  Basic example:
  Search google

I am using Drupal 6! (D6 Version: 6.22 & lightbox2 Version: 6.x-1.11)

Update: I tested this works in my D7 installation - but not in my D6 site. :S

I found the solution - had a silly error.
In lightbox2 module configuration page, under Page Specific Lightbox2 Settings, I was telling it to not load on any page.


How can I learn the Views 3 API? Where can I learn the views 3 API? I can use the ui to make views but I would like to create views using the API in my modules. I would settle for the views 2 API at this point. I looked at the docs and did not get very far. Anyone know of a good tutorial?

Not sure what exactly you mean with "creating" views.

First, if you have custom tables/data, you can use hook_views_data() and custom plugins and handlers to tell views how to access these tables. Some Tutorials/examples: http://treehouseagency.com/blog/neil-hastings/2010/01/19/views-handler-easy-way (Drupal 6) and http://larsolesen.dk/node/273 (Drupal 7). But again, you only need this if you want to expose your own tables to views.

Then, there are a number of pre-render and alter hooks, which allow you to alter some things that you can't do in the user interface. List of views hooks in Drupal 6.

That said, there is no "API" to create actual views (that I know of). I think everybody uses the views UI for that (After all, it's a great UI now in Drupal 7). What you can do is export the views you created in the UI to distribute them with your module or as a new module. This is also useful for contributed/standard modules to not only expose their tables to views but also provide example views, which can be customized/extended for a specific site.

Instead of exporting them manually, you can also use the Features module, which allows you to export all kinds of configuration (views, content types, fields, permissions, ...) into so called features (which is basically an automatically generated module). That is especially useful when moving configuration like views from a development to a production installation, or re-using the same views/configuration on multiple sites.


How to make author field required? In Drupal 8. I noticed that I can create a new node or edit a current node and delete the "Authored By" name, it's blank and when I hit save the node is authored by Anonymous.

How can I make this Author field required to be a current user in the system?

And the page will show a message and will not save until a name is entered. I tried this but it does not work:

use Drupal\Core\Form\FormStateInterface;

function demo4_form_alter(&$form, $form_state, $form_id) {
$form['author']['name']['#required'] = TRUE;
}

I also tried this:

function demo4_form_alter(&$form, $form_state, $form_id) {
if ( $form_id == 'page_node_form'){
$form['author']['name']['#required'] = TRUE;
}
return $form;
}

This works only in Drupal 7 not in Drupal 8, And I changed page_node_form to node_page_form for Drupal 8

function demo4_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'page_node_form') {

$form['author']['name']['#required'] = TRUE;
 }
   return $form;
}

What you're looking for is this:

$form['uid']['widget'][0]['target_id']['#required'] = TRUE;

(Devel is your friend!)

You were on the right track as $form['author']['#required'] = TRUE; will make the "Authoring Information" have a red star (*), but won't make your authored by field required.

Complete code:

function hook_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form['uid']['widget'][0]['target_id']['#required'] = TRUE;
  }
}


Change the position of the block created from the Locale module I am using Drupal 7, and I have enabled the Locale module. I have configured the block so  that it appears on the header, but I want the block to appear near the site's name.

How can I do it? Which files need to be changed?

I am using a Zen sub-theme.

You can put your block into any region you like on the general block config page.

If this is not enough you can change everything about a region in the page.tpl.php file or the corresponding CSS files.


How do I add social bookmarking icons to my site that only load or look for javascript only when executed? I have taken a look at the Sharethis and Addthis modules. I have also looked at putting the embed codes directly from twitter and facebook in my site. With each option, my site needs to load the external javasript libraries/images from the third parties on every page load. This doubles(and in some cases, triples) my load times. It can also go sideways if the external site is under a heavy load or offline. It appears there is no way to provide a local copy of the js files/images with these approaches. Can someone suggest a module or a way to add social bookmarking icons to my site that only load or look for javascript only when executed?

Had this same issue on a site when using the Addthis widget and its probably similar for most sharing situations. We tried the addthis module but were also concerned about the overhead involved with loading the module and adding this on every page. We only wanted this to appear on blog posts so we wrote a simple preprocess_node hook to our module, ex:

if ($vars['type'] == 'blog_post') {

    drupal_add_js('http://addthis.com/<script-link-here>.js', 'external');

}

And then added our specific call to AddThis in our blog post template. You could also add the script tag in your template as well but its not best practice and wouldn't get cached as well as if its done through drupal_add_js.

We considered caching the addthis file locally (which is allowed for by addthis) but resolved that it would be better performance-wise to shift the external load to their servers rather than adding another file hit to ours. This page may also be helpful for addressing performance concerns (for AddThis).


Add an entity reference select to a form I am writing a Drupal 8 module, and I have some code that adds an entity reference field to a form.
$form['commitment']['goal'] = array(
    '#type' => 'entity_autocomplete',
    '#title' => 'Goal',
    '#target_type' => 'node',
    '#selection_settings' => ['target_bundles' => ['goal']],
);

This works, except that I want a select list instead of an autocomplete.
How can I accomplish this?

Basing on the OP solution, I would suggest the follow code.

$options = [];
$goal_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'type' => 'goal',
]);

foreach ($goal_nodes as $goal_node) {
  $options[$goal_node->id()] = $goal_node->label();
}

$form['commitment']['goal'] = [
  '#type' => 'select',
  '#title' => t('Goal'),
  '#options' => $options,
];

This has still two issues:

Entities are not translated
Bundle label ('Goal') is not  programmatically coming


How can I get both "body" and "summary" fields to appear in a new article? I'm defining a Drupal 7 content type using the "long text and summary" field.  When a new story is created, I'd like both the "summary" and "body" text fields to be present in the creation form, instead of making the user click the "edit summary" link.  Is there a way to do this through the basic Drupal content type tools (I've looked, but can't find anything), or do I need to write a hook_form_alter handler or something comparable for the content type?  Thanks!

I think you'll have to do it in a form alter hook as you suggest, I don't know of a way to do it in the UI.

Looking at the code for text summary fields the "Edit Summary" link and functionality are done completely through javascript, added in the form by setting an #attached property on the element, which includes a JS file (modules/field/modules/text/text.js).

All that JS file does is add that "Edit Summary" link so it would be completely safe to just get rid of it. This example uses the standard page content type:

function mymodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  unset($form['body'][LANGUAGE_NONE][0]['summary']['#attached']);
}


Handle permission based on both person and role? I am using workflow module for a publishing website.

There are many people who have the role reviewer....The comapny want to enable that when you change state from 'in moderation' to 'in-review', we can assign the content to a reviewer through an autocomplete field. NOT ALL reviewers.

Workflow content permissions does a great job, for making it role based. So the author is no longer allowed to edit the article when it is 'in-review' state. Now I don't want to allow all reviewers to edit it 'in-review', only the one that has been selected.

Is there a module for this? If not, how should I be going about this.

P.S. -: I am barely a few weeks into Drupal, so go easy :-)

I suggest first to use the Rules module to fire an action on your workflow transition : from 'in moderation' to 'in-review'

Second try to use the Node access user reference module or the Nodeaccess module to use an API method inside your a custom PHP code or as a rule's action to grant the referenced user


Creating multiple views from Entityform Submissions I would like to create multiple views containing filtered/ordered results from submissions made into forms created using EntityForm.

In the documentation and in question on DA(The Entityform module allows me to create forms that any user can submit and the forms fields are available for me to use in views, similar to how a content type would work. it seems this is possible but I cannot figure out how.

Fields created and submitted in the forms are not listed under "add field" in views, nor in "add relationship".

So the question is:

How is it possible to fully interrogate Entityform submitted data using views?

THE SOLUTION:
As per Wolverine's answer it is very simple to do, displayed in the picture:

No idea how I missed it before!

It should be available, create a view of Entityform Submission and add the filter Entityform Type, if you want. Add the fields that you want to display, make sure you have selected Show : Fields under Format section.

By default entity form module creates two views, Entityforms & Entityform Type List, you can edit the Entityforms view instead creating a new view, if you want.


Cell Phone Validation field using sms message I recently want to develop a field for user account.

The Field will provide a cellphone textfield and a validate button!

After finishing the cellphone textfield by the user, The user push the validate button.

Then, the system will send the sms message using ajax.

After sending the validate code message to the user, the system will respond the CODE to the client side. However, the cell phone textfield is invisible right now.

Finally,the user enter the code get from sms message and then push the button.

The system will check the code by ajax and then return the correct/false value to the client side.

After the steps above, the system will hide all the field and show the result of the validation.

My question is how can I do that?

You don't want to create this yourself. You want to use the relatively new Two-Factor Authentication Module and it's plugins -- or create your own plugin.

  Second-factor authentication for Drupal sites. Drupal provides
  authentication via something you know -- a username and password while
  TFA module adds a second step of authentication with a check for
  something you have -- such as a code sent to (or generated by) your
  mobile phone.

  TFA is a base module for providing two-factor authentication for your
  Drupal site. As a base module, TFA handles the work of integrating
  with Drupal, providing flexible and well tested interfaces to enable
  your choice of various two-factor authentication solutions like
  Time-based One Time Passwords (TOTP), SMS-delivered codes,
  pre-generated codes, or integrations with third-party services like
  Authy, Duo and others.

  Features

  Pluggable - Supports multiple methods of 2nd factor verification and
  can work with any number of 3rd party systems
  Configurable - Supports fallback methods and context-specific exceptions
  Flood control and even secures one-time logins
  Tested - Over 100 tests

  TFA module is recommended as a full suite solution to 2nd factor authentication and Drupal.

  See the TFA basic plugins for a TOTP plugin that works with FreeOTP,
  Google Authenticator, Authy, and any other app that works with TOTP
  tokens.

  This module stores some sensitive data which it encrypts using the php
  mcrypt library. You will need to have the mcrypt extension installed
  to use the module.

This module is designed to allow you to meet your use-case (some custom code may be required). It's also designed with fallbacks and edge-cases taken into consideration which you may not have thought of -- and it has a zillion tests.


node.getRevisionCreationTime equivalent in views This question is somewhat related to Comparing node creation and modification dates in twig I asked earlier.

For the website in question, we agreed to the following semantics of the various dates related to a node (in our case, blog posts):

Creation date: The date the note was created.
Changed date: The date when any of the node's modifiable settings were changed.
First publication: The date the node was first published (using Drupal module Publication Date).
Publication date: The date a new revision of the node has been created - in other words, the current revision's date.

In rendering the content, all is well when using node.getRevisionCreationTime for the publication date in the relevant twig templates and display modes.

However, I what certain blocks and views to order the blog posts by publication date as defined above.

I fail to find the right settings when defining the view - I find the Views user interface incredibly complicated and not intuitive at all. In my (perhaps naive) assumption, using the Content Revision field Changed or Authored on as sufficient, but I suspect that that doesn't always relates to the current revision.

See the attached screenshot on how I have defined the view:

UPDATE: An example:

The above view (with some filtering on example name) gives the following result:

Taking a screenshot when editing the node I get this:

So far, so good: Node creation, publication and changed times all match. But look at the "Revision created" and "Revision changed" dates - they match the corresponding node times!

Checking the node's revisions, I see that the current revision's date (which date exactly? Created? Changed? Something else?) is 12 June 2018 - but nowhere to be found in my view - see screenshot:

The revision date 12 June 2018 is the date I want to fetch as the "Publication date" explained above.

How do I do that in a view?

Please help!

TIA,
Michel

I found the answer eventually:

The crucial thing to do was to built the query starting with content revisions rather content. Rather unintuitively - creating a relationship the other way around does NOT get you to where you need to get in this situation!

To create a view listing the node's title, creation date, changed date, first publication, and publication date (the creation date of the current revision, follow these steps, and then add/remove as required:

Create a view showing content revisions of type all as follows, creating a page for easier review:

Remove the field "Content revision: Changed (Changed)" as this is not what we are interested in.
Add a relationship to Content as seen in the screenshot below:

This is one of the #DrupalWTF moments - where's the crucial documentation that allows me to select the correct relationship!?
There are apparently two RDBMS foreign key relationships you can use to join revisions and content:

a. Via content revision foreign key to the id of the node this revision belongs to - this is the first content relationship, and

b. Via revision id referenced as foreign key from the content table as current node - this is the second content relationship shown above in the screenshot.

For whatever reason you cannot reach the creation date of a revision when joining via the first content relationship, #Drupal, #WTF?

Require the relationship for all results, and change the administrative title if you wish:

Add a filter criterion to show only blog posts
The relationship shows revisions for all content types, so we need to filter for content type blog post (Yours may be different). This is pretty straightforward, see the following screenshots:

a. Select the filter criterion:

b. Configure the filter:

Add the various date related fields
This is repetitive; to add the fields select them all in the "Add field" form, and configure them all the same way:

(Content) Authored on,
(Content) Changed,
(Content) Published on,
(Content revision) Revision create time

Here are the screenshots:

and

Et voila, all fields present as required.

Now you (I) can go to town for formatting and sorting.


Use drush to put a site in maintenance mode drush @mysite cget system.maintenance shows:

  message: '@mysite is currently under maintenance. We should be back shortly. Thank you for your patience.'
      langcode: en

Drupal 8 uses state values to record transient state, so drush @mysite sget system.maintenance_mode gives me a 1 or a 0.

But, try as I may, I cannot see how to set the boolean. I've tried:

$ drush @mysite sset system.maintenance.mode "TRUE" --format=boolean
$ drush @mysite sget system.maintenance_mode
0
$ drush @mysite sset system.maintenance.mode "TRUE" --format=auto
$ drush @mysite sget system.maintenance_mode
0
$ drush @mysite sset system.maintenance.mode true --format=auto
$ drush @mysite sget system.maintenance_mode
0
$ drush @mysite sset system.maintenance.mode true --format=boolean
$ drush @mysite sget system.maintenance_mode
0

What's the secret?

system.maintenance_mode is not a boolean, it is an integer:

drush ev "var_dump(\Drupal::state()->get('system.maintenance_mode'));"

Result:

int(0)

The answer to the question, how to use drush to put a site in maintenance mode:

drush sset system.maintenance_mode 1


how to display a custom entity in a view This is my first time making a custom module and I want to display some of the content that is produced in a view, but I can't figure out how to make my custom entity show up in the SHOW: select list when making a new view.

What code do I need to add to my custom module to have it show up there?

Include this in your hook_entity_info

MyModule_entity_info() {
...
'views controller class' => 'EntityDefaultViewsController',
...
}

For more details check this link : http://www.sitepoint.com/build-custom-drupal-entities/


Setup custom required field validation for a field in custom form How can I setup custom required field validation message for a text field in my custom form. I tried below code. But it is not working. It always showing 'Please fill out this field'.

$form['first_name'] = [
  '#type' => 'textfield',
  '#title' => $this->t('First Name'),
  '#default_value' => $this->store->get('first_name') ? $this->store->get('first_name') : '',
  '#required_but_empty' => $this->t('Please enter First Name'),
  '#required' => TRUE,
];

How do I add a custom validation to an existing form/field?

If you want to add your custom validator in addition to the default, you will have to add something like this in hook_form_FORM_ID_alter (or similar):

$form['#validate'][] = 'my_test_validate';


How to prevent displaying the theme on a custom page callback in hook_menu() I am developing a custom module with a callback script at foo/myurl:

function foo_menu() {
  $items = array();
  $items['foo/myurl'] = array( // change 'foo/myurl' to the url you want
    'title' => 'Callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  return $items;
}

function custom_callback () {
  echo 'success';
  return;
}

But this URL is to be called by a 3rd party script, and I only want to return the echoed string, how can I prevent the rest of the theme from loading?

Thank you

Simply don't return any value, and exit.

In Drupal 7, that can be done by calling drupal_exit(). In Drupal 6, you use code similar to the following one:

function custom_callback() {
  echo 'success';
  module_invoke_all('exit');
  exit();
}

When you call drupal_exit() you don't need to use exit too, as it is already used by the function.

exit() (or drupal_exit()) avoids other hooks are invoked after hook_exit().
Drupal normally calls drupal_page_footer() after the menu callback returns its value; using exit() (or drupal_exit()) avoids that function is called, too. The effect is that the output of the menu callback is not cached. If caching the output is desired then the call to module_invoke_all('exit') and exit(), or drupal_exit() can be removed. As far as the menu callback doesn't return any value, the Drupal page will not be rendered, as it is evident in the Drupal 6 code contained in the index.php file:

$return = menu_execute_active_handler();

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

drupal_page_footer();


Multiple results being returned using search for same node I have a view-based search in my site. I notice that when I type a phrase like so "search terms" or even just search terms (no quotes) into the search box it returns all results that match that exact phrase as you'd expect BUT it also returns multiple versions of the same node!

I checked to make sure they are the exact same node and I think they are. One of these nodes is returned 6 times. I clicked on each linked result and the pathauto-altered URL is exactly the same for each. So for some reason it's returning it 6 times and I don't know why. Other nodes get returned fewer times. Some don't get returned more than once. I've checked some of the items that get returned multiple times in the mysql database and they appear to only be in there once...

I've cleared caches and run cron/re-indexed site...nothing.

I've got into 'find content' and looked to see if there are multiple copies of the nodes. Nope just the one.

And if, when I search, I just search for one word in the profile it only returns it once.

However, when I search for multiple terms I get multiple copies. I've reviewed the SQL of the returned view and it doesn't look like anything funky is going on.

Any idea why this might be happening?

There is a join in the query that is causing multiple instances of the same node to be returned.

Edit the view and under the "Other" section click on Query settings and choose Distinct.

The description says:

"This will make the view display only distinct items. If there are multiple identical items, each will be displayed only once. You can use this to try and remove duplicates from a view, though it does not always work. Note that this can slow queries down, so use it with caution."

Here is the "Other section" in the view settings:

EDIT:

If this doesn't work then try the Views Distinct Module that Sage mentions in his comment below.


Breadcrumb add content type data without any modules How could I print content type like the breadcrumb, for example

  Home/Content type/Create

It is possible using theme_breadcrumb().

Example:

/**
 * Implements theme_breadcrumb().
 */
function theme_breadcrumb($variables) {
  // global variable
  $output = '';
  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    $nid = arg(1);
    $node = node_load($nid);
    $output = '
';
      $i = 1;
      foreach($breadcrumb as $value) {
        $output .= '
'.$value.'
';
      $i++;
      }
      if ($node->type == 'content_type') {
        $output .= '
' .  $node->type . '
';
      }
    $output .= '
'. drupal_get_title() .'
';
    $output .= '
';
    return $output;
  }
}


How to restrict permissions for administering Taxonomy? I would like a user role to be able to add/edit terms for a specific vocabulary, but not all vocabularies.

In the permission settings for taxonomy, it seems that I need to give the role permission to 'Administer vocabularies and terms'. But then they can edit all vocabularies; the edit/delete permissions for each vocabulary don't have any effect?

I've seen various taxonomy access modules, but they seem to restrict the use of terms on nodes etc. My situation is more simple; a specific role just needs to be able to add additional terms to a vocabulary.

What am I missing here?

For D7 there is a taxonomy access fix module. It makes it possible to manage access permissions to individual vocabularies.


How to create automatically a view of all nodes sharing the same field value? Working with Drupal 7.54 and Views 3.15

For each content type field, I need to display a link (after the value) which returns a view of all nodes sharing the same field value.

I manage to get my link (field - rewrite results and add a link with tokens) but I need to create a view (with specific contextual filter related to the field) for each field.

Is there a way to build this so I do not need to create x views for x fields? Any token for the field? Any PHP contextual filter using field_name and field_value?

Thanks in advance.

Example :

Node 1

Field A : value x (link)
Field B : value y (link)

etc.

The link returns a view :

All nodes with value x for Field A

Node 2
Node 7
Node 15

...

Related questions :

Create a view of all nodes that have the same value for a specified field as the current node

Suggested method

I suggest looking into using the Search API (with Views) for this purpose.

From the Search API module page:

  This module integrates the Search API with the Views module, allowing searches on any index to be created and viewed via Views. All of an entity's properties, as well as those of related entities (e.g. a node's author's name), are available as fields, filters and arguments for all indexed fields are available and sorts (as well as click sorts) can be created on any indexed single-valued field. Also some additional features, like linking the results to the entity, are available.

Drupal.org uses this method to create Issue pages with links like: https://www.drupal.org/project/issues/search_api?text=&status=13&priorities=All&categories=All&version=All&component=All. You should be able to craft your links to the view integrated with the Search API using tokens.

Detailed Instructions

I was able to set this up in my testing with the following steps, which are detailed below.

Install the Search API and related modules
Set up a search server
Set up a search index
Set up a view of the search index
Create the links to the view with tokens

Install the Search API and related modules

Install and enable the Search API module. Also enable the Search views extension module that comes with the Search API.

Set up a search server

For my testing, I used the Search API Database Search module. This is a separate module in Drupal 7 but it is in the main Search API project for Drupal 8. From the module page:

  This module provides a backend for the Search API that uses a normal database to index data. It is therefore a cheap and simple alternative to backends like Solr, but can also be a great option for larger sites if you know what you're doing.

This search server set up may work for you, or you may need to configure a different service class for your search server. I think specific instructions on other options like Solr are out of the scope of this answer, but I recommend taking a look at the Service classes and features documentation page which lists various options and their features.

To use the Search API Database Search, install and enable the module. Then visit Configuration > Search and Metadata > Search API (admin/config/search/search_api) and click +Add server. Name your server, leave the Enabled checkbox checked, and choose the Database service as the Service class. Click Create server.

Set up an index

Visit Configuration > Search and Metadata > Search API (admin/config/search/search_api) and click +Add index. Name your index, choose the Item type, and restrict by Bundle (content type) if desired. I restricted to Nodes of type Article in my testing. You can leave the Bundles checkboxes blank if you want to include all content types. Choose the server you set up in the previous step as the Server. Click Create index.

Now, you will select the fields you want to add to the index. In my testing I added an Integer field to the Article content type, so I added both the integer field and the tags field to the index. Check the fields you want to add and click Save changes.

The next part of the configuration is the Filters settings. You can choose to add "Alterations" or "Processors" to the data in the index. Your choices here will depend on what kind of data you're indexing, each option has a description that will help you understand what it does. In my testing I chose to Exclude unpublished nodes under Alterations and I chose Ignore case under Processors. Click Save configuration.

At this point, you should click the View tab to see the Index status page and add items to your index. The Index status page is located at Configuration > Search and metadata > Search API > Edit (Your Index) (admin/config/search/search_api/index/INDEX_MACHINE_NAME). For testing purposes I suggest indexing in a small batch at first and clicking Index now.

Set up a view of the search index

Now, visit Structure > Views (admin/structure/views) and click Add a new view. Name your view and in the Show dropdown field choose Your Index. Click continue and edit.

In the view under Filter Criteria, add a filter for your each of your indexed fields (I know that will be a lot of fields in your specific case). I added one for the Integer field and one for the Tags taxonomy field. Make sure you click the "Expose this filter to visitors" checkbox for each filter. (You can also look into the Facet API for the facets option, however I think you would end up with a block for every field you wanted to put a facet on as opposed to one disabled block with a ton of filters you won't use. I think the Facet API method would also be worse for performance but I may be incorrect.)

Now you can visit the view page and adjust the exposed filters to get the URL structures you need to use with your tokens. Or, the pattern is: https://example.com/[VIEW_NAME]?[FIELD_MACHINE_NAME]=[FIELD_VALUE]

Change the Exposed form to a block

For your use case, it sounds like you just want the results from your links and not really a search page with filters or facets. So, once you've got your tokens and URLs working, in your view settings expand the Advanced section and change the Exposed form in block to Yes. This will put all the filters you've added to a block that must be manually enabled. The filtering in the URL will still work, users just won't see the exposed form with all the possible filters.

Set up your fields to be links with tokens in your content type

It sounds like you've already got the tokens in links part working on your nodes or your view of nodes. In my testing, I found you can exclude all link arguments except the one you're filtering with, and the view will display everything that matches that field regardless of the other filters.

So, instead of having to make a link this: https://example.com/test-view?field_integer_field=&other_field=&another_field=&field_tags=[TOKEN_VALUE]

Your link can just include the one relevant filter: https://example.com/test-view?field_tags=[FIELD_VALUE_TOKEN]


How do I add reCaptcha to a custom form? I need to add a reCaptcha to my form; creating the form then adding the form ID to the reCaptcha settings did nothing.

I added the following form item to my form.

$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);

It's pretty simple but it may trip some others up so hopefully this post saves someone time.

If you want to use some other captcha method you have installed on your site you can easily replace #captcha_type by going to /admin/config/people/captcha and using a tool like Firebug (or just view the page source and do some hunting) to view the options for the "Default challenge type" field on the captcha admin settings page. The values of each option is a valid option for the #captcha_type.


Show New Comment Count in View If you use the messaging system in Drupal.org, you have noticed that if you go to your messages, there may be a link that says New Message next to the thread.

We have Q&A section where people ask questions and others leave comments.

What is the proper field to add in views that will show "New Message" or "X new messages". The notification will be to the login user only.


Conditional field display in node template I have a specific content type that I am overwriting the template node--contenttype.html.twig.

This conent type has 4 fields.

Title
Body
Image
Video

I am trying to hide the image field from displaying if VIDEO field has value. Which I am doing by using this code in custom twig template.

{% if node.field_video is not empty %}
{{ content.field_video }}
{% else %}
  {{ content.field_image }}
{% endif %}

The only problem is that I get one of the fields printed as needed plus I get both fields shown.

Video filed is displayed, plus I get an image and video shown again. Wherever those fields are positioned in MANAGE DISPLAY.

If I disable the two fields in MANAGE DISPLAY then, nothing shows up at all.

How can this be fixed?

You wrote that you are using Twig conditions to selectively print fields, but they show up twice now. This most likely is, because your template still renders the entire content variable somewhere like {{ content }}.

You can easily avoid the fields being rendered twice by using the without Twig filter. Locate the {{ content }} part in your template and alter it to

{{ content|without('field_video', 'field_image') }}


Accordion display for views inside panel I have a panel page which contains 2 views. I only want 1 view to display as an accordion. My problems are -

If I set the style setting of the view to accordion - nothing happens.
If I set the style setting of the panel to accordion - both views become accordions.

I think panel settings are overriding view settings.
Any idea how to fix this?

You can do it by using these modules :

Panels Accordion

  Panels Accordion provides an accordion display within Panels. By using
  accordions you can fit more content into smaller areas and allow your
  users to expand each section as needed. This uses the existing jQuery
  file for the accordion effect. The layout settings allow you to choose
  the action, effect, and speed for accordions.

views Accordion

  Views Accordion provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using
  the first field as the header for the accordion rows.


Installation issue (drush problem?) I was trying to install Aegir following the Automatic install guide, but I get an error. I've tried to install Aegir 2, then tried also Aegir 3, but the error is the same. Any clues?

Here's the message:

  The following settings will be used:
    Aegir frontend URL: site.dev.local
    Master server FQDN: site.dev.local
    Aegir root: /var/aegir
    Aegir user: aegir
    Web group: www-data
    Web server: apache
    Web server port: 80
    Aegir DB host: localhost
    Aegir DB user: root
    Aegir DB password:
    Aegir DB port: 3306
    Aegir version: 7.x-3.x
    Aegir platform path: /var/aegir/hostmaster-7.x-3.x
    Admin email: aegir@site.dev.local

  Aegir install profile: hostmaster

  Do you really want to proceed with the install (y/n): y
  Enabling hosting-queued daemon

  The drush command '@hostmaster pm-enable hosting_queued' could not be found.  Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions.                       [error]
  A Drupal installation directory could not be found                                                                                [error]

  dpkg: error processing package aegir3-hostmaster (--configure):
   subprocess installed post-installation script returned error exit status 1
  dpkg: dependency problems prevent configuration of aegir3:
   aegir3 depends on aegir3-hostmaster (>= 3.0.1); however:
    Package aegir3-hostmaster is not configured yet.

  dpkg: error processing package aegir3 (--configure):
   dependency problems - leaving unconfigured
  No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                Errors were encountered while processing:
   aegir3-hostmaster
   aegir3
  E: Sub-process /usr/bin/dpkg returned an error code (1)

Thanks!

The most common problem that could cause this is a broken mail setup.

Please the if you can sent an email from the server's cli to aegir@site.dev.local


How do I create a year-only drop-down field? How do I create a year-only drop-down field?

I want to create a Drupal 8 field that shows a year drop-down with 100 years to the current year.

The Year Only module provides this feature by defining a new field type.

.

It comes with a range configuration.

It produces the following result in the entity (node, ...) edit form. Configured with unlimited number of values in this example.


Allow Anonymous User to Access Form I'd like to create a form with Drupal that all users can access, but every time I try to access the form without being logged in, I get this error:

Access denied

You are not authorized to access this page.

How can I allow all users to access the form?

Select People -> Permissions, scroll down and adjust the permissions of Contact.


Custom Region doesnt render at the same position I have created a region in my theme that contains only menus. Each menu has its own visibility settings. For e.g. my main-menu is everywhere visible except at /blog/* and my blog-menu only at /blog/*. I use this as my main navigation bar region.

My issue is that i call this region in my page.tpl.php with

<?php //print zurb_foundation_links__topbar_main_menu($main_menu); ?>
    <?php print render($page['menu']);
    ?>

but the html structure that is printed is different to what I need. The following is what gets printed. As you can see its creating a new section with a list inside. I want to get that menu in the section that is currently empty (be aware that I'm printing it at the correct position in my tpl.). I also need to change its ID & CSS Classes.

Lernumgebungen

Unterstützung

Förderung

Projekte

Kontakt

I want to avoid to call the menu directly instead of the region. The reason behind it is as I wrote in the beginning the visibility settings. The region contains menus that differ by the URL.

You can override the block template use by your position (block--menu.tpl.php) directly in your theme folder. By default, the render of your menu must use block.tpl.php from the block module.

I recommend you to have a look at the Working with template suggestions page, and to enable the Theme debug mode to see witch template are used for your block menu.

After, to modify the Classes and the ID of your menu, I recommend you to work with template_preprocess_block hook to modify the block object before the render print it.

You can also have a look at the theme_menu_tree hook, to be able to modify a wrapper of the menu tree, depending on conditions (menu names).
There is also a THEMENAME_menu_tree__MENU_NAME possible method, that work only for one specific menu.


How do I get the node type label from a node object? I'm trying to get the bundle label (node type label) of the node from a node object in Drupal 8.

This works, but seems long-winded:

$node_type = \Drupal::entityManager()->getStorage('node_type')->load($node->getType())->get('name');

Is there another way to get the bundle label, possible in a less complicated way?

The following code works, as pointed out from @Clive.

$type_name = $node->type->entity->label();


Using REST API for data storage for user definable content I might be barking up the wrong tree completely however I am trying to achieve the following.

Drupal 7.
Custom REST web service which can hold user definable content types.

These pieces of content are stored and revisioned at a entity level. (not at a field level like drupal)

I want to be able to use Entity API + Entity Model to define Content Types to store in the REST service.
When inserting DO NOT create the Drupal field tables.

When I hook_entity_insert the field tables are still being created. How can I prevent Drupal from creating these tables.

Also, does this sound like the best way to go about this? Is there an easier way to achieve using REST services and not duplicating data in the Drupal DB?

Thanks.

This is achieved by creating a custom Entity Controller class, extending either the DrupalDefaultEntityController or creating a DrupalEntityControllerInterface implementation.

Then create a field storage engine, using the Field Storage API and  attach the correct fields where required.

I used the MongoDB mongodb_field_storage module for reference.

This all works as expected, and I do not use the Drupal database to store any Entity Metadata or field data. Only the field_config table is used.

The only hiccup I have is that the Drupal 7 'Per Field' storage engine actually needs to be defined in the variable table setting the field_storage_default to your custom storage engine. I have yet to find a way to hook into this on a per field basis without patching core. See here for more details.


How to a use a template file to theme a form? While nodes, comments, blocks and many other things in Drupal are themed using theme template files (like node.tpl.php), forms are a different story. There are no theme template files for forms. How can I get a particular form to use a custom theme template?

It's completely reasonable to want to use a tpl file to display a form. You can use lots of extraneous CSS and #prefix/#suffix properties to achieve similar results, but by using tpl's you don't have to clutter up the separation of your logic and presentation layers and don't have to target ugly CSS selectors like #user-login label. Here's an example in Drupal 7...

mytheme/template.php:

function mytheme_theme($existing, $type, $theme, $path) {
    // Ex 1: the "story" node edit form.
    $items['story_node_form'] = array(
        'render element' => 'form',
        'template' => 'node-edit--story',
        'path' => drupal_get_path('theme', 'mytheme') . '/template/form',
    );

    // Ex 2: a custom form that comes from a custom module's "custom_donate_form()" function.
    $items['custom_donate_form'] = array(
        'render element' => 'form',
        'template' => 'donate',
        'path' => drupal_get_path('theme', 'mytheme') . '/template/form',
    );

    return $items;
}

custom_donate_form():

function custom_donate_form($form, &$form_state) {
    $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );
    $form['last_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Last name')),
    );
    $form['address'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Address')),
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('City')),
    );
    $form['state'] = array(
        '#type' => 'select',
        '#options' => array(
            'default' => 'State',
            '...' => '...',
        ),
    );
    $form['zip'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Zip')),
    );
    $form['email'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Email')),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Phone')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );

    return $form;
}

mytheme/template/form/donate.tpl.php:

Contact Information

                <?php print render($form['first_name']); ?>

                <?php print render($form['last_name']); ?>

                <?php print render($form['address']); ?>

                <?php print render($form['city']); ?>

                <?php print render($form['state']); ?>

                <?php print render($form['zip']); ?>

                <?php print render($form['email']); ?>

                <?php print render($form['phone']); ?>

            <?php print render($form['submit']); ?>

<?php print drupal_render_children($form); ?>

This is using Foundation, which gives us a form like this:


How can I get the submission ID in a custom submit handler? I have added a submission handler in a .module file to execute some custom code when a webform is submitted.
function mh_newsletter_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'webform_submission_newsletter_node_26_add_form') {
    $form['#validate'][] = 'mh_newsletter_form_validate';
    $form['actions']['submit']['#submit'][] = 'mh_newsletter_form_submit';
  }
}

function mh_newsletter_form_submit($form, &$form_state) {
  // Custom code
}

I'm unable to access the webform submission ID. How can I get that value?

To get the webform submission ID in a custom form handler, I used the following code.
function MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id== 'webform_submission_add_form') {
    $form['actions']['submit']['#submit'][] = 'MODULE_custom_submit_handler';
  }
}

function MODULE_custom_submit_handler(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $webform_submission_id = $form_state->getFormObject()->getEntity()->id();
 }


How to setup year increment? I use Date module in D7, and I create new field "decade" (field type is Date).

Also in the settings, I add a custom input format 'Y' (only years). There is increment for time (+/-30 minutes), but I need increments for years (+/- 10 year). In node add form I need selectbox with values like:

1700
1710
1720
1730
....
now
How can I do that?

You shouldn't use a date format for your field

I advice you to use CCK module (7.x-2.x-dev)

  some miscellaneous helpers to do things that core will not do, like
  maintain the PHP code snippets some fields may have been using to
  define allowed values (partially working)

With this module, you define these kind of allowed values from a php code