You dont need to do access the form elements directly like that. You can use some unobtrusive JavaScript with jQuery to do the same thing.

;(function ($){
    Drupal.behaviors.YOUR_FUNCTION = {
        attach: function (context, settings) {
                    // your script goes here...
               };
    };
})(jQuery);

Create a scripts file and add the above. Add a reference to that file in your .info file.

Then add your script.

Some references if your not familiar with jQuery.

http://api.jquery.com/class-selector/
http://api.jquery.com/blur/
http://api.jquery.com/focus/
http://api.jquery.com/val/


Depending on what you're trying to add/change hook_field_widget_form_alter() might be an option. It's invoked whenever a field widget is built and you have access to context data so you can easily determine which field type/entity type/bundle you're dealing with.

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}


Which hook can I use for a Drupal webform Post to a Google Spreadsheet?

The hook you need is hook_webform_submission_presave($node, $submission) that, according to the documentation allows to modify a Webform submission, prior to saving it in the database.

So all values should be available there.


$order_id = arg(1);
$orderLoad = commerce_order_load($order_id);

foreach ($orderLoad->commerce_line_items['und'] as $line) {
    $line_item = commerce_line_item_load($line['line_item_id']);
    $product_id = $line_item->commerce_product['und'][0]['product_id'];
    $product = commerce_product_load($product_id);
    $type = $product->type;

    if($type == 'X'){
      //go mental
    }
}

If anyone has any improvements to this code (to make it more efficient etc. then please comment below). Thanks.


How to use summary field conditionally for display?

The Description text field needs to be of type Long text and summary.

With view modes (admin/structure/types/manage/band/display) you can configure how the fields must be rendered.

In the view mode Teaser you could set the format to Summary or trimmed and in other view modes to Default.

When viewing the content type Band as a full page you can render the view mode Default. When rendering a list of Bands with views you can set the view mode to Teaser.


How to detect when a user navigates to a taxonomy term page and access that terms data?

Since there is no global variable that you could use to load the node, you will have to use code like the following:

<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
$node = node_load(arg(1));
}
dsm(get_defined_vars());
?>

The dsm(get_defined_vars()); part is of course optional and will only work if you have the devel module enabled. However, if you do have devel, you will be able to see the whole $node object and the tags associated with the specific node.

Notice, that if you are in a term page, you can use the same principle to load a specific term. For example:

<?php
if ( arg(0) == 'tag' && is_numeric(arg(1)) && ! arg(2) ) {
$term = taxonomy_term_load(arg(1));
}
dsm(get_defined_vars());
?>


Newbie Question: Modify forms before render

I really wouldn't use jquery to wrap form elements renderend by Drupal. What if the user has javascript disabled ?

Drupal provides several core api functions for theming forms, one of those is
http://api.drupal.org/api/drupal/includes--form.inc/function/theme_form_element/7

place the function in the template.php file of your custom theme (change the function name from 'theme_form_element' to 'mytheme_form_element'

change the contents of the function to your liking, especially look at places where there's html markup involved


Prevent cache when updating with field_attach_update

Sorry I didn't do more digging before asking this, but going to answer my own question in case someone else finds this.

I've taken a look inside the user_save function, and seen that it does some invoking, so I did it too. Surprise: it worked (EntityCache was the bad guy who was caching everything BTW).

Here's my code for reference:

$usr->field_somefield[LANGUAGE_NONE][0]['value'] = 0;
field_attach_presave('user', $usr);
module_invoke_all('entity_presave', $usr, 'user');
module_invoke_all('entity_update', $usr, 'user');
field_attach_update('user', $usr);


cck delta values: delta with leading space = "historical change," no leading space = "multiple selection?"

Use a custom module and unset the field items using hook_form_alter(), or do it in your themes template.php.

/**
* Implements hook_form_alter().
*/
function YOUR_THEME_form_alter(&$form, &$form_state) {
  if ( $form_id= 'YOUR_FORM_ID' ) {
    unset($form['YOUR_FORM_FIELD']);
    // ... ADD MORE
  }
}


Change order of breadcrumbs elements in hook hook_system_breadcrumb_alter

Create a new breadcrumb instance:

$links = $breadcrumb->getLinks();
// change order of $links
$cacheability = \Drupal\Core\Cache\CacheableMetadata::createFromObject($breadcrumb);
$breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
$breadcrumb->setLinks($links);
$breadcrumb->addCacheableDependency($cacheability);


In which order should one build up a multilingual site?

I would suggest starting with setting up the multilingual backend. Besides what Drupal core already offers you probably want to use the i18n module. Then you could move on to content migration. If there is no module that can do that for you I'd suggest writing a PHP script rather than manually copy/paste-ing (seeing as the amount of data seems to be fairly large). You could make use of either node_save() or drupal_form_submit() for this task. The first option is a quicker way of adding nodes while the second mimics more closely normal node creation by invoking additional hooks. There's a solid amount of information about using them to create nodes programmatically available on the web that you can make use of. At what point to work on appearance (templates and theming) shouldn't matter too much, but it's probably somewhat easier at later stages when you already have the content to work with.


Alternate solution to avoid handling a huge number of menu items

Context will handle it, but needs some template.php additions.

and it looks like Menu Position will too.


You can use Views attachment to put them all together.  See example at http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments


How to return a DatabaseStatementBase object

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());
}


Difficult to separate your php from javascript, but if you set js variable with this php code it should execute first and can be used within leaflet js function later:

<?php render('<script>var username = "'.$GLOBALS['user'].'";</script>'); ?>


1) Use EntityFieldQuery to load a list of entity ID's.

2) Load the full entity using entity_load.

3) Optionally wrap the entity using entity_metadata_wrapper.

4) For each entity, manipulate the field to your desire then save the entity. If you have it in a wrapper use $entity_wrapper_object->save() or if using the entity it's entity_save.

If you want to do this quickly and easily, install the devel module and use the PHP execute page @ example.com/devel/php. Go through each step and ensure you have the correct data to work with at each stage.

Optionally you could use something like VBO to create a view and manipulate the data using a PHP field. This might be easier depending on your experience level.

How to use EFQ


Migrating orders doesn't migrate total values

The bi-directional link is a relic of the Drupal 7 entity API at the time we wrote Drupal Commerce 1.x. It was basically a DX concession of dubious benefit, but we'll be fixing that in 2.x. ; )

As for how order totals are calculated, order save automatically calculates the total by summing up all of the price components in the "total" price fields on line items. If you haven't properly set the associations in your line items or if you haven't set the price component arrays for the line items you've created, your order total will not calculate properly.


Feeds with Xpath Parser won't import images using image URL in XML file

yes it's possible.
Feeds is buggy sometimes.

Try this patch:
http://drupal.org/node/1482530

Can you give more information about what isn't working? What errors are produced etc.


How to enable/disable Billing Information in Commerce depending on the payment method

There is no way just through Rules to influence the visibility of a checkout pane. Instead, you'll need to use hook_form_alter() and hook_commerce_checkout_pane_info_alter(). Why both?

You have to use the form alter to remove or disable the billing information checkout pane when you detect PayPal has been selected, which means you also need the payment method selection to be first (and, in the most simplest case, on its own page).

You have to use the checkout pane info alter to set your own validate and submit callbacks for the billing information checkout pane. These should also check the payment method and only invoke the default callbacks if the proper payment method was selected. The reason for this step is that the checkout form validates / submits checkout panes based on where they're configured to appear in the checkout form, not based on whether or not they were actually present on the finally rendered form. You can alter a pane out of the checkout form's array, but its default validate callback will still process it as if it had been there.

To determine what payment method was selected, look in $order->data['payment_method'].


Recieving PDOExceptions and missing fields and table on Module installation

I noticed that I was getting this error only on Modules that I've been installing directly into the modules/contrib/  folder.  Using the 'Install new module' button in 'Modules' installation was not bringing up the PDO exception.

By the way if anyone else couldn't find that button thats becuase you need to activate the 'Update Manager' module first to be able to see it.

I hope this helps anyone else search for the same issue.


Disabling Twig cache does not prevent Drupal from caching

https://www.drupal.org/node/2598914

Follow the steps in the above link and it should definitely help with the caching issue.


Programmatically load the uid of the owner of a viewed profile2 entity

Try with :

global $user; //is the current user

// you can get the viewing user id :
$user_id = arg(1);

if ($user->uid != $user_id){
}


How do I programmatically add a new language?

You can use below way:

 \Drupal::service('module_installer')->install(['language']);
  $langcode = 'ca'; // get language from Your Form Input
    //print_r($langcode);
  $language = ConfigurableLanguage::createFromLangcode($langcode);
  $language->save();


It appears to me that you are missing something in the setup of your FAQ. E.g., if you're using categorized faq nodes, then you also need to do some taxonomy vocabulary setup. Without doing so, you might suffer an issue similar to this issue.

Here are some links to Community documentation you may want to verify:

FAQ - Basic Setup Guide.
FAQ - Settings.


How can I render a responsive image style from an image in the theme directory?

This is the same when using the image filters from the Twig Tweak
  module: You can't render responsive images from a random URI, it has
  to be an URI that is stored in the file_managed DB table. But with
  Twig tweak you can render normal image styles from random URIs, and
  manually create a responsive image tag by rendering multiple normal
  image styles. – Hudri

Great, so there is a workaround one can do, manually create one:

{% set imagePath = '/themes/custom/mytheme/img/mygraphic.png' %}
<img srcset="{{ imagePath|image_style('thumbnail') }} 300w, {{ imagePath|image_style('medium') }} 800w" src="{{ file_url(imagePath) }}" alt="some graphic image" typeof="foaf:Image"/>


How to determine create access for a given enitty and bundle

OK, I have figured it out. Here's what I am using to get access for the current user (in the createAccess() step the second parameter can be an account, if you need to pass an account):

// Before this, you need to get the entity type and bundle,
// shown here as $entity_type and $bundle .
$entity_manager = \Drupal::entityTypeManager();
$access_handler = $entity_manager->getAccessControlHandler($entity_type);
$access = FALSE;
if ($bundle) {
  $access = $access_handler->createAccess($bundle);
}
else {
  $access = $access_handler->createAccess();
}


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

probably, this would help you.

Drupal support forum page


Drupal 7 View display "Page not found" without contextual filter

Click on your second argument, under Contextual Filter.

You should see an option - "When the filter value is not in the URL". That's where you specify what to do when the argument, i.e. "/sector" is not present. Provide the appropriate selection, and make sure Show "Page not found" is not selected.


How to disallow selected roles to edit node titles?

You could use the Title module

This converts the Title to fields API and should work with permissions as well. Basically it replaces the node title with a field


how to stop a view from executing within a views hook

this worked for me, i unset all the results and the view disappeared

foreach ($view->result as $key => $value) {
    unset ($view->result[$key]); // delete a row

  }


That can happen if the site is redirecting to a different domain or to a secure/non-secure protocol upon login. I.e. with/without www or to http/https. If so, you could set a base domain and cookie domain in settings.php, and/or enable www/non-www redirect in .htaccess.

It also seems there may be a problem with PHP 5.6.1.
https://www.drupal.org/node/2723927
https://www.drupal.org/node/2379019


While waiting for an answer, I found the solution at this blog.

All you need to do is to edit the settings.php under /sites/default folder.

Here are the two variables that need to be set:

ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

Be sure to change also the cache expiry of the following variable according to your needs:

ini_set('session.cache_expire',     3600);
ini_set('session.cookie_lifetime',  3600);
ini_set('session.gc_maxlifetime',   3600);

The default is 200000. 3600 is equavalent to 1 hour.


How to patch your htaccess file correctly in composer.json

In the scripts section of your composer.json file, use the following:

"post-drupal-scaffold-cmd": [
  "patch -p0 < patches/htaccess.patch"
]

(this requires "drupal-composer/drupal-scaffold" in your require section)


Tabs: invalidating cache tags does not lead to a rebuild of the tabs

Two suggestions to improve caching:

Even if you don't want to make a decision to allow or deny access you can return a neutral result to add cache metadata.

The custom cache tag can be replaced by the list tag ENTITY_TYPE_list, which is invalidated automatically when entities are added or deleted.

The resulting code:
  public function access(AccountInterface $account) {
    if ($entity_does_not_exist) {
      return AccessResult::forbidden()->addCacheTags(['my_entity_list']);
    }
    return AccessResult::neutral()->addCacheTags(['my_entity_list']);
  }

postDelete() and postSave() are no longer necessary.


D7 Execute javascript on views exposed filters AJAX submit (Dropkick)

You need to use ajaxcomplete function of jquery to perform any script after the ajax call. I have not worked on "Dropkick" module, but I have implemented "Selectbox" jquery plugin in my site to format the dropdown.

May be it will help you.

$(document).ajaxComplete(function(e, xhr, settings) {

  if (settings.url == Drupal.settings.basePath + "?q=views/ajax" || settings.url == Drupal.settings.basePath + "views/ajax" || settings.url == Drupal.settings.basePath + "?q=system/ajax" ||  settings.url == Drupal.settings.basePath + "system/ajax") {
 // enable selectBox jQuery plugin for all <select> elements
    $("SELECT").selectBox();
    //Drupal.attachbehaviours();

  }
});


How to append a Value in cck field in a for loop?

Solved It by using

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


I had to enable the Advanced Import module from Biblio in order to get the file to import.

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


How to get exact value of a field from database?

I'm not sure there's an API function to get this directly; the field functions (like  field_get_items()) seem to rely on a loaded entity object, which in the case of a node would have gone through the whole loading process.

If you want to get the value directly you'll find the data in the field_data_field_* tables. A query like the following would get the data for a node of type 'article', assuming a text field called 'field_my_field' with a column name of 'value'. It also assumes the field is not multiple; if it is you'll need to remove the last line of the query and loop through $val instead:

$val = db_select('field_data_field_my_field', 'f')
  ->fields('f', array('field_my_field_value'))
  ->condition('entity_type', 'node')
  ->condition('bundle', 'article')
  ->condition('entity_id', $node->nid)
  ->execute()
  ->fetchField();

If you've got node revisions turned on for the content type in question you'll probably need to alter this to query the field_revision_field_my_field table instead, and use the node revision id (vid) instead.


Seperate Drupal instance as files server for other Drupal instances

You could use feeds module to periodically import file URIs from XML on your file server to you individual drupal instances. You might then be able to hook that up with the media module and use the files on all your different sites.

Edit:
If you're just looking for a cdn for your images you could probably just use Amazon S3. Looks like there's a few modules already built to work with it


I am already not try this but i think it will work

function mymodule_form_alter(&$form, &$form_state, $form_id) {

  global $user;
  if ($form_id == 'FORM_ID') {
  if (in_array('yourrole', $user->roles)) {
  $form['your_field']['#access'] = FALSE;
    }
  }
}


If you are using entity translation for translating the content, you will have to install the Search API Entity Translation module.

  Search API Entity Translation module provides multilingual support for the Search API module through integration with Entity Translation.

This module provides a new index type : "multilingual node index", similar to the "default node index" which is provided by default by Search API.
You can use this to create the views and they will honor the language selected from the language switcher.


How do I get fields of a certain field type?

I came across this the other day and remembered seeing this question, so here it is, a somehow very unknown function (I have neveer seen anyone mention it in a blog or anything):

field_read_fields()

and the companion function:

field_read_instances()

For example, get all taxonomy term fields:

$taxonomy_fields = field_read_fields(array('type' => 'taxonomy_term_reference'));

Or get the instances for a field with the a machine name of field_image:

$image_field_instances = field_read_instances(array('field_name' => 'field_image'));


CSS and JS 404 On Admin Site Only - New Install

Don't forget AllowOverride All if your Apache is defaulted to AllowOverride None.  The missing directive was prohibiting rewriting from working [properly?] since I had, lastly, moved the rules to .htaccess (where they are in a default installation).  Added it to the "main" <Directory> in my <VirtualHost> and all is well.


Yes, you can do that programmatically using the function hook_form_alter in a custom module. Follow this for creating a custom module.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'contact_personal_form') {
    $form['new_field'] = array (
      '#title' => t('New field'),
      '#type' => 'textfield',
      'description' => t('The description of the new field goes here...'),
      '#required' => TRUE, // make the user to fill it compulsorily
    );
  }
}

Update: I forgot to mention that, the above code will just add the field to the form. The field is not added the mail you send. You should implement hook_mail_alter and add the field to the body, by something like:

function MODULE_mail_alter(&$message) {
  if($message['id'] == 'contact_user_mail') {
    $message['body'][] = $message['params']['new_field'];  //value of key 'new_field' same as in $form['new_field'] above in form alter
  }
}


How to use Rules to perform a simple anti-spam validation using specific keywords?

IMO you should use a captcha, such as:
reCAPTCHA

Uses the Google reCAPTCHA web service to improve the CAPTCHA system
and protect email addresses.

OR
Draggable Captcha

Here is an instruction video on how to set it up Drupal 7 Draggable Captcha - a more friendly way to prevent Spam
If spam still happening, which means they are indeed human and not bots, you could implement a point system. Where users need to gain points by doing something (login x amount of days or comment x amount of times etc..)
To create nodes, users need to have x amount of points.
In addition, you could also implement spam flags, where users can flag content as spam and have the content be auto deleted if x amount of flags are raised.


Managed file validation on first upload only

I ended up adding a custom validator only to the new_form file upload field:

'#type' => 'managed_file',
'#upload_validators' => array(
      'file_validate_unique' => array($file),
)

and then added a function:

function file_validate_unique($file) {
   $errors = array();
   $filename = $file->filename;
   if (file_exists('public://' . $filename)) {
         $errors[] = t('The file could not be uploaded because a file by that name already exists in the destination directory.');
   }
   return $errors;
}

now it only validates the new_form and outputs an error right when the user tries to upload the managed_file, before the form is even submitted.


Is it possible to implement an express checkout with Drupal commerce?

Here is a nice tutorial on how to set up an EXPRESS CHECKOUT using Rules
to bypass the add to cart stage.

I noticed there is a Commerce Express Checkout module, but I personally rather use rules to do it.

To display this on your home page, using the views module you'll need to create a block view  of your product and put it in your home page.


Problem with commerce_checkout_page_info() function

I think you can handle it with hook_form_later, try something like below,
change your condition according to your checkout base name ,
I hope this help you :

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, &$form_values, $form_id) {
  if($form['checkout_pane']['#value']['base'] == 'checkout_pane_review') {
    $form['submit']['#value']='yourvalue';
  }
}


Region for Main page content block field is required Error?

This post helped me get closer, but I thought I would provide a more concise answer for those following the same path.

If you are looking to remove all blocks from Drupal 7, like you would want to do if you were placing blocks by using Context, you want to make sure that core's "Main page content" is the last block removed.

Steps:

Select "- None -" for all other blocks, then click Save.
Then change the "Main page content" block's region to "- Select -" and
click Save.


How to notify site admin when user registers with a specific field checked

You should be able to accomplish this easily using the Rules module:

Create a rule that triggers 'After saving a new account'
Add a condition that determines whether the value of the field is set to the teacher value (Using 'Data Comparison').
Add an action element to send a notification email (System > Send Mail).


Inside your batch callback, where you do the batch work, you should be able to set $context['finished'] to 1, and that will signal to Drupal that the batch is complete.

So, in your case:

$error = FALSE;
try {
  $sth = $dbh->prepare($sql);
  $sth->bindParam(':newid',$new_id,PDO::PARAM_INT);
  $sth->bindParam(':id',$id,PDO::PARAM_INT);
  if($sth->execute()) {
    $context['results'][] = $sth->rowCount();
  }
  else {
    $error = TRUE;
  }
}
catch (PDOException $e) {
  $error = TRUE;
}
// If there was an error, immediately complete the batch process.
if ($error) {
  $context['finished'] = 1;
}

And, even better, you can pass in an error message in the $context as well, which you can check for in your finished callback, then display to the end user in case of failure.

If you want to immediately stop processing anything in other callbacks in the $operations list, you might also need to check for a static variable at the beginning of each callback, and skip the callback if it's in an error condition. You could try using variable_get/variable_set, or some other mechanism that persists between page requests. This would definitely be a hackish/last-resort solution, though!

See also:

How does the batch API work internally?
Batch operations API documentation


Trigger jQuery "add more" multiple times

It is possible that the ID of the "Add more" button you're targeting is changing as the first AJAX request comes back (the form will be rebuilt, so IDs of all elements will change). Try changing '#edit-fgm-node-example-form-group-stuff-add-more' to a class-based selector.


There is a beta version of a module that can help you achieve this:

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

  This module provides the ability to add form field widgets to a view to edit multiple entities at one time.

  Form field options will show up in a View's "Add field" list, prefixed with "Form field: " and then the name of the field being added.


How do I create a variable to check last time hook_cron() implemented from a custom module was ran?

You are implementing the wrong hook. What you are trying to implement is hook_variable_info(), used from the Variable module. Hook name apart, that hook implementation seems correct.

Instead of using variable_set(), you should use variable_set_value(). The equivalent of variable_get() is variable_get_value().

See the project page for more information about how to use the module API,  Variable API for a list of available functions, and variable.api.php for a list of hooks used from the Variable module.

The code you want to use should be similar to the following one.

function mymodule_cron() {
  if (variable_get_value('mymodule_last_run') <= strtotime('-1 day')) {
    // Omissis.
    variable_set_value('mymodule_last_run', REQUEST_TIME);
  }
}

function mymodule_variable_info($options) {
  $variable['mymodule_last_run'] = array(
    'title' => t('Last Run', array(), $options),
    'type' => 'datetime',
    'default' => 0,
  );
}

Notice that variable_get_value() doesn't need the default value, since it gets it from the hook_variable_info() implementation done from your module. If you need to use a different default, you call the function as variable_get_value('mymodule_last_run', array('default' => REQUEST_TIME).

As for your original code, you don't call t() as t(time(), array(), $options) because:

The first argument of t() must be a literal string, not the value returned from a function
time() returns an integer; even if it would be casted to a string, t() doesn't change an integer in any way, for example returning '1,000' when receiving 1000 as first argument.

If the Variable module is expecting a string (e.g. '19700318T19:00') as default value for a variable of type datetime, you need to use a different function.


Hide or remove the "Remove" button, "Quantity" box, and Price for specific product/SKU on cart page of Ubercart

You could achive this with hook_form_alter() and hide the field with $form['field_name']['#access'] = FALSE;


It is a bug in the rules module. The issue is discussed HERE.
You can either apply the patch in the issue or use the latest dev version of the jquery update module which allows you to select the drupal default version of jquery for the backend.


Why my custom submit handler isn't working in menu item edit form?

Forms can have submit callbacks in two places. Either on the form level or on the button that is pressed. The form level callbacks are only invoked if no button-specific callbacks are specified.

Entity forms generally have the submit callbacks on the submit button, which is usually $form['actions']['submit']['#submit'].

This was the same in Drupal 7, although the node form and possibly others had a backwards compatibility layer that also invoked form-level submit callbacks, but this was removed.


How can I check that the file is present in database entry and also in files folder?

You can use file_destination() drupal function to  check if file already exists in sites/default/files with second parameter as FILE_EXISTS_ERROR.

if (!file_destination($uri, FILE_EXISTS_ERROR)) {
  // The file exist
  // Do something
}


Add an image selection list to a content type

I Found a way to do so Using Node reference field type, enabled by Drupal 6 CCK module or in Drupal 7 it's with: Reference Module

Once the module enabled, Node reference will be available as CCK field type :)


Views: no results text not showing when contextual filter is set & no results returned

I just had a similar issue, I had a block view showing the current category:

Block view
Contextual Filter - Taxonomy term: Term ID - Provide default value (term id from url)
fields
filters
No results - Global text field

Like you, because the contextual filter was set to provide default value I never saw the no results text.

SOLUTION

Edit the contextual filter and scroll down to the bottom, under

  "When the filter value IS available or a default is provided"

Check Specify validation criteria.
Leave validator as default.
Change "Action to take if filter value does not validate" to "display contents of No result found".

Bingo, on the Overview page with no term passed I get the no results found text, and when I go to a category page it picks up the term and displays the correct content.


Subtheme is the answer. The theme is the last line in the rendering of the page which is why you generally can't override it. The H2 tags is most likely hardcoded in the page template which is why you can't alter it.

that being said, you could in a module make garland use a page template that your module has created. This require some complex altering of the Drupal theming system, and is not something you want to do, unless you understand the consequences.


User having issue with site being redirected to home page from every link

It is possibly an issue with a cookie. Have that user try to use another browser to check if the same problem occurs with that browser.

Or just delete the session cookie in the browser being used, then check if the issue is resolved.


How to show preview of entered values in previous steps in webform with multiple steps

You can try Webform Bonus Pack module, it have the option to preview webform fields before submission.

  which allows you to add a summary component directly to your form in
  the same way you would add a textfield or any other component type.
  Install that module and add a summary field to your form, selecting
  which fields you would like to include in the summary. If you would
  like it on its own page, make sure to add a pagebreak component first.

also take a look at this https://drupal.org/node/435232


How can I use LottieFiles to render animations?

Sure it is. See the LottiFiles sample. First, you need to add the  Lotti player library yourself first.

https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js

Learn about adding Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme in the docs.

And second, find a way to place the Lotti markup on the page somewhere.

<lottie-player
    src="https://assets4.lottiefiles.com/packages/lf20_32NcN8.json"
    background="transparent"
    speed="1"
    style="width: 300px; height: 300px;"
    loop controls autoplay>
</lottie-player>

I'd probably have a field for that where you only paste the animation file URL or upload the animation file which then gets wrapped by the corresponding markup via a custom field formatter.

<lottie-player
    src="{{ field_lotti.entity.url }}"
    background="transparent"
    speed="1"
    style="width: 300px; height: 300px;"
    loop controls autoplay>
</lottie-player>


text formats - not allowed tags are saved anyway

Were not the tags supposed to be deleted by drupal?

No, the mantra in Drupal is "save the raw string, sanitise on output".

What you're seeing is the filter system working as designed.

As you mentioned in the comments, the Sanitizable (formatted text) module does exactly what you're looking for.

  The Sanitize module allows administrators to configure a text format to be applied to formatted text before storage. This is useful to ensure clean and valid data in the database.


How can I upload photos from iphone/Android to Drupal?

phonegap and titanium are probably considered easier than for example, developing a separate native app for iOS and Android.

However, if you are looking for something even easier, perhaps you could explore using an existing application that uploads images to a service such as Flickr. A query for iPhone apps on Flickr's App Garden provides plenty of results. You could then use an app such as this one to upload images and then use Flickr's API to create image galleries in Drupal. Plus, you can make calls to Flickr from Drupal and receive data in different formats including JSON and XML. It really doesn't get easier than that.

The Flickr contrib module could then provide you with plenty of examples of how to query Flickr's API.

The fact that your images would be hosted by a third party could be seen as good or a drawback, depending on how you analyze it.


Finally got it. It was mod_security indeed. I could not see errors in my (cpanel) log because I am on a shared host but went ssh and saw it:

UNSUPPORTED DELAYED Rules: POST request must have a Content-Length header

$header->header('Content-Type' => 'application/x-www-form-urlencoded', 'Content-Length' => 0, 'X-CSRF-Token' => $token);

That did the trick

Thank you Molot and David for taking the time to respond


Webform Drupal 8, node and form, how to pass node field info to form?

The location node is considered the 'source entity' and is automatically tracked.

You can use the [webform_submission:node] to pull information from the location node into the 'Default webform submission data (YAML)'. For example, to get the location's title you should use the [webform_submission:node:title] token.


This isn't really a Drupal question.

One of the usual methods is to use absolute positioning to remove the title from the document flow. Starting from HTML looking something like (e.g., rewriting with views):

Image title

Then use CSS rules something like:

.my-frame { position: relative; }
.my-title { position: absolute; top: 10; left: 10; }


Get a list of field variables for template code

Use Devel module and then with using get_defined_vars you can get a list of defined variables. then in you template file use the following snippet

<?php
 dsm(get_defined_vars());
// or even  dsm(get_defined_vars());
?>

and another solution is based on  hook_preprocess. just dumps the variables there.

on your template.theme file

mymodule_preprocess(&$vars, $hook) {
dpm($vars);
}

**Update*
if you want to see the $variables on node template try on your template.

copy/paste this snippet on your template.php then clear the cache
function YOURTHEMENAME_preprocess_node(&$variables) {
    dpm($variables);
    // you can add or remove whatever you want to it here
}

if your theme name is themetastic So

function themetastic_preprocess_node(&$variables) {
    dpm($variables);
    // you can add or remove whatever you want to it here
}

Ref: Read this to learn more about preprocessing


Close commenting after X comments have been posted

You could use the drupal rules module to set up a system to close your comments after X amount of comments. In combination with the views bulk operations module, you could set up a rule for "new comment has been posted."

For the condition compare the number of results from a VBO created that counts the number of comments on the node the comment was posted to and compare it to the number of comments you want before closing. If there are 20 comments posted and the number you want to close at is 20 the rule will move on to the action.

The action would be a custom php snippet to set comments from read / write to read only. The snippet I was using for Drupal 6 was

$node->comment = '1';
return array("node" => $node);

so it may need to be modified slightly for 7.

With that all being said, if you are looking to set up an event registration setup where a certain number of people can sign up, you are actually looking for the entity registration module.

From the drupal.org website

  Entity Registration does lots of things you are expecting from a
  registration system (like allowing you to restrict the number of total
  registrations for a given event), and other stuff you are crossing
  your fingers and hoping for (like building in automated reminder
  messages for your registrants).


Override entityreference autocomplete and return entityfieldquery output

EntityReference uses the ctools plugin system to define selection handlers which feed into the autocomplete options.  The interface definition is defined in entityreference/plugins/selection/abstract.inc.  In that same directory, you will see the two included handlers, Simple and Views.  Each of these is defined by two files, one for the class itself, and one with an array to register the plugin with ctools.

To provide your own selection handler, first tell ctools where to look for your plugin by implementing hook_ctools_plugin_directory.

/**
 * Implements hook_ctools_plugin_directory().
 */
function wl_event_ctools_plugin_directory($module, $plugin) {
  if ($module == 'entityreference') {
    return 'plugins/' . $plugin;
  }
}

Then create 2 files in wl_event/plugins/selection similar to those in the entityreference.  The .inc file should define the ctools plugin info, and the .class.php file should contain your plugin class.  Most likely you'll want to subclass EntityReference_SelectionHandler_Generic and just override the appropriate methods.

Lastly, make sure you add the file with your plugin class to the files[] array in your modules info file so that the autoloader can find it.


This functionality appears to already be in the current release of Display Suite.  See here for details: https://www.drupal.org/node/1673626


Drupal 7 Megamenu Construction Using Views in Menu and a menu module?

I would try the Superfish module. The Menu Views module page states it should be compatible with the current stable release of Superfish.

Superfish is also responsive out-of-the-box (based on user agent or window width).


I was able to accomplish this adding or statements to my calendar's existing contextual filter. I added each date field as an "or" statement and now it shows each date on the calendar.


Change the number of entries depending on a theme setting

You could do this, but it will require that you know a bit about views exports.

You would have to create the view in code, by exporting it, this could be done with features or the views alone and use hook_default_views.

Once views read the view from code instead of the database you could insert a dynamic value for the number of items shown by the view, gotten from the theme setting. You would need to make sure that the value is formatted the way views expects it.

One important note. You can't make any changes to the way, as it will stop reading from the code and use the database instead. When this happens the dynamic value will be replace with a static one.


View filter - Show content that has 1 field matching another field in current node

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

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

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

Or refine this code by yourself.


Does unset($form['field']); in hook_form_alter stop entity reference views select list queries from running?

Short Answer: Unsetting the form element won't stop the view from being called. You may want to use an autocomplete widget instead if that is an option (if only to test your theory is correct - that the views are slowing the page load).

Long Answer:
When hook_form_alter is called, what you get is a form that contains elements from the Field API. Modules such as Entity Reference typically do not create new Form API elements - instead they provide field widgets.

Such modules contain code that generate their widget using the base elements in the Form API. This is typically done when field_attach_form is called, and it is at this point that the view would be called.

This is done before hook_form_alter is called. So what you get in form alter is the low level Form API elements - not the high level widget. Unsetting the field won't make a difference, since the low-level elements that contain the list of options have already been created.

It is possible that some module would actually use hook_form_alter to populate their widget - I have seen this done, and must say it is very bad practice - but I do not think this is the case with Entity Reference.


How to have different URLs for microsites?

This is what the Domain Access module is for.  Essentially, it allows you to run multiple Drupal sites out of the same database, and share content.

Sending particular pieces of content to different domains is rather easy; a new tab shows up on edit panels.

It integrates nicely with Panels, Views, and other modules that use cTools, as domain rules show up as selection criteria.

For the Apache side, you need to configure it so that your multiple domains point to the same DOCROOT.  How this is done depends on how you are running your sites.  If you are using virtual hosts, then you set up additional ServerAlias settings for your <VirtualHost>


Show a link in a menu even if user has no access

Add to the menu a page with no access restrictions that contains the login form. (But still called "Add Content Type" or whatever it's currently called).

Using Rules, add redirects to node/add/content-type

automatically redirects logged-in users
automatically redirects anonymous once logged in from the above page


Display text according to the access to a field

You can use drupal_set_message in hook_node_view to display the text as a message to the users.

function MODULE_NAME_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'your_node_type') {
    if (!field_access('view', field_info_field('field_name'),'node', $node)) {
      drupal_set_message(t('Your text.'), 'warning');
    }
  }
}


Save language preference for future visit

Actually there are two modules, Language Cookie and Locale Cookie.  Both work about the same, but both have problems if you are using Varnish as a cache.  There was some work on Language Cookie done to fix this, but I haven't been able to get it working with Varnish yet.  If you're not working with Varnish, though, it works great.


Let user pick background Image/Color on node form

I suggest you do it in your  node.tpl.php. You can add the style attribute directly to the attributes array in a node preprocess.

in your template.php , load(add css file ) or insert in-line css style

function THEMENAME_preprocess_node(&$variables) {
  $type = $variables['type'];
   // dpm($$variables['node']);
  // as example
 if($color=$variables['node']->field_color['und'][0]['value']){
 $css = "p {background-color: $color }";
 drupal_add_css($css, 'inline');
   }
 }

you can do something like this .I hope this solution get you some good clue .


Moving the Sites/Default/Files Directory

Look in Admin > Config > Media > File System:

/admin/config/media/file-system

  Public file system path
  sites/default/files
  A local file system path where public files will be stored. This directory must exist and be writable by Drupal. This directory must be relative to the Drupal installation directory and be accessible over the web. This must be changed in settings.php

So there you have it. If you want to change the file system path for the public:// stream wrapper, you will need to edit settings.php.

EDIT: I'm not sure what else is at play here. If you still can't get this working to your client's specifications, you may be able to spoof it with a symbolic link in the file system:

ln -s files sites/default/files

The files would still be hosted in the wrong location, so this is actually no solution. Hopefully somebody else can point you in the right direction. Good luck!


Simple string replacement in views output?

In your custom module, create module_name.views.inc file and add following code.

<?php
use \Drupal\views\ViewExecutable;
use \Drupal\views\Plugin\views\cache\CachePluginBase;

function custom_module_views_post_render(ViewExecutable $view, &$output, CachePluginBase $cache) {
  if ($view->id() == 'VIEW_NAME') {
    $html = \Drupal::service('renderer')->renderRoot($output['#rows']);
    $replace_pairs = array(
      ' am ' => ' a.m. ',
      ' pm ' => ' p.m. ',
    );
    $html =  strtr($html, $replace_pairs);

    $output['#rows'] = $html;
  }
}

Replace VIEW_NAME with your view name and clear drupal cache.


How to clone a entity with its attached fields?

A recent module called Replicate provides an API to easily clone any entity, including of course its fields and references.


How to inline edit node fields in a view

Use the Editable Views module for inline editing

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.


You don't need a module to do that. You can use .tpl files to wrap rows in <entry> tags, fields in their tags and so on. It may be a bit less intuitive and more exhausting at first, but in the long run you will get exactly what you ask for, without compromises modules call for.


change weight of fileds programmaticaly in drupal 7

it seems there are different scope in your form .
Like question and captcha are in different scope. Try to give weight for each scope too.
Then it will work for you. Like

 $elements['questions']['#weight']=50;


Nested OR and AND condition with db_select

In Drupal, conditions are AND by default. It's easier to use objects directly, in my opinion:

$left_condition = new DatabaseCondition('AND');
$left_condition->condition( ... ); // add what you need

$right_condition = new DatabaseCondition('AND');
$right_condition->condition( ... ); // add what you need

$condition = new DatabaseCondition('OR');
$condition->condition($left_condition);
$condition->condition($right_condition);

But you can use db_and() and db_or() if you prefer.


How to upgrade Acquia desktop to php 7.1?

DevDesktop 2 now supports PHP 7.1.

Updated components in the latest version:

  Added option to use PHP 7.1
  MySQL Windows build) updated to 5.6
  Percona (Mac build) updated to 5.6
  Drush updated to 8.1.15
  In addition, the feedback submission function within the app has been fixed.


Purging is the second step, after the field was deleted. field.module should do that automatically for you.

A field config is an entity, you delete it like any other entity:

$field->delete();


you don't need to alter the hook. You can implement the hook. But in your case maybe you want to use theme_menu_link() instead
Customizing menu link output

also check https://api.drupal.org/comment/55298#comment-55298


I don't think you need a custom module for something like this...
This should be as easy as:

Go to Configuration -> System -> Basic Site Settings, get the page URL you have for the 404 page.
Go to Structure -> Block Layout, edit the 'Page Title' block, and exclude it under the Visibility section, by page URL from step1.


Add Additional (Term Reference) Field to repeating Date & Time Field for Locations

If i understand your question correctly, you could fix this quite easily by creating a field collection

The field collection would contain the repeating date field and the term reference field.

When you add the field collection to your event content type, you can select to allow an unlimited amount of values.

I hop this can get you started?

If you should have any problem, just let me know.
I will add some screenshots then. Im posting from mobile phone now...

Good luck!


Images should be deleted automatically during cron runs, if they are not used anymore. Meaning, their file_usage count is 0.


To avoid users can access a user profile, I would implement hook_ENTITY_TYPE_access().
For the search engines, it would be sufficient to check the logged-in user isn't anonymous. For any Drupal user and the search engines, it's sufficient to check the permission the logged-in user has. (I would not hide the user profile to users who have the permission to administer users.)

In the first case, I would use code similar to the following one.

function mymodule_user_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'view' && $entity->id() == USER_ID && $account->isAnonymous()) {
    return AccessResult::forbidden()->cachePerUser();
  }
}

In the second case, I would use code similar to the following one.

function mymodule_user_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'view' && $entity->id() == USER_ID && !$account->hasPermission('administer users')) {
    return AccessResult::forbidden()->cachePerPermissions();
  }
}

(In both the cases, replace USER_ID with the actual user ID of the user profile you need to hide.)

The code checks the value of the operation, and forbids it only when it's view. In this way, the code is simpler, as it doesn't need to check users are trying to edit their own accounts, for example (which I assume it's not an operation you want to forbid).

hook_ENTITY_TYPE_access() is not invoked for pages listing more than one entity, for example a view page. In the case of user accounts, hook_ENTITY_TYPE_access() should be sufficient, but if you want to avoid that user account is listed also in a view output, the alternative is hook_query_TAG_alter() which is more complicated to implement, but it works in every case.


Commerce: What field to join line_item in order to get product price in custom query?

As you can see in the graph from the question you're linking, there's a field that relates the line item with the products, that's not a database field but a Drupal field. This means that there will be a database table for the field data and revisions and you don't want to deal with that in a db_query, you should be using Entity Field Query instead that will know the database tables and fields to use in each case.

I'm guessing you want to get products from the line items you already have, or the order.

I'd get the line items with EntityFieldQuery:

$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'commerce_line_item')
  ->propertyCondition('order_id', <-your-order-id->)
  ->execute();

Now you've got the line items there, wrap them and get the product price:

if (!empty($result['commerce_line_item'])) {
  foreach ($result['commerce_line_item'] as $id => $value) {
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $id);
    $product_wrapper = $line_item_wrapper->commerce_product;
    $price = commerce_price_wrapper_value($product_wrapper, 'commerce_price', TRUE);
  }
}

Also, all this data is exposed to views, so you can create a view instead.


Is there a simple way to add user access on a page level?

Well when you say page in drupal, it comes down to a lot of options. it might be a views page, a panels page, a page created directly with hook_menu().

So options:

If its a panels/views page, you already have permissions options there through UI in those cases.
Node and taxonomy term pages, have contrib modules that does this..Ankit's answer above lists out some.
If the page is a custom page defined bu hook_menu, you can employ '#access_callback' parameter to add a permissions function where you can return TRUE of FALSE based on check.

After restricting access to each page based on roles, these will be respected already when you add their links to the superfish menu.


Unable to login into admin after theme change

To quote you, it sounds like the answer to your question is you needed to:

  ...include <?php print render($page['content']); ?> in my tpl.php file.
  ...the drupal login form wasn't appearing on my site since no default
  region was specified.


Try

1. Search configuration

This module has five main functions.

Alter the appearance of the core node search form
Group content types for more meaningful searching
Restrict search results by the content type. This is a role based restriction.
search results from showing individual items.
Alter the pager limit (aka number search item results per page).

2. Custom Search

  This module alters the default search box in many ways. If you need to
  have options available like in advanced search, but directly in the
  search box, this module is for you.


You can try use hook_query_TAG_alter

...
->addTag('my_module_birtday')

/**
 * Implements hook_query_TAG_alter().
 */
function my_module_query_my_module_birtday_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $today = new DrupalDateTime();
  $today = $today->format("m-d");
  $query->addJoin('LEFT', 'user__field_birthday', 'field_birthday', 'field_birthday.entity_id = base_table.uid');
  $expression = "DATE_FORMAT(field_birthday.field_birthday_value,'%m-%d')";
  $args = [
    ':birthday'=>$today
  ];
  $query->where($expression . '=:birthday', $args);

}


How do I calculate and permanently store a field value with code

I haven't done this myself before, so I cannot give really detailed instructions. I think I would do something like this:

Create a CCK text field in the content type(s) of your choice
Create a custom module and implement hook_form_alter
In your form alter function:

Give your CCK text field a #disabled property and set it to true (this will grey out the field so it cannot be edited)
Check if the field is already populated; if not, set the #default_value to the return value of the code in your question

This means that when Drupal builds the form, your custom module will disable the CCK field and put your content in it if that has not been done before. Because we're just populating a form field, all Drupaly stuff like the 'Display Fields' page will keep working.

I hope that helps.


Private schema is always used for system.files route

I looked into this. Long story short, it's a bug in core: https://www.drupal.org/node/2694129. It will be a bit tricky to fix, since it might require API change and not 100% sure when such a change can actually be made.


What is the twig template name for a node edit form?

You could have a look at this comment. It suggests adding a theme suggestion like this:

  This feels hacky, but it's the best I can come up with. First add this
  code to your admin .theme file (likely a sub-theme of Seven):

function NAMEOFTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
   if ($hook == 'node_edit_form') {
     if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $content_type = $node->bundle();
     }
     else {
       $current_path = \Drupal::service('path.current')->getPath();
       $path_args = explode('/', $current_path);
       $content_type = $path_args[3];
     }
     $suggestions[] = 'node_edit_form__' . $content_type;
   }
 }

  Next, create twig templates in your theme's template directory in the form
  of node-edit-form--NODE-TYPE-SEPARATED-WITH-DASHES.html.twig.


Bootstrap Subtheme undefined variable error for custom node type template

Duplicating node.tpl.php (instead of page.tpl.php) and putting it in /subtheme/templates/node/node--[type].tpl.php fixed my undefined variable error.


How do I migrate from a site using a core version to another one using the same version?

Why don't you just uninstall those modules and remove the configuration you no longer need?

Migration is a complicated task that requires a lot of work.

And to switch the webhost, you just need to copy the files and database, no need to mix those two things together. Clean up your site first and then switch the host. Otherwise you'll never be sure if a problem is caused by the host change or changed configuration


What you call post type is for Drupal a content type, or an entity bundle. The first argument of \Drupal::entityQuery() is the entity type that, in the case of nodes, is node.

The code you need is the following one.

use \Drupal\node\Entity\Node;

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->execute();

$nodes = Node::loadMultiple($nids);

Note I added the condition('status', 1) line, which returns only the published nodes; if you are not interested only in the published nodes, you can leave that line off.

Furthermore, if you are executing the code without showing the result to the currently logged-in user, for example because it runs at cron time, you should disable the access check, and use the following code.

// Put the following line at the beginning of the file containing the code.
use \Drupal\node\Entity\Node;

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'front_page_slider')
  ->condition('status', 1)
  ->accessCheck(FALSE)
  ->execute();

$nodes = Node::loadMultiple($nids);

Differently, you would get only the nodes for which the currently logged-in user has access.
In the example of a hook_cron() implementation, that user is the anonymous user. Without the accessCheck(FALSE) line, the code would get only the published nodes to which anonymous users have access, which could be none, if the user permissions don't allow anonymous users to see nodes.

accessCheck(FALSE) is used by node_access_rebuild(), which contains the following lines. (Read the comment before the code.)

  // Disable access checking since all nodes must be processed even if the
  // user does not have access. And unless the current user has the bypass
  // node access permission, no nodes are accessible since the grants have
  // just been deleted.
  $entity_query->accessCheck(FALSE);


Is it possible to get Entity Connect and Entity Reference View Widget to work together and if so how?

This week a patch for both modules was released that may fix the issue (see Can't get Entity Connect to work with Entity Reference View Widget, which also links to the second patch). As of today (23 Mar 14), the patches still need review.


What Causes DatabaseTransactionOutOfOrderException and how do I fix this?

The DatabaseTransactionOutOfOrderException exception is part of the rollback() method (DatabaseConnection class) and it is thrown when a rollback() resulted in other active transactions being rolled-back instead of rollback to correct earlier savepoint.

You may debug it checking the backtrace when this exception is thrown.

In example defining the following hook:

/**
 * Implements hook_watchdog().
 */
function foo_watchdog($log_entry) {
  if ($log_entry['type'] == 'php' && $log_entry['severity'] <= WATCHDOG_WARNING) {
    // Old school
    // var_dump(debug_backtrace()); // Optionally add: exit();

    // Devel: Log the backtrace into temporary file: drupal_debug.txt
    // Locate via: $ drush eval "echo file_directory_temp() . '/drupal_debug.txt'"
    function_exists('dd') && dd(debug_backtrace());
  }
}

Don't forget to install Devel module (for dd) and clear the cache before testing it.

Then try to reproduce the problem and then check your /tmp/drupal_debug.txt debug file which should contain something like (section _drupal_exception_handler):

[function] => _drupal_exception_handler
[args] => Array
    (
        [0] => DatabaseTransactionOutOfOrderException Object
            (
                [file:protected] => /var/www/includes/database/database.inc
                [line:protected] => 1071
                [trace:Exception:private] => Array
                    (
                        [0] => Array
                            (
                                [file] => /var/www/includes/database/database.inc
                                [line] => 1933
                                [function] => rollback
                                [class] => DatabaseConnection
                            )
                        [1] => Array
                            (
                                [file] => /var/www/sites/all/modules/contrib/commerce/modules/order/includes/commerce_order.controller.inc
                                [line] => 123
                                [function] => rollback
                                [class] => DatabaseTransaction
                            )
                        [2] => Array
                            (
                                [file] => /var/www/sites/all/modules/contrib/commerce/modules/order/commerce_order.module
                                [line] => 734
                                [function] => save
                                [class] => CommerceOrderEntityController
                                [type] => ->

So based on the above example, you know that something goes wrong in commerce_order.module on line 734 during CommerceOrderEntity save.

If it's still not clear, other suggestion is to enable MySQL query logging and check the suspicious queries which are sent.


You can use below code to print login form block

<?php
print(drupal_render(drupal_get_form('user_login_block')));
?>

For login redirect to destination you can use Login Destination module

Project page says

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.


Clear cache doesn't clear the cache tables?

Can I just truncate all cache_... tables?

You should not truncate the "cache_form" table, as it contains the data used from Drupal to validate them; if you delete that table, the form currently being submitted from the user would be invalidated, and the users would need to submit the form again.

There could be some other cache tables that cause a module to act strangely. That is the reason modules that are using extra cache tables (whose name generally starts with "cache_") are supposed to implement hook_flush_cache() to return the cache tables that can be cleared from Drupal, and which is then called with the following code, from drupal_flush_all_caches().

  $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
    cache_clear_all('*', $table, TRUE);
  }

drupal_flush_all_caches() is the function called from system_clear_cache_submit(), the submission form handler called when you click on the "Clear all caches" button, in the performance settings page.

During cron tasks, system_cron() clears the cache using the following code.

  $core = array('cache', 'cache_path', 'cache_filter', 'cache_page', 'cache_form', 'cache_menu');
  $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
  foreach ($cache_tables as $table) {
    cache_clear_all(NULL, $table);
  }

As the first argument of cache_clear_all() is NULL, the code executed in DrupalDatabaseCache::clear() (Drupal 7) is the following one.

if (variable_get('cache_lifetime', 0)) {
  // We store the time in the current user's $user->cache variable which
  // will be saved into the sessions bin by _drupal_session_write(). We then
  // simulate that the cache was flushed for this user by not returning
  // cached data that was cached before the timestamp.
  $user->cache = REQUEST_TIME;

  $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  if ($cache_flush == 0) {
    // This is the first request to clear the cache, start a timer.
    variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
  }
  elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
    // Clear the cache for everyone, cache_lifetime seconds have
    // passed since the first request to clear the cache.
    db_delete($this->bin)
        ->condition('expire', CACHE_PERMANENT, '<>')
        ->condition('expire', REQUEST_TIME, '<')
        ->execute();
    variable_set('cache_flush_' . $this->bin, 0);
  }
}

The code removes only the rows, which are not marked as permanent, and are expired, from the tables returned from hook_flush_caches(), and from various cache tables used from Drupal, including "cache_form." There should not be too much rows in "cache_form"; if that happens, you can reduce the time passed between two consecutive executions of the cron tasks, or execute the following code from a custom module.

cache_clear_all(NULL, 'cache_form');

An alternative is to manually cause the cache to be cleared, using the Devel module, and the menu link it shows.


Uninstall or delete modules when upgrading 6 to 7?

Updated after re-reading your question. :)

The process for completely removing a module is generally:

Backup your site.  The Backup and Migrate module is great
here too.
Disable the module. Admin -> Modules -> Uncheck module ->
save.
Uninstall the module - Goto yoursite.tld/admin/modules/uninstall ->
Check Modules to uninstall -> Click Uninstall
Delete the module - Delete module directory.

Additionally you can find details regarding upgrading from previous versions of Drupal at drupal.org.

Another useful module is the Upgrade Status module.  Listed only for reference.


Drop-down menu only works after clicking into the parent page first

Have you checked the "show as expanded" for the parent menu?

Edit your parent level menu and see if it's checked.

Check it if it's not and check the drop down menu again.


Helpful links for creating multi steps form are https://drupal.stackexchange.com/questions/135/are-there-any-examples-of-setting-up-multistep-forms http://drupal.org/node/717750, and http://drupal.org/project/examples.

I practiced multi step forms by getting the code of the form tutorial from http://drupal.org/project/examples, and added further steps; it works excellently fine for me.


How to wrap content around a display suite region?

To solve this issue you need to reorder your html by flipping columns in your custom layout

If you inspect your html you'll see that group-left renders first then group-right

content

image and location

So you need to have the following structure:

image and location

content

Then add the following style to your css file

.ds-2col-stacked > .group-left {
  float: right;
  width: auto;
}

.ds-2col-stacked > .group-right {
  float: none;
  width: auto;
}


replacing article or basic page image with video

Here is a standard front page. The teaser view. I think this is what you see and where you would like to see the video instead of the image.

This seems like what you would like. On the preview, add the video.

This is the full node view. As you can see, the full text is here.

When you go to the content type admin/structure/types/manage/article/display the default display is the full node view

On the teaser display, /admin/structure/types/manage/article/display/teaser (this is for the article content type). At the top right it says teaser.

Here you need to add the "Embed field". By default it was hidden.

You can move the image to hidden if you want.

And with this you get the image from the second screenshot.

I think that's what you want/need.

Original answer. Updated above based on comments.

If you want to upload, instead of embed, the video module has the option,

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


how to add data to custom content type using node with codeing

The proper method is

  $body_text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.';

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $path = 'content/my-lipsum-' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);

To Add custom fields

// Let's add some CCK/Fields API field. This is pretty similar to the body example
$node->field_custom_name[$node->language][0]['value'] = 'This is a custom field value';
// If your custom field has a format, don't forget to define it here
$node->field_custom_name[$node->language][0]['format'] = 'This is a custom field value';

How to programmatically create/manage node in drupal 7


Let you try with this code. Clear performance cache.

function example_block_info() {
  $blocks['my-block-id'] = array(
    'info' => t('Block Name'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function example_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'my-block-id':
      $block['subject'] = t('Block Name');
      $block['content'] = example_contents();
      break;
  }
  return $block;
}

/**
 * custom html block
 * @return string
 */
function example_contents() {
  return '

      Hello World, this is a example custom Block

  ';
}

For more info see this http://www.summasolutions.net/blogposts/how-create-basic-block-code-new-drupal-7


Create a block with a list of all pages tagged with a taxonomy vocabulary

I want to create a block (based on a view, I am assuming) that will display all of the pages that are tagged with a particular taxonomy vocabulary.

You are absolutely correct that your problem can be solved with a view.

From the way you worded it, though, I sense that you don't understand the difference between nodes and page, and between taxonomy vocabularies and their terms. So let's address that first.

The difference between nodes and pages

A node in Drupal is a single bundle of content. I use the word bundle in the sense that there are multiple pieces of information which all describe the same object. So, for example, the pieces of information "red", "180 horse power", and "manual transmission" could be bundled together to describe a particular car, and then stored as a node in Drupal. Nodes are most commonly used to store information that describes a Web page, which is where the confusion comes from.

A page in Drupal is, well, trickier to explain. Drupal, being a CMS, doesn't really deal with pages so much as it deals with programmatic functions which create pages on demand that are then sent to an user's browser. When you click on a menu link (or, more correctly, when you request a URL) in Drupal, you're not asking for a page, you're actually asking to run a particular programmatic pathway in the gigantic, dynamic program that Drupal really is.

So, we'll be talking about nodes from here on out. We want to create a view of nodes, including links to the URLs which cause Drupal to run in a way that returns the "normal" web pages that we expect and use every day.

The difference between taxonomy vocabularies and taxonomy terms

This is easier to explain. Taxonomy terms are the "words" or "tags" you want to use categorize your nodes. Taxonomy vocabularies are the named containers that we put terms in. So, we could have a taxonomy vocabulary named "Fruit" that contained the terms "Apple", "Tomato", and so on.

Building your view

OK, so your view is going to list nodes. That means you need to set up your view to show "content". I'd show you a picture right here, but apparently I can only link to one.

Once you've got that, set up your view's filter. You want to add some filter criteria, using the "Content: Has taxonomy term" filter. You'll be asked what vocabulary you want this filter to use, so select the vocabulary that contains the terms you're interested in. You can also pick if you use a dropdown menu or an autocomplete text box for the filter to enter the filter's parameter into. I recommend using the dropdown.

Next, you can choose a logical operator and the taxonomy terms on which to apply it. If you want to show only nodes that are tagged with Apples, then you would choose the "Is one of" operator and select only the Apples term.

And there you go. The view is now showing you all content nodes on your site that are tagged with Apples in the vocabulary that Apples is in. You can finish customizing the rest of the view however you like now.


You should print hidden elements:

    <?php print $name; ?>
    <?php print $pass; ?>
    <?php print $submit; ?>
    <?php print $rendered; // HERE HIDDEN ELEMENTS ?>

    Create an Account | Forgot Password


Use cd to go to the right directory, you can later comment it out. If you have multisite, you have sites/default renamed or using multisite you have to go to that directory for the drush to work.


Use the views filter condition OR groups. Also make sure that the taxonomy relationship optional (uncheck Require this relationship).


OpenDialogCommand how to include Buttons in dialog_options

In the $options array the element "buttons" must be a "multiple" array.
For example:

$options = [
  'dialogClass' => 'my-dialog-class',
  'width' => '700px',
  'buttons' => [
    [
      'text' => 'Continue #1',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
    [
      'text' => 'Continue #2',
      'class' => 'btn-primary ok-button',
      'click' => "function() { $(this).dialog('close'); }",
    ],
  ],


I use the Themekey module.  This allows me to give each area a distinct look without even touching any code.  It also integrates with the Print, Revisioning, Organic Groups, and other major modules out-of-the-box.

Some of the things this module enables you to do (from the module page):

  individually-styled channels
  a front-page / "splash" screen
  a date/time-selected Christmas theme
  mobile themes for different auto-detected mobile devices
  special themes for "limited" or "old" browsers
  content, user, or role -specific themes
  indicating your environment (production, staging, testing, sandbox, … )
  testing your redesign safely on a live server


How to disable obligated address fields in Drupal Commerce in checkout?

You need to edit the address field on the Customer profile type.
See admin/config/people/profiles/manage/customer/fields/profile.customer.address
In more recent versions of Commerce this can be found under
admin/config/people/profile-types/manage/customer/fields/profile.customer.address


How do I retrieve a menu using its link?

Try the property link.uri:

$menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['link.uri' => 'internal:' . $path]);


How do I make the exposed filter values available as tokens for text areas

You can show the relevant search term in Text area when you add it to the Header option in Views.

When you tick the Use replacement tokens from the first row option you will see the Replacement patterns tokens available, and below that global replacement tokens.

You can use something like:

<div class="messages messages--status">Your search of {{ name }} has [view:total-rows] result(s). </div>

Although you'll probably want to take care of plurals more intelligently and also use a twig conditional to not show anything if the Exposed form isn't used.


Content Access

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Or you can do by allow permission to allow specific viewer/role


How do I make the select options have a textfield beside them instead of a box?

You can build your own custom Form api element looking at select other example
http://drupal.org/project/select_or_other
and the documentation for it form api element is at http://drupal.org/node/1158654


Twig get value of field in entity reference

For any type you of field get the value directly like you wrote node.field_name.value. But for reference type you can't get the value directly. For reference type you have to write

ex.:

node.field_team_location.entity.name.value

and for uri u can write:  node.field_team_location.entity.uri.value


How to restrict previous date display in custom forms?

Approach to get today's date as Minimum date

Pass the JS options in '#datepicker_options'

$form['oneway']['from_date'] = array(
  '#title' => t('From Date'),
  '#type' => 'date_popup',
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-80:0',
  '#required' => TRUE,
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);

  minDate => 0 (Sets the min date to today's date)

  minDate => -1 (Sets the min date to yesterday's date)

More info: http://api.jqueryui.com/datepicker/#option-minDate


How can I theme profile field forms in an HTML table?

I found out why it didn't work. Because my category name was not ASCII characters and it now works after changing them to ASCII characters with the code above.


Get $form_state backup and migrate filter extended class

From your question, I get you altered the form built from the following function.

/**
 * The quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form($form, &$form_state, $inline = TRUE) {
  backup_migrate_include('profiles', 'destinations', 'sources');
  drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js');

  $form = array();

  // Theme the form if we want it inline.
  if ($inline) {
    $form['#theme'] = 'backup_migrate_ui_manual_quick_backup_form_inline';
  }

  $form['quickbackup'] = array(
    '#type' => 'fieldset',
    "#title" => t("Quick Backup"),
    "#collapsible" => FALSE,
    "#collapsed" => FALSE,
    "#tree" => FALSE,
  );

  $form['quickbackup']['source_id'] = _backup_migrate_get_source_pulldown(variable_get('backup_migrate_source_id', NULL));

  $form['quickbackup']['destination'] = _backup_migrate_get_destination_pulldown('manual backup', variable_get('backup_migrate_destination_id', 'download'), variable_get('backup_migrate_copy_destination_id', ''));

  $profile_options = _backup_migrate_get_profile_form_item_options();
  $form['quickbackup']['profile_id'] = array(
    "#type" => "select",
    "#title" => t("Settings Profile"),
    '#default_value' => variable_get('backup_migrate_profile_id', NULL),
    "#options" => $profile_options,
  );

  $form['quickbackup']['description_enabled'] = array(
    '#type' => 'checkbox',
    "#title" => t("Add a note to the backup"),
  );
  $form['quickbackup']['description'] = array(
    '#type' => 'backup_migrate_dependent',
    '#dependencies' => array(
      'description_enabled' => TRUE,
    ),
  );

  $form['quickbackup']['description']['description'] = array(
    '#type' => 'textarea',
    "#title" => t("Note"),
    '#description' => t('This note will be saved with the backup file and shown on the listing page.'),
  );

  $form['advanced'] = array(
    '#type' => 'markup',
    '#markup' => '
' . t('For more backup options, try the advanced backup page.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/export/advanced'))) . '
',
  );

  $form['quickbackup']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Backup now'),
    '#weight' => 1,
  );

  $form['#validate'] = array('backup_migrate_ui_manual_quick_backup_form_validate');
  $form['#submit'] = array('backup_migrate_ui_manual_quick_backup_form_submit');

  return _backup_migrate_ui_action_form($form, $form_state, 'backup');
}

The only way to pass a value submitted in a form to a hook is to save it into a persistent variable, exactly in the same way a submission handler does.

/**
 * Submit the quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form_submit($form, &$form_state) {
  backup_migrate_include('profiles', 'destinations');
  if (user_access('perform backup') && !empty($form_state['values']['settings'])) {
    // Save the settings for next time.
    variable_set("backup_migrate_source_id", $form_state['values']['source_id']);
    variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
    variable_set("backup_migrate_copy_destination_id", $form_state['values']['copy_destination_id']);
    variable_set("backup_migrate_profile_id", $form_state['values']['profile_id']);

    // Do the backup.
    backup_migrate_ui_manual_backup_perform($form_state['values']['settings']);
  }
  $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH;
}

Your hook_form_alter() implementation needs to do two things:

Add the form element, as you already did
Add a submission handler to $form['#submit'] ($form['#submit'][] = 'mymodule_submission_callback';)


Zen Theme Outputting Term Desc in Node - How To Add To Views

See source of term:

term01

So term's descrtiption here just title attribute.
So for Views you can add field with link (or rewrite output), and put in Title some placeholder name.


How to set different default images in an image field per domain?

Point the image to a .php file instead of a .jpg file, and then write a script to

Find the domain name (https://stackoverflow.com/a/17201254/836995)
Output the appropriate image (https://stackoverflow.com/a/1353867/836995)

Something like this should work (untested):

<?php

$img_file = NULL;

switch ($_SERVER['SERVER_NAME']) {
  case "www.a.com":
    $img_file = "filename_a.jpg";
    break;
  case "www.b.com":
    $img_file = "filename_b.jpg";
    break;
  default:
    break;
}

if (!empty($img_file)) {
  header("Content-type: image/jpeg");
  readfile($img_file);
}

This is a bare minimum script. A more elaborate version here: https://stackoverflow.com/a/9453207/836995 (although you don't need the .htaccess part to do this for only one image).


How can I access individual form elements for theming?

That's a case for the new Formdazzle! module.

  Drupal form theming with less pain

  Theming drupal forms can be difficult and time-consuming. This module
  provides a set of utilities that make form theming easier.

  Currently, this module provides theme suggestions for forms that are
  much more useful than those provided by Drupal core.

  Theme suggestions for all form elements (including buttons)
  Theme suggestions for all form element labels
  All theme suggestions include the form ID and the form element name; e.g. [element-type]--[form-id]--[form-element-name].html.twig

  While Drupal core only provided these two theme suggestions:

input.html.twig
input--textfield.html.twig

  Formdazzle adds the following two theme suggestions to the list:

input--textfield--webform-contact-form.html.twig
input--textfield--webform-contact-form--first-name.html.twig


Gmap Module open info window(bubble) from external link

You can create a function that opens an existing infoWindow:

function triggerPopup(marker) {
  // Get the map using getMap() which needs the maps ID
  var mapID = $('.gmap').attr('id');
  var map = Drupal.gmap.getMap(mapID);
  map = map.map;
  // Get the map's current markers
  var markers = map.markers;
  // Trigger the popup for the marker passed to triggerPopup()
  google.maps.event.trigger(markers[marker], 'click');
};

Then you can use this function with any external link:

$('.your-external-link').click( function(e) {
  e.preventDefault();
  triggerPopup(0);
});

This gives you the basic idea of how you can trigger the popups, you'd need to figure out a way to associate the sidebar links with the markers - this is completely dependent on how you have everything set up.


Pre-select Group Audience for Organic Groups

You can use Field Permission module to not allow a user to see the group field on content type.
Use  hook_form_BASE_FORM_ID_alter() to set a default field value for group field based on current logged in user.

as a sample code (not tested)

function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    global $user;
    $groups = og_get_groups_by_user($user);
      if(is_array($groups)) {
      // This needs to be evaluated to check proper mapping of what field expect to set a default default field value
      $form['group_field_name']['#default'] = $groups[0];
      }
  }
}


Database error after transferring Drupal 6 site

Check that the table isn't corrupted or locked in some way. phpmyadmin should show you this when you view the list of tables in the database.

Try dropping the table and re-importing just that table, not the entire DB.


How to call limited data items per page?

$doors_nids = db_select('node', 'n')

->condition('n.type', 'vivarium_door')

->fields('n', array('nid'))

->orderBy('n.title', 'ASC')

->extend('PagerDefault')->limit(10)

->execute()

->fetchCol();

Hopes this will helps you.


Get field definitions across bundles, including base fields

The more I look, the more confusing and complex this entire architecture looks to me.

The architecture is actually very similar to 7.x, just renamed. 7.x had fields and field instances, 8.x has field storages (= 7.x fields) and fields. Base fields are exposed as both by default, while configurable fields have a separate entity type for each.

Field storages exist per entity type and fields per entity_type/bundle. (in 7.x, fields were global, otherwise it is the same).

To get all field storages of an entity type, you can use \Drupal\Core\Entity\EntityFieldManager::getFieldStorageDefinitions(). Note that a field storage has no label, only the field (and the label can be different per bundle), so you will need to consider all bundles anyway if you don't want to just show a machine name. token and views have helper functions for that, e.g. _token_field_label().

Another useful reference is how the entity selection plugin build the list of fields to sort by: \Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection::buildConfigurationForm()


In Drupal 5 you need to add the suggestion yourself by placing this function in your theme's template.php:

function _phptemplate_variables($hook, $vars = array()) {
  switch ($hook) {
    case 'node':
      $vars['template_files'] = array('node-'. $vars['nid']);
      break;
  }
  return $vars;
}

Once that's done you'll be able to use node-13.tpl.php (note the single dash).

Source: Separate node template for a specific node.


Strict warning: Only variables should be passed by reference

That error happens when a function is expecting a reference as parameter, but it is not getting a reference.

In your case, render() is defined as render(&$element), but node_show() is defined as node_show($node, $message = FALSE), not &node_show($node, $message = FALSE).
The same would be true for drupal_render(), since the function is defined as drupal_render(&$elements).

As explained on Passing by Reference, when a function requires a reference parameter, you can pass to the function:

Variables (for example, a temporary variable containing the result of a function which is not returning a reference)
References returned from functions

Using other expressions, the result is undefined, and it depends from the PHP version.

render(node_show()) produces a fatal error in PHP 5.0.5, a strict standards notice in PHP 5.1.1, and a notice in PHP 7.0.0
render(5) produces a fatal error
render(new DateTime()) produces a notice in PHP 7.0.7


Generally speaking, objects are used for storing structured data and arrays for lists or collections.
It even logically makes more sense. Node is an object with properties; it's not an array of properties.

See this answer posted on SO as an example.


How can I rebuild my installation after attempting to manually update D8 core using D7 instructions?

Manually uploading the 3rd party modules to /modules (atleast the modules i found translation files for in my /sites folder) and restoring my database from backup, allowed me to restart the update process;  so far everything seems to be working again.


It can be done. You have to add a tag to your EFQ, for example:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->addTag('published_at')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

Then you wil have to implement hook_query_tag_alter, in your case:

function mymodule_query_published_at_alter($query){
  // Extend your query with some joins and order statements:
  $query->join('table');
  $query->orderBy('field');
}

The above code is an example, it won't work, but you get the picture :)


Actual code should be:

I have used hook_form_FORM_ID_alter() instead of hook_form_alter().

function test_form_user_profile_form_alter(&$form, &$form_state) {
  // Used dpm() to check for picture array.
  $form['picture']['#title'] = t('Profile Picture');
}

Result:

Note: The capitalization of all the character must be coming from theming layer.

Use dpm() for development:
The structure has changed and the account array no longer holds picture array.


Done using 'Shurly' and 'feeds_tamper_php' module.

After enabling both the modules, add

  Execute PHP Code

plugin to

  Feed Importer's field_url

.

Execute the following code:

$shortUrl = shurly_shorten($field);
return $shortUrl['shortUrl'];


How can I use a media field in a custom form?

I found the answer to create the media autocomplete field like below.

// $id is your media ID.
$media = \Drupal\media_entity\Entity\Media::load($id);

$form['upload_doc'] = [
  '#type'          => 'entity_autocomplete',
  '#target_type'   => 'media',
  '#default_value' => $media,
];


Create node--YOOR_TYPE_NAME.tpl.php and print_r($node) object, find what you need and place it on write tag style


There are two questions:

1.) goal: open login form in bootsrap modal.

In your code by redirecting to a new path the page will reload, and not display a modal login.

But you don't need a new path, your form is already there. It is in the block content and you should be able to place {{ content }} in the bootstrap modal dialog like this.

block--userlogin.html.twig:

                <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

                {{ content }}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

2.) ajaxifing the login (not reloading after submit)

For this there is some work to do, you can see this in the D7 module:

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

For D8 you need to code something similar.


Why do users with permission to post commenst get "You do not have permission to post a comment"?

Go to the admin/people/permission check for comment section in permission page where you can see skip comment approval you need to give appropriate permission for the user.

Like below screenshot.


Hook the language switcher and change the URLs it redirects to in Drupal 7

I have discovered how to do it.

function MYTEMPLATE_language_switch_links_alter(array &$links, $type, $path) {

 $extract_parameters_URL = explode("/", $_SERVER['REQUEST_URI']);

 $code_altered_url = process_URL_extracts($extract_parameters_URL);

 foreach ($links as $langcode => $link) {

    $links[$langcode]['href'] = $code_altered_url ;

 } // foreach


How to programmatically truncate table in Drupal8

Sure, the function still exists: https://api.drupal.org/api/drupal/core%21includes%21database.inc/function/db_truncate/8.5.x.

It's deprecated, though, with the advice:

  Instead, get a database connection injected into your service from the container and call truncate() on it. For example, $injected_database->truncate($table, $options);

If you're not in a context where injection is possible, get it from \Drupal:

\Drupal::database()->truncate('foo')->execute();


Take a look at the CCK multi group options, which are only a part of CCK 3.0+. This functionality allows you to combine multiple base fields into one field grouping. See http://drupal.org/node/119102 for the long history on how this came about.

I actually can't find good documentation on using it, as CCK 3.0 is still only in Alpha, so unfortunately you'll just have to play around with it some.

The other option is to write your own CCK field type, in which there is no issue creating multiple inputs for one field. The upshot is that you can definitely achieve this using your own custom field, the downsides are you are writing custom code (which is nice to avoid) and it's not as flexible as the multigroup options built into CCK 3.0


Administration views change filter on my content type fields

Go to admin/structure/views/view/admin_views_node and add a filter criteria on the field "last name". While adding the field check "Expose this filter" and you will be able to search on last name


Add Rating Widget to a custom full content layout in drupal 7

You can use below function to print rate field

rate_embed(&$node, $machine_name, $mode = RATE_FULL);

Like print rate_embed($node, 'rate', $mode = RATE_FULL);


Adding confirm email field to entityform

You can use CCK Match to achieve this goal.


The results within the page results do not lead to the nodes

Yes, you can change the link settings from within the field settings on the view (or, if you are rendering nodes, you will have to change it in the display settings or template files if you are showing teasers using default templates).

Once you've edited your view, you might consider using the Rabbit Hole module to further deal with unwanted Node views.


How to set Ajax callback from jquery on node edit form?

Listening to your suggestion I did this.
Now this is my_module.module file:

    /**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_node_test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['field_test1']['widget']['#ajax'] = [
    'event' => 'change',
    'callback' => 'my_module_myAjaxCallback',
    'disable-refocus' => FALSE,
    // Or TRUE to prevent re-focusing on the triggering element.
    'progress' => [
      'type' => 'throbber',
      'message' => t('Verifying entry...'),
    ]
  ];

  $form['#attached']['library'][] = 'my_module/trytest'; //form.js
}

/**
 * An Ajax callback.
 */
function my_module_myAjaxCallback(array &$form, FormStateInterface $form_state) {
  $db = new mysqli('host', 'user', 'password', "db");
  mysqli_set_charset($db, "UTF8");
  // Check connection
  if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
  }
  else{
    echo "Connected successfully";
  }

  if(\Drupal::request()->request->get('field_test1')){
    $out = array();
    $sql = "SELECT * FROM `car_type`";
    $res = $db->query($sql) or die(mysqli_error($db));
    while($row = mysqli_fetch_object($res)){
      $out[] = array(
        'id' => $row->id_car_type,
        'name' => $row->name
      );
    }
    echo json_encode($out);
  }
}

Obviously it doesn't work because I don't know if it is correct to insert the data of the connection to the DB in this file and even if the code to return the query result to the file form.js. is correct.


Dynamically grow menu based on terms in vocabulary?

The Taxonomy Menu module will be able to handle that...

  Transform any of your taxonomy vocabularies into existing menus easily!

  Features

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

The module page also links to a tutorial called How to add a block menu of tags (or other taxonomy terms) on a Drupal site in conjunction with the Menu Block module in case you need that functionality.