Create database fields to an existing table when installing a module I'm new to drupal and I need some help.

I created a new module with name user_extra. Which create necessery table when Installing the module.

But I also need to insert some database field in 'users_field_data' table ('user_extra_id' and 'user_office')

In baseFieldDefinitions I wrote all necessery database table fields for user_extra table.

 public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    // Standard field, used as a unique if primary index.
    $fields['id'] = BaseFieldDefinition::create('integer')
        ->setLabel(t('Unit ID'))
        ->setDescription(t('The unit ID.'))
        ->setReadOnly(TRUE)
        ->setSetting('unsigned', TRUE);

    $fields['uuid'] = BaseFieldDefinition::create('uuid')
        ->setLabel(t('UUID'))
        ->setDescription(t('The unit UUID.'))
        ->setReadOnly(TRUE);
        .
        .
        .
    $fields['user_info'] = BaseFieldDefinition::create('string')
        ->setLabel(t('User Info'))
        ->setDescription(t("The User Info"))
        ->setSetting('max_length', 255)
        ->setDisplayOptions('form', array(
          'type' => 'string_textfield',
          'weight' => 10,
        ))
        ->setDisplayConfigurable('form', TRUE);
     return $fields;
     }

When I install the module it inserts all values that I define in baseFieldDefinitions.

But I also need to create 'user_extra_id' and 'user_office' in 'users_field_data' table with setDisplayOptions and setDisplayConfigurable options.

This is the commenting that I made in entity file

/**
 * @ContentEntityType(
 *   id = "user_extra",
 *   label = @Translation("user extra"),
 *   handlers = {
 *     "storage" = "Drupal\user_extra\UserextraStorage",
 *     "storage_schema" = "Drupal\user_extra\UserextraStorageSchema",
 *     "access" = "Drupal\user_extra\UserextraAccessControlHandler",
 *     "list_builder" = "Drupal\user_extra\UserextraListBuilder",
 *     "view_builder" = "Drupal\user_extra\UserextraViewBuilder",
 *     "views_data" = "Drupal\user_extra\UserextraViewsData",
 *     "form" = {
 *       "default" = "Drupal\user_extra\Form\UserextraForm",
 *       "add" = "Drupal\user_extra\Form\UserextraAddForm",
 *       "edit" = "Drupal\user_extra\Form\UserextraEditForm",
 *       "delete" = "Drupal\user_extra\Form\UserextraDeleteForm",
 *     }
 *   },
 *   admin_permission = "administer user_extra",
 *   base_table = "user_extra",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *   },
 *   links = {
 *     "canonical" = "/admin/user_extra/{user_extra}",
 *     "add-form" = "/admin/user_extra/add",
 *     "delete-form" = "/admin/user_extra/{user_extra}/delete",
 *     "overview-form" = "/admin/user_extra/${user_extra}/overview",
 *     "edit-form" = "/admin/user_extra/{user_extra}",
 *     "collection" = "/admin/user_extra",
 *     "children" = "/admin/user_extra/{user_extra}/children",
 *   },
 * )
 */

There are a couple of inconsistencies with the question and code so I am not sure whether or not this can be accepted as an answer to the strict question "How do I create database fields to an existing table when installing a module".

"user_extra" is defined as a new content entity. What this means is that it is a fundamental new thing that is not related to a Drupal User entity nor the User entity's storage. This might be a similar use case to Profile2.
Modifying base field definition is probably a bit too heavy/complex for adding in the "user_office" and "user_extra_id" data that your site needs. The "Drupal Way" would be to add a "Bundle Field" to the entity.

This could be done as a site builder in the user interface (See Configuration > People), programmatically or providing YAML in config/install (Berdir). See field.storage.user.user_picture.yml.
Adding many fields to the User entity may have a performance impact, which could be solved by using a module such as Profile2 to only load that information on certain pages.


Disallow specific combination of checkbox selections in term reference field? I have a term reference field in the format of checkboxes. However, I'd like to disallow certain combinations of checkboxes. The options are:

[]None
[]Food
[]Drinks

The "None" option is not the default none, but a taxonomy term that is actually stored in the database. I'm wondering how to allow two selections, but to disallow the selection of both "Food" and "None", or "Drinks" and "None", since in practice that really doesn't make any sense. Any suggestions?

Take a look at the Field Validation module, it attaches a UI where you can set custom validation rules for each field on a content type.

I am not sure whether any of the inbuilt options will work for what you want, but you can select the PHP code option and write the rules you require. There is a short reference for the PHP validator here: http://drupal.org/node/1537028


How to correctly access entity elements in a twig template I have an array of entities that i would like to render in a list.

$ids = \Drupal::entityQuery('chemical')
  ->condition('tid', $tid)
  ->execute();
$controller = \Drupal::entityManager()->getStorage('chemical');
$entities = $controller->loadMultiple($ids);

$chemicals = [];
foreach ($entities as $entity){
  $chemicals[] = ['id' => $entity->id(), 'label' => $entity->label()];
}

$output[] = [
  '#theme' => 'chemical_taxonomy',
  '#chemicals' => $chemicals,
];
return $output;

The twig template then creates the unordered list of URLs using the array of {{ chemicals.label }} and {{ chemicals.id }}. However, I should be able to just pass $entities to the template instead of extracting the id and label and building a new array, shouldn't I?

If I replace '#chemicals' => $chemicals with '#chemicals' => $entities I receive an error:

Uncaught PHP Exception Exception: "Object of type Drupal\\Core\\Field\\FieldItemList cannot be printed." at /var/www/Drupal_Sites/console/core/lib/Drupal/Core/Template/TwigExtension.php line 443,

As the exception explains, you tried to print an object that is not renderable and cannot be converted to a string. In this case it was Drupal\Core\Field\FieldItemList which is the object returned by drupal entities when you ask for a field ({{ entity.id }} / {{ entity.label }}).

To get the actual value you need to call to methods of your entity (the actual value of the fields is protected from outside access).

The long way:

{{ entity.get('id').get(0).get('value').getValue() }}

The above is the actual path you need to take to get from the entity object to the value of the id field.

However drupal supplies shortcuts through what is known as magic properties.
The short way

{{ entity.id.value }}


How do I use the value of a JavaScript variable in a module? I need to use the value of a JavaScript variable in a module.
For example, I am getting a city = 'delhi' in a JavaScript file, and I need to use this value in a module showing a form.

You could send that value to a callback function in your .module file using AJAX, an example to do that stuff in forms see that tutorial Ajaxify form fields

And you could send any value to js variable see sending-a-javascript-variable-to-drupal


making user profile available for anonymous user viewing I am creating a views to list the users in that I want anyone to be able to access the user's profile node. However,there doesnt seem to have any such options. Any suggestion?

I was having this same problem and was able to solve it by going to EDIT VIEW > ACCESS (under Page Settings) > PERMISSION and changing it to VIEW COMMENTS. Then in the POEPLE > PERMISSIONS area I made sure that anonymous users were permitted to view comments.


Webform: how to wrap each form field with a div? Due to a design request, I need to add a DIV around each textfield/select field in my webform.

Since a webform is, both, a form and a node, I'm struggling to figure out how to do that.

In a normal form, I would use the hook_form_alter() and use the #prefix and #suffix attributes to add extra markup, but when printing out the webform in the hook to see the structure of the fields I can't see how to target each field.

Any help will be greatly appreciated!

Thanks.

You're correct in thinking to use the #prefix and #suffix attributes.  Webform components are stored in the 'submitted' part of the form array.  To add a surrounding div to each textfield and select, you can do the following in hook_form_alter:

if ($form_id == 'webform_client_my_form_id') {
  foreach($form['submitted'] as &$field) {
    if($field['#type'] == 'textfield' || $field['#type'] == 'select') {
        $field['#prefix'] = '
';
        $field['#suffix'] = '
';
    }
  }
}

To find out your form id, you can add a watchdog statement:

watchdog('My Module', "Form Id: $form_id");

Then check the dblog at /admin/reports/dblog.

This link may also be helpful: https://drupal.org/node/1558246


Default values in tableselect I have a custom module that, among other things, shows the user of a certain role. I want some of the users in this tableselect, do already be checked and I have and arry with these uids.

Now, how do I chedk default values in my list? See code below:

$companies = 'mail1@test.org,test2@test.org';
$uids = array();
$comp_mail = explode(',', $companies);
foreach ($comp_mail as $mail) {
    $uids[] = db_query("SELECT uid FROM {users} WHERE mail = '$mail'")->fetchField();
}

$form['msg']['accounts'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => in_array($uids),
    '#empty' => 'no companies',
);

in_array() returns a boolean (and takes two arguments), whereas Drupal is expecting an array to be passed for the default value.

The default value array needs to be keyed by the same key used for the options array, so in this case uid. The value for each array element should be TRUE or FALSE, to mark the element as checked or unchecked respectively.

$uids[1] = TRUE;
$uids[2] = FALSE;
$uids[3] = TRUE;
// etc.

$form['msg']['accounts'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#default_value' => $uids,
  '#empty' => 'no companies',
);

EDIT

I haven't tested the following, but since your $uids array contains only the array keys you want checked, and a positive number is automatically cast to a boolean TRUE in PHP, you might get away converting your array in one step:

$uids = drupal_map_assoc($uids);


How to choose appropriate token for URL path alias pattern display in URL? Using Drupal 7 + PathAuto + Token + Entity API

Having a really hard time setting url aliases...for nice URLs.
I have it set up like this:

[node:field-root:parents]/[node:field-root:name]/[node:title]

But it's not what I want, I want every term displayed separately in the URL, now it's like this:

 ab/c/d/item

but I want:

 a/b/c/d/item

What token should I use to get this done, tried tons of combinations and can't get it working...

I see the explanations besides the token, but still, it's too complex and I can't wrap my head around this to get it working.

I saw a page that asks users to share their pattern recipes (https://www.drupal.org/node/124462), but there is nothing in there...if I could see a list of patterns and then resulting ULR it would be great.

Otherwise, how do I know what token to choose?

Picture below is hierarchy, the URL I want is:

 mysite . com /destinations/northern-laos/outodmxay/history

This is the answer:

 [node:field-category:parents:join-path]/[node:field-category]/[node:title]


How can I list all Twig functions and filters with their description? I want a list of all available Twig filters and functions and for each one of them I need to have a description of the function/filter so the user can see what functions and filters are available and how to use them in templates.

I know how to get the list of functions and filters(How to get all filters and functions available in Twig templates?) but I don't know how to get their descriptions.

I don't know how to find out in which file the filter/function resides so I can parse it for the description of the function.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21TwigExtension.php/class/TwigExtension/8 Twig functions have no descriptions. You can run getCallable on a twig function/filter object and then do $reflection = new \ReflectionFunction($callable); $doxygen = $reflection->getDocComment() to get the doxygen which is the closest to "description".


Applied Image Styles Cause Failed Image Render I'm using Aquia Dev on Windows 10 for a local installation and after the latest Drupal 8 update (8.2 to 8.3), applying image styles to content now causes my images to fail to render.

Checking debug and the directory, the paths site/MY-SITE/files/styles/MY-STYLES are correct and the images are there, but for whatever reason Drupal can't pull the images. The alt text is displayed instead. Image-styles that were applied to items before the update still render correctly, but changing the styles on the correctly rendering images thereafter again breaks them.

Most of the information I have found is geared toward changing "775" ownership on a Unix platform. I can't figure out what that means and translate it to a Windows set up.

These aren't private files, right? There is an open issue for something that sounds a lot like this. We applied patch #34 and it resolved the problem for us.


How to create temporary select field? I added a field:

$form['field_brand_selector']['#type'] = "select";
$form['field_brand_selector']['#title'] = "Brand";
$form['field_brand_selector']['#required'] = false;

This field is populated dynamically using Javascript. However, if I try to save the form, I get:

Illegal choice 49124 in Brand element.

I suspect that this is because I don't have this:

$form['field_brand_selector']['#options'] = $options;

So Drupal doesn't know which values are allowed for this Dropdown Selector. But seeing as this dropdown selector is not actually a field that must be saved, is there a way to "ignore" it's submission when I press save, so that I don't get the illegal Brand element error?

Probably a hack, but this is how I solved it:

$form['field_brand_selector'] = array(
    '#type' => 'inline_template',
    '#template' => '{{ somecontent | raw }}',
    '#context' => [ 'somecontent' =>
    '
        <label for="edit-field-brand-selector">Brand</label>
        <select class="" id="edit-field-brand-selector" name="field_brand_selector" readonly="readonly"></select>
    '],
    '#weight' => 8,
);

This way Drupal doesn't validate the field I added.


SQL error for anonymous users on Views Nivo Slider block I have created a slideshow using the Views Nivo Slider module and added it as a block to the home page of my site (running Drupal 6). Everything works great, but for anonymous users I am getting 2 MySQL errors and the block does not display.

You can see the error message by going here: http://staging.thespanishacademy.com

Naturally, I suspect permissions issues but have triple checked everything, flushed all caches, rebuilt node permissions to no avail.

Any help would be appreciated. I'm also including the exact error message below for historical purposes.

warning: Invalid argument supplied for foreach() in /home/spanish/public_html/staging/sites/all/modules/views/plugins/views_plugin_query_default.inc on line 924.

warning: Invalid argument supplied for foreach() in /home/spanish/public_html/staging/sites/all/modules/views/plugins/views_plugin_query_default.inc on line 1000.

warning: Invalid argument supplied for foreach() in /home/spanish/public_html/staging/sites/all/modules/views/plugins/views_plugin_query_default.inc on line 924.

user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node node INNER JOIN node_access na ON na.nid = node.nid WHERE (na.grant' at line 2 query: db_query /* Anonymous : db_query / SELECT COUNT() FROM (SELECT DISTINCT FROM node node INNER JOIN node_access na ON na.nid = node.nid WHERE (na.grant_view >= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'content_access_author') OR (na.gid = 1 AND na.realm = 'content_access_rid'))) AND ( (node.status = 1) AND (node.type in ('home_page_slideshow')) )) count_alias in /home/spanish/public_html/staging/sites/all/modules/views/plugins/views_plugin_pager.inc on line 141.

user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node node INNER JOIN node_access na ON na.nid = node.nid WHERE (na.grant' at line 2 query: db_query_range /* Anonymous : db_query_range */ SELECT DISTINCT FROM node node INNER JOIN node_access na ON na.nid = node.nid WHERE (na.grant_view >= 1 AND ((na.gid = 0 AND na.realm = 'all') OR (na.gid = 0 AND na.realm = 'content_access_author') OR (na.gid = 1 AND na.realm = 'content_access_rid'))) AND ( (node.status = 1) AND (node.type in ('home_page_slideshow')) ) LIMIT 0, 5 in /home/spanish/public_html/staging/sites/all/modules/views/plugins/views_plugin_query_default.inc on line 1150.

When you enable content_permissions together with the rest of cck submodules, the fields you created aren't visible to anonymous users per default. Due to this, views doesn't add any columns to the select statement and you end up with a faulty select. So the solution is to either setup some permissions or switch content_permissions off.
In case you need to setup permissions on fields, i think Field Permissions is nicer - you can select the fields that will be affected, by default all is shown.


Problems with theming a grid I am having problems trying to control the layout and fields together in a grid style of a view.
On the internet I saw several tutorials about how to theme views, and they suggest using functions in template.php, or using view template files. I cannot find a tutorial that helps me.

Specifically, when I use a template file, I cannot control the disposition of fields (controlling the disposition of each field; controlling the fields altogether; adding conditionals; adding classes; trying to use "views-view--," "views-view-field--," "views-view-fields--," or "views-view-grid--"), and when I use a function in template.php, I cannot get the variables/values of fields.

I must say that I know how to include a custom design using the Views module interface, to control the design per fields (or controling all fields of each item, if I include the design and fields in the last field). But I want to do this using some external way to custom display in a centralized way (also to not allow to change the design from the web interface, and to have the control in a files, not in the database).

When I say a centralized way, I mean, using a file or files to control the disposition of each field, control fields together, add conditionals, add classes, add functions, (such as a theme in Drupal).

I am using Drupal 6 and Views 2.

in views-view-grid--viewname.tpl.php, with print_r($variables), you will find the whole values in the 'view' array (is a very huge output, so I recomend only pull 1 item in this test).

here you will discover that 'result' carry the stdClass Object with the fields of views (not it all, seems that the images are not there), to print this you can use:

print_r($variables['view']->result);

with the id of the values, you can use these values for example, show a node title:

echo $variables['view']->result[$i]->node_title;

or you can use the id of the node to get, for example, images from nodes (seems that the images are not in result).

$nIdItem = $variables['view']->result[$i]->nid;
$node = node_load($nIdItem);
echo "<img src='/".$node->field_image[0]['filepath']."'>";

so with this way is possible to control each field, set of fields, and/or add conditions, functions.

I do not know the performance or security implications of using this way, this may be a new question.


How to query solr server from php in Drupal 8 How do you query solr server from php in Drupal 8?

I have installed search_api, search_api_solr and search_api_attachments.  Also have Solr v.8.4.0 installed.

I installed php SolrClient for Centos 7 following this guidance: https://stackoverflow.com/questions/22959330/fatal-error-class-solrclient-not-found
, but I still get "Class 'SolrClient' not found" every time I run

new SolrClient($options);

I have located documentation on querying Solr from php in Drupal 7 (apachesolr_get_solr()) but nothing in Drupal 8.

I managed to fix the problems with SolrClient install: https://stackoverflow.com/questions/41052999/php-warning-unable-to-load-dynamic-library-usr-lib64-php-modules-solr-so-und%C2%A0

This is how I can now query the solr server from php (right out of php SolrClient manual):

$options = array
(
    'hostname' => 'localhost',
    'port'     => '8983',
    'path'     => 'solr/sbn01'
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('*file/10*');

$query->setStart(0);

$query->setRows(50);

$query->addField('id');
$query->addField('its_fid');
$query->addField('ss_uri');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);


Admin Config page for my module is empty I created a module (namely, "casabaca_s3s") and set a configure entry in the casabaca_s3s.info file:

configure = admin/config/content/casabaca_s3s

Now my "Configure" appears in the module.

Then, i added, in my casabaca_s3s.module file, the following code:

And my hook:

function casabaca_s3s_menu()
{
    return array(
        'admin/config/content/casabaca_s3s' => array(
            'title' => 'Casabaca',
            'description' => 'Configuración de Casabaca',
            'page_callback' => 'drupal_get_form',
            'page_arguments' => array('casabaca_s3s_admin'),
            'access arguments' => array('administer casabaca_s3s pages'),
            'type' => MENU_NORMAL_ITEM,
        ),
    );
}

And my handler for the hook:

function casabaca_s3s_admin() {
    return system_settings_form(array(
        'casabaca_s3s_modelcosts' => array(
            '#type' => 'managed_file',
            '#title' => t('Modelos y kilometrajes'),
            '#description' => t("Archivo .csv con el contenido de la tabla de precios según modelo y kilometraje"),
            '#required' => true,
            '#upload_validators' => array(
                'file_validate_extensions' => array(0 => 'csv'),
                'file_validate_size' => array(32*1024*1024),
            ),
        ),
        'casabaca_s3s_extracosts' => array(
            '#type' => 'managed_file',
            '#title' => t('Costos de servicios adicionales'),
            '#description' => t("Archivo .csv con el contenido de la tabla de precios de servicios extra"),
            '#required' => true,
            '#upload_validators' => array(
                'file_validate_extensions' => array(0 => 'csv'),
                'file_validate_size' => array(32*1024*1024),
            ),
        ),
    ));
}

Problem: When I click "Configure" button in module listing (the one with the gear), it redirects to admin/config/content/casabaca_s3s, but that page is empty, showing standard message: "No tiene ningún elemento administrativo." (trans. You have no administrative elements). What am I missing to display the form?

'page_callback' => 'drupal_get_form',
'page_arguments' => array('casabaca_s3s_admin'),

needs to be

'page callback' => 'drupal_get_form',
'page arguments' => array('casabaca_s3s_admin'),

(underscores removed from array keys)


Is it possible to run a View from code in a cron hook? I'm writing a queued cron process, and need to retrieve some information while doing this. Rather than fiddling around with DB queries, it seemed to me much easier to create a View and then execute it in the code. Which I did (and by the way, the View itself works fine and returns the expected result). Trouble is, although it seems to run fine, it returns no result.

I've tried two different ways of doing this, but both are the same: the result is empty.

First was very simple:

if (!isset($node->og_group_ref)) {
  $regions = views_get_view_result('og_regions');
  }

That left $regions empty, so I tried this, with no better result:

if (!isset($node->og_group_ref)) {
  $view = views_get_view('og_regions');
  $view->execute();
  $regions = $view->result;
  }

Problem sorted. It was all down to permissions, and loading user 1 as described in the blog linked to by my previous comment allowed the View to work as expected.


Drupal 7 Display legal module fieldset on user/% instead of user/%/edit How can I display the legal module fieldset on /user/% instead of /user/%/edit? Please note my /user/% is a view page so I can use views template schema.

I just took a look inside the code of Legal module, what you describe is not possible by design, as of legal is hooking in existing forms:

legale.module line 223

function legal_form_user_profile_form_alter(&$form, $form_state) {

legale.module line 223

function legal_form_user_register_form_alter(&$form, &$form_state) {

You might want to try out building a custom user-page form and hide the unwanted elements from profile form.

For reference in how to to that see this answer.

I also think you will need to go a bit further than views only and use Panels to add multiple views on one page.


Load file of content by weight Let's suppose I have a simple content type with title, body and file fields, and file field is multi value. I create a piece of content and upload some file in my field. Finally my content is something like

title : my title
body  : somebody text come in body

file  :

file1
file2
file3

My question

I can change the order of files in node edit by drag them up or down, I want to know how I can load a file programmatically by its weight. I mean I want to upload a file that is shown first or second in node edit mode. How can I upload file form node programmatically, ordering by weight?

When you change the order, the changes are saved as the delta in the database. For example if your field was called file you would access $node->field_file[$node->language][delta]. In your example above, the second file would be $node->field_file[$node->language][1] as the first file would be 0


Redirect to 404 or 403? When you set the 404/403 error pages to nodes with a path, how then can you have Drupal go to the 404 path or 403 path instead of outputting the message on the page?

For example, if I type in www.mydomain.com/skdjhfjsdhfjsh, it shows the custom 404 text from my node. But, is there a way to make Drupal send the user to www.mydomain.com/404, so I can use Contexts/Blocks with in the content area of this specific page?

I agree that redirecting a 404 page is a bad idea.  One way customize error pages is the blocks404 module.


Drush cache-rebuild breaking menus We have had an issue with an expanding menu on a drupal 8 website that stops working when the command

drush cache-rebuild

is used.

MORE INFO ON ERROR:

When triggered, the error causes menus set to expand some sub-menu portion when active to stop expanding. That is to say the menu stops expanding at all, just stays in the inactive state.

The menus where this occurred were generated with the core menu module.

Logging into the site and using the clear all found in admin->config->performance->"clear all caches" fixes the issue.

Can anyone suggest an alternative drush/command line command we can use or how we can fix this problem?

drush clear-cache

does not seem to fix the issue.

I also tried executing as apache:

sudo -u www-data drush cache-rebuild

this also broke my menus.

What exactly is the difference between the UI cache clear and the drush one?

MORE INFO

Ok after some digging - and please correct me if I am wrong here - it seems that when Drush rebuilds all caches it invokes:

drupal_rebuild(ClassLoader $class_loader, Request $request)

which is found in utility.inc, see drush github repo, while the admin command in Drupal calls:

drupal_flush_all_caches()

found in common.inc, see drupal docs.

I have always been under the impression drush either called the same cache function as the internal performance button or at least they had the same behaviour, but they seem not to - at least in regards to my issue with the menu.

Can anyone suggest a way to have drush - or some other tool - invoke drupal_flush_all_caches()?

A further question, is the behaviour I am observing intended or should drush cache-rebuild work the same as drupal_flush_all_caches()?

MORE INFO AGAIN

Further experiments lead me to believe that it is specifically the clearing of the views cache that is causing some expanding menus to break.

drush cache-clear views

Will also trigger the behaviour. Again, clearing with the drupal_flush_all_caches() via the performance admin page fixes the issue.

EDIT: I take it back. The problem has started again in drush 8.1.8 when Drush cr is used in a script - we have it in a back up script to reduce the size of the DB before pilling a copy of it - the application of the is-Active tag is getting broken on menu elements and any styling - say turning on or off visibility to expand the menu - seems to to totally break.

Manually clearing the cache through the UI fixes the issue but is not ideal

Drush 8.1.8 seems to have fixed the problem. I have looked through the change log though and cannot see what got changed in regards to the cache-rebuild that would fix the problem but it seems to have gone away so...


How to unset $page['#attached']['html_head_link'] from head? Help me with this question please: how to unset html_head_link from pages in my Drupal 8.0.3 site.

I mean, delete this META:

<link rel="delete-form" href="/node/{id}/delete" />
<link rel="edit-form" href="/node/{id}/edit" />
<link rel="version-history" href="/node/{id}/revisions" />
<link rel="revision" href="/mypage" />

I try this in MYTHEME.theme file:

function MYTHEME_page_attachments_alter(array &$page) {
  foreach ($page['#attached']['html_head_link'] as $key => $value) {
    unset($page['#attached']['html_head_link'][$key]);
  }
}

But this do nothing...

OK. I found fresh module for this trouble. Module's author use hook_entity_view_alter() for implements head render. Check out their git respository to download the module and get the full code with comments.


Filter a view by a field on a referenced entity Sorry to be yet another question about entry reference relationships in views, but I can't find the answer in pre-existing questions.

Given:

the content type "page" has an entity reference field "artref" that references multiple nodes of the content type "article"
the content type "article" has a boolean field "fishy"

How do I create a view that shows all pages which reference at least one article where fishy is checked.

I understand that here are 4 relevant settings:

the basic entity bundle (pages or articles) selected for the view
the relationship type ("content referenced from" or "content using")
"require this relationship" setting
Aggregation, especially if "distinct" is a possibility

All advice much appreciated

I figured it out. Configure in this sequence:

Show: "content" of type "page"
Relationships: "Content referenced from art_ref"
Use Aggregation: Yes
Add filter criteria: fishy, Aggregation: "group results together", relationship: "art_ref:content", operator: "is equal to" "1"


how can I use drush in ftp host Is this possible to  use drush in  dedicated host that only I can access cpanel?
If yes how can I do it?


Registration module, Rules, how to add the node-title of the registrated entity to notification mail I have a registration form built with registration module to enable users to reserve tickets for events. Now i want to send notification mails to the site administrators to inform them about new registrations. The mails are sent via Rules "After saving a new registration" and i have all fields included except the node-title... the only "hints" of this field are the tokens [registration:registration-id] and [registration:url]. Can i transform these to human-readable items somehow? Is there a way to connect the registration-form to the specific node?

Figured it out. I had to add another action before the mail-action: "Fetch entity by id". Set the type to "Node" and the data selector to "registration:entity-id". After this all the node-specific fields were available for the mail-action.


How to delete a Feature? I created a feature module in site-1.

Then I instaled the feature module in site-2. This features creates a new content type and enable a module. Then I got the new content type and the module enabled.

So far so good.

Now I disabled and uninstall de feature module(drush). I expected the content type to be deleted and the module to be disabled, I mean the content type and the module that the feature created.

But they are still there...

How do I disable a feature and remove all the things that the feature created?

UPDATE: Steps I did to disable the feature:

1) drush dis myFeatureModule

2) drush pm-uninstall myFeatureModule

3) in admin/structure/features the feature myFeatureModuleis disabled

4) The delete button for the content type (created by this feature) in admin/structure/types is missing...

The first thing you will want to do is disable (and uninstall) the feature module.  That doesn't always remove everything the module initially created.  Once that feature module is uninstalled however you can go in and manually delete the content type and anything else that was left on the site.

Some additional detail can be found at this other question.  It provides an example of how the feature module can add an uninstall hook to unlock the content type. Looking at the query used in that example you should be able to run the query manually and unlock the offending content type.


how do you alter queries for node/# to select entity-referenced node titles instead of just target_id? I am using Drupal 7 Services and the generic call of services/node/#. Unfortunately that only gives me the target_id as a property of every field with type entity reference; and my interface does need the node title at the least.

I have...

function  HOOK_query_alter(QueryAlterableInterface $query) {
    if ($query->hasTag('NODE RETRIEVE')) { // WHAT TAG SHOULD I USE?
        // ..TO ONLY ALTER (service)/NODE/# QUERIES?
    }
    $fields =& $query->getFields();
    ... // AND HOW DO I ALTER TO GET REFERENCED FIELD NODE TITLES?
}

All said, I do realize I might be able to use node_load and loop over the results to run subsequent queries for this data, but that seems kind of expensive, unless the resulting hook_alter_query would be too complicated. Please say so if you feel that's most likely the case.

I believe @Clive was going in this direction here, but I wasn't clear that the Services does in fact invoke Hook_node_load($nodes, $types) when using the retrieve methods at services/node/#. I suppose I was avoiding the node_load_multiple because they are so heavy for only the few fields I want. Code is below

function HOOK_node_load($nodes, $types){
    if (in_array('yournodetype', $types)) {
        foreach($nodes as &$node) {
            $f = field_get_items('node', $node, 'field_your_reference_field');
            if (!empty($f) && isset($f[0]['target_id'])) {
                $refNode = _mymodule_reference_load($f[0]['target_id']); // this function simply writes a manual SQL query for my title and iata values.
                $node->field_your_reference_field[LANGUAGE_NONE][0]['title'] = $refNode->title;
                $node->field_your_reference_field[LANGUAGE_NONE][0]['iata'] = $refNode->field_iata[LANGUAGE_NONE][0]['value'];
            }
        }
    }
}

function _mymodule_reference_load($nid){
    $refNode = db_query(sprintf("SELECT N.nid, N.type, N.title, A.field_iata_value, R1.field_readmore1_value, R2.field_readmore2_value
                FROM node N
                LEFT JOIN field_data_field_iata A ON N.nid = A.entity_id
                LEFT JOIN field_data_field_readmore1 R1 ON N.nid = R1.entity_id
                LEFT JOIN field_data_field_readmore2 R2 ON N.nid = R2.entity_id
                AND A.deleted =  '0'
                AND R1.deleted =  '0'
                AND R2.deleted =  '0'
                WHERE N.nid =  '%s'", $nid))->fetchObject();
    $refNode->field_iata = array('und' => array(0 => array('value' => $refNode->field_iata_value))); // maintain same structure as node_load
    $refNode->field_readmore1 = array('und' => array(0 => array('value' => $refNode->field_readmore1_value)));
    $refNode->field_readmore2 = array('und' => array(0 => array('value' => $refNode->field_readmore2_value)));
    unset($refNode->field_iata_value);
    unset($refNode->field_readmore1_value);
    unset($refNode->field_readmore2_value);
    return $refNode;
}


Get whole tree of a taxonomy term from node into seperate php variables Can anyone of you brainy folk suggest the best way of retrieving the taxonomy term on a node and both of it's parents then storing as variables on a php snippet?
For example: Country->City->District output to $country, $city and $district?

Thanks in advance for all your answers!...

nb, this is what I get from print_r, [0] being the country, [1] being the area and [2] the district:

field_location_term] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [tid] => 26
                        [taxonomy_term] => stdClass Object
                            (
                                [tid] => 26
                                [vid] => 5
                                [name] => B----a
                                [description] =>
                                [format] => filtered_html
                                [weight] => 3
                                [vocabulary_machine_name] => geographical_location
                                [metatags] => Array
                                    (
                                    )

                            )

                    )

                [1] => Array
                    (
                        [tid] => 27
                        [taxonomy_term] => stdClass Object
                            (
                                [tid] => 27
                                [vid] => 5
                                [name] => B----o
                                [description] =>
                                [format] => filtered_html
                                [weight] => 0
                                [vocabulary_machine_name] => geographical_location
                                [metatags] => Array
                                    (
                                    )

                            )

                    )

                [2] => Array
                    (
                        [tid] => 28
                        [taxonomy_term] => stdClass Object
                            (
                                [tid] => 28
                                [vid] => 5
                                [name] => M----w
                                [description] =>
                                [format] => filtered_html
                                [weight] => 0
                                [vocabulary_machine_name] => geographical_location
                                [metatags] => Array
                                    (
                                    )

                            )

                    )

            )

I thought the best thing to do would be

$country = $node->field_location_term['und'][0]['taxonomy_term']['name'];

But I get no output.

It appears from your printout that taxonomy_term is an object, not an array. So your code would look like this:

$country = $node->field_location_term['und'][0]['taxonomy_term']->name;

You might not be able to do the object->['array']->object->['key'] thing. It might need to be broken into:

$foo = $node->field_location_term['und'][0]['taxonomy_term'];
$country = $foo->name;


How to modify a term reference autocomplete field I am using a term reference field but the widget type is autocomplete term widget. This term consist of many levels as parents and child. In the form I need to display only the child terms(only the lowest level in my case 3rd level) in this field. How can I do this. Please anyone help me on this. Thanks

There's a GREAT module for this type of configurations called Hierarchical Select

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!

This module has a lot to offer, but as for your need, it also does the trick.
Also you might want to consider Taxonomy Term Reference Tree Widget as well, the main functionality is a different thing but you can define a permission via views to do what you are after too with this module.


How do I add a more/less link in block? How do I add a more/less link to drop-down and roll up a block?

I have a custom search block with a lot of field items and as such, the block is so long.
I want to be able to add a more link to drop down the redundant fields and less to roll up the block again.

I'm trying to do something similar to the search block on checki.com.ng. I am running a Drupal 7 site, naijabooker.com.

I assume you have a custom block with a form created from your custom module.
You would need to add an attribute #prefix to the first field item starting from which you want to hide the items and add an attribute #suffix to the last field item you want to hide, For example,

$form['first_item']['#prefix'] = '
';

// more elements here

$form['last_item']['#suffix'] = '
';

Then, you can bind jQuery.slideUp() and jQuery.slideDown() to the more/less link element, let's say for example, #moreless.

$('#moreless').bind('click', function(){
    if( $('#accordian:visible').size() ){
         $('#accordian').slideUp();
         $(this).html('More &raquo;');
     }else{
         $('#accordian').slideDown();
         $(this).html('Less &laquo;');
     }
});

You can see the working jQuery code here. These two jQuery functions are provided by jQuery core API. You don't need to include any extra library.


How can I use the Comment field as a way to privately message the node author? I am working on a classifieds site where individual users can sign up and, of course, post things they would like to sell.

However, I need for users, both anonymous and signed up, to be able to contact the poster about his or her item.

Using the default comment form for this would be perfect.  What would I need to do in order to allow only the author of that node to see the comments for his node? I don't mind writing a module if I need to, but I am not sure how to get started. Even if I had to go that route, sounds like I would need to modify the permissions setting?

I know there are other modules out there like Private Message, but that's just too big and bulky when Comments work almost exactly like I need them to.

Thanks!

I see some potential pitfalls with this approach:

It probably won't be quite as simple as you describe because I guess you'd also like commenters to be able to see their comments, and replies to their comments, while hiding other people's comments. (Or am I wrong?)
You mention you'd like to allow anon users to comment, so you need some way to differentiate one anon user from another (if they're able to see their own comments, but not others).
It won't play nicely with page caching (at least without a bit of effort).
It might make life a bit more difficult if you want to have normal comments on a content type at some point. (Eg. should the comment moderation tools be showing comments which are actually private messages?)

If you do want to go down this route however you can use hook_node_view_alter().


Libraries require jQuery and not work I load some libraries in my module by using this hook :

function food_truck_form_views_pre_render(&$view) {
  if ($view->name == 'marqueurs_admin') {
    drupal_add_css(libraries_get_path('animate') . '/animate.min.css');
    drupal_add_js(libraries_get_path('bootstrap_notify') . '/bootstrap-notify.min.js');
    drupal_add_js(drupal_get_path('module', 'food_truck_form') . '/js/food_truck_form_admin.js');
  }
}

But when I write a notify in my food_truck_form_admin.js (this code) :

(function($) {
    $.notify({
    icon : 'fa fa-exclamation',
    message : 'TEST'
    }, {
    animate : {
        enter : 'animated flipInY',
        exit : 'animated zoomOutUp'
    },
    type : 'danger'
    });
})(jQuery);

I get this error :

  2bootstrap-notify.min.js?o68oa5:1 Uncaught TypeError:
  this.$ele.find(...).on is not a function

have you got an idea ?

PS : is it the best method to load libraries ? I see on libraries API there was libraries_load... method but i don't understand how to use them :/

I suppose you should be loading the libraries through the libraries API:

It is in the Libraries API documentation

libraries_load($name);

// Usually, you'll want to do something after the library has been loaded.
// Because you cannot always depend on the library being installed you have
// to check first if the loading was actually successful:
// Try to load the library and check if that worked.
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // Do something with the library here.
}

Since you say you don't understand this. The above check makes sure the library is loaded correct. So you will not run into weird errors or exceptions. Just put all the code that depends on the libraries inside that if-statement. (As a matter of fact is it much important for PHP than it if for JS, but nevertheless it prevents errors.)

UPDATE:

Oh wait. The problem is that jQuery.on() the function that throws the error was added in jQuery 1.7. Stock Drupal runs on 1.4, so in order to get this to work, have a look at jQuery update and make sure Drupal runs at leat 1.7.


How do I track if a user is logged in on multiple devices and computers? I have video content behind a paywall and want to make sure that each user is only logged in from one computer, or device at a time. If they are logged in on the computer watching videos, I don't want their friends to use the account to log in and watch videos from a different computer, device or IP address.

How do I enforce this?

Check Session Limit module.

Session Limit allows administrators to limit the number of simultaneous sessions per user.
Max session is configurable, no database tables needed.
By default, a session is created for each browser that a user uses to log in. This module will force the user to log out any extra sessions after they exceed the administrator-defined maximum.
Assuming the session limit is 1, if a user is logged in to a Drupal site from their work computer and they log in from their home computer, they would be forced to either log off the work computer session, or abort their new login from home.


"This entity (node: id) cannot be referenced" error I use Drupal 8 and I have a content type which has a field that references another content type as a entity reference field. I use a rest endpoint to create the node and the referenced node which works fine.

I also have the workbench module installed so I can change the moderation state of the nodes.

The problem is that when I change the moderation state from draft to review I get the error This entity (node: {ID}) cannot be referenced.

Why am I getting this?

The view_unpublished "module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard."

composer require drupal/view_unpublished
drush en -y view_unpublished

At /admin/people/permissions set permissions as required:

Finally, at /en/admin/reports/status/rebuild rebuild the permissions, which may take some time:


How to programatically change a view's style_options when user clicking the exposed filter apply button? In a Leaflet Map view, the exposed filter is a list(text) field. On user clicking the Apply button of the exposed filter form, I need to programatically change the value of $handler->display->display_options['style_options']['map'], I mean to change the Leaflet map style (which is defined in the module leaflet_more_maps).

How to make it?

The hook_views_pre_render() works.

function my_misc_views_pre_render(&$view) {
  if($view->name == 'classrooms_map') {
    $view->style_plugin->options['map'] = ($view->exposed_data['type'] == 'All') ? 'all' : $view->exposed_data['type'];
  }
}


How to create custom theme a view I've defined a view with the CCK and Views modules. I have two ways for printing the result:

As node content
As fields content

If I choose node content, I need to choose the view mode, which by default allows to choose between teaser, and rss (among others). How do I create a new custom view mode?

If I choose fields content, I see the following data, under theme information.

Display output: views-view.tpl.php, views-view--frontpage.tpl.php, views-view--default.tpl.php, views-view--default.tpl.php, views-view--page.tpl.php, views-view--frontpage--page.tpl.php
Style output: views-view-unformatted.tpl.php, views-view-unformatted--frontpage.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--page.tpl.php, views-view-unformatted--frontpage--page.tpl.php
Row style output: views-view-fields.tpl.php, views-view-fields--frontpage.tpl.php, views-view-fields--default.tpl.php, views-view-fields--default.tpl.php, views-view-fields--page.tpl.php, views-view-fields--frontpage--page.tpl.php

How do I create a custom theme for printing the result using the fields method?

Edit1: i create new view mode with Chapabu answer.(create a custom build mode you can use Entity view modes)

now i see this result in front page : Image Link

now, this print default content with default html/css.in act, i need custom content default for my theme. Example : i dont need to print date and author content! i need to print image(Thumbs), Summary and content type. in html/css i need to list content in

Or Any Div or Span ... (custom html/CSS) How To Edit This HTML/CSS?

I Think Fields Method Better For My result. This Is TRUE? If YES, How To?

EDIT2: Example Of my Need Conetnt And CSS/HTML:

I need to design this block(in act example: article promoted front page Or last Article Or Last News ...) for show in vertical news ticker using jquery and css. this jquery plugin need to custom html/css:

Latest News

news item 1

news item 2

news item 3

news item 4

news item 5

news item 6

news item 7

news item 8

now, I need a custom content and html/css design views block for this.

When you're not satisfied with the existing view modes you could create your own using either your own tiny plugin (see ready code) or use Display Suite. The new view mode will appear in Views UI for selecting.

I'd recommend however the true theming technique by using Views and fields. There you have more flexibility and control over the markup. You can do many things using Views UI (such as turning off the wrapper markup, linking a field to its content, overwriting some attributes, etc.) When you find out you cannot do something in Views UI this might be a reason for using a .tpl.php file at one of the output levels - in your case the style or row variants would be your friends)

It's recommendable that you watch some Views tutorials, such as NodeOne's Taming the Beast series or by Mustardseed Media (even if for Views 2 only) to get the idea how to tailor Views output to your needs.

Hope this helps.


Commerce Analytics not working On my website we don't get any e-commerce tracking in Google Analytics. Usual analytics works fine. How do I troubleshoot?

Have sold around 200 products since installing & configuring the Google Analytics and Commerce Analytics modules.

The module maintainers haven't replied on the same request on drupal.org https://www.drupal.org/node/2612390

Cheers,

EDIT:
I updated from Commerce Analytics from 7.x-1.1 to 7.x-2.0-beta2. Still nothing in Google Analytics, but now ga_push appears in source code.

What method are you using to Push? Configuring the rule, you can select it at the bottom of the edit page:

I just tried it with Analytics.js support and the checkout page appears to display the Analytics code:

<!--//--><![CDATA[//><!--
var ga = ga || [];
ga('require', 'ecommerce', 'ecommerce.js');
ga('ecommerce:addTransaction', {"id":"5","affiliation":"Commerce Kickstart","revenue":16,"currency":"USD","tax":0,"shipping":8,"city":"Austin","region":"Texas","country":"United States"});
ga('ecommerce:addItem', {"id":"5","sku":"MG2-YLW-OS","name":"Coffee Mug 2","category":"Product: drinks","price":8,"currency":"USD","quantity":1});
ga('ecommerce:addItem', {"id":"5","sku":"shipping","name":"Standard shipping: 3 - 5 business days","category":"Shipping","price":8,"currency":"USD","quantity":1});
ga('ecommerce:send');

//--><!]]>

This appears to be correct. One of the difficulties with testing GA for Commerce is that they do not show up in realtime.

So, I'd try it with Analytics.js if you aren't currently using that method and ensure that something like what you see above is being included on the page. If it isn't, then something isn't working on the site side. If it displayed, then check your JS console for errors to see if something else happened. You can also open up the Network tab and ensure that you're seeing the calls to "collect":


Drupal 6: Custom Menu not Expanding when Parent (generated by views) is selected I have a Drupal 6.26 site with a custom menu like so:

-Category 1
--Page
--Page
-Category 2
--Page
--Page
...

All Category pages are genrated by a view (e.g. sitename.com/intranet/category)

All pages that are children of each category are nodes.

My primary problem is, when a category page is selected, the menu it's associated with doesn't expand. The site owner doesn't want the menus expanded by default.

A secondary problem is the menu won't expand when one of the child pages is selected unless it has the path /intranet/category/*, which is not always desired.

Hopefully a bit of code can solve this issue.

Five lines of code placed in a views template file solved the issue:

 <?php
    $path = drupal_get_path_alias(check_plain($_GET['q']));
    $menu_item = menu_get_item($path);
    $menu_item['href'] = $path;
    if($path && $menu_item) {
      menu_set_item(NULL, $menu_item);
    }
  ?>


Guidelines on customisation options when using hook_views_default_views? Are there any good instructions for the customisation options available when creating a default Views files using hook_views_default_views()?

The API for the function can be found here:
http://api.drupal.org/api/views/views.api.php/function/hook_views_default_views/7

However I have yet to find any explicit information on the values that can be used and the options that are available when using the display_options array.

As an aside, here is an example where the lack of instruction become a problem for a novice Drupal developer: it's hard to know what to put for:

$handler->display->display_options['access']['type'] = 'none';

Do you add just add the name of a permission, or a role, if you want to restrict access? Is this even what the option means?

There is one neat and simple way. Create view normally, using GUI. Then export it. I created view default-demo for demonstration purposes:

http://example.org/admin/structure/views/view/default_demo/export

gives:

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'default demo';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'default-demo';
$translatables['default_demo'] = array(
  t('Master'),
  t('default demo'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);

As you can see that's exactly what you would want to put into hook_views_default_views function. Simple as this :D

If you can't find export link, it's at top right, drop down edit view name/description to see it.

Everything available from code is supposed to be available from GUI too, with the notable exceptions of $view->core and $view->api_version that are always set by gui to the current release and must match what you set in hook_views_api() in your module.

For specific line you asked for:

$handler->display->display_options['access']['type'] = 'none';

You need to go to Page Settings > Access, set things as you want them, export view. Done. It seems that Views developers chooses to use their time to give us tools, not documentation, when their time is limited, but the tools they give us are comprehensive.


Show drupal message with ajax flags I bound an action to my flag to display a message on flagging. However because I am using AJAX flags the message is only displayed after I refresh the page.

Is there any way to make the message appear after the flag is flagged and not on page reload?

Thanks

This feature already there with flags module.

Please check in your flags settings page.


How do I pass contextual filters to a view via services I have a view that accepts a contextual filter in order to return the correct results. I'm using Services 3 and Drupal 7. I'm able to create an endpoint, and retrieve the view via services. But it seems like there is no way to pass the contextual filter, because services_views only has a retrieve method (which uses GET). Does anyone know if this is possible, and if so how it can be done?

pass your filter as follows:
yourendpoint?args[0]=value&args[1]=value

Good luck


List all the taxonomy terms in a particular vocabulary in Drupal 6. My task is to display all the terms in a particular vocabulary. It should also display all the sub-terms along with their parent terms.

For example the taxonomy page for a particular vocabulary is like

Term 1

Term 2

Term 3

Sub-term 1 of Term 3

Sub-term 2 of Term 3

Sub-term 3 of Term 3

Term 4

Term 5

Term 6

Sub term 1 of Term 6

Sub term 2 of Term 6

I need an exact display of taxonomy terms as above (without edit, just to list all the terms in a tree order). Is it possible with views or whether I have to do coding? I tried this thing with views by giving term- weight filter, taxonomy parent term relationships etc, received duplicate values and found it very complex.

You can use taxonomy_get_tree()

Parameters

$vid: Which vocabulary to generate the tree for.

$parent: The term ID under which to generate the tree. If 0, generate the tree for the entire vocabulary.

$depth: Internal use only. Now deprecated and isn't used. It is left here only because of compatibility issues.

$max_depth: The number of levels of the tree to return. Leave NULL to return all levels.

API here


Drupal 7 Draggable Views in different order when logged in My site is : www.terrafirmasouth.co.uk
I have draggable views set up for projects, I have a menu option called 'Sort Projects', certain users can access this to rearrange projects, if they have a role called 'publisher' .
I have given the Publisher role access to 'Sort Draggable Views' in People/Permissions (but not for anonymous users). When they are logged in, they can rearrange projects under a Sort Projects menu item (path is 'sort-projects'), and the order seems fine, then when they log out the order just reverts back to what it was before the update. When they log back in again, the order to retained from the previous update.  When I log in as administrator and do the same thing i.e. change order of a project,  the order is fine , and when I log out.

Is there some other permission I need to set for anonymous users so they see they updated order? Also, on the Sort Projects screen, it doesnt show 'updated successfully or saved' in green  at the top which I would normally expect, i dont get any message, other than the spinning circle at the top, then it finishes as normal. Any ideas?

This can be resolved by following this link:-
http://drupal.org/node/616658

Scroll to the bottom, and follow instructions in the last Post whereby you install the Rule module, create a rule to clear cache on sorting a View, you may have a problem where the option to create custom PHP is not in the drop down list, if so, this is resolved by enabling the 'PHP Filter' module.

All tested and works perfectly ! :)


How do I filter a views page with contextual filters? I have an all events views page where I would like to put the links 'All Events', 'Upcoming Events', 'Past Events' in the header.

I would like to link them to the same views page but show filtered results. It seems possible by looking at contextual filters but not sure which way to go.

Thanks,

Kevin

you can add exposed filters to show past and future events. When you use the filters you'll see the URLs it generates. Those are your links and you can add them to the header of the view with a "global text area".
You can now hide the exposed filter forms by setting "Exposed form in block:" to yes. That will remove them from the view.


How can I give the permission to edit, update, or delete a comment or a user profile to specific roles? I am using the ACL module for Drupal 7 to give the permission to edit, update, and delete nodes to specific users. It works perfectly.
I want the same feature for comments and user profiles.
Is there any specific module or API for the same?

There's the Comment Permissions module:

  The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.

It does have a (dev) Drupal 7 release, it's just not listed on the module page for whatever reason. You can find the archive here.

It will need testing before you can use it in a production site, but it's a very small module and a cursory glance at the code suggests it should work. I used that code as the base for a more advanced comment permissions module (including soft-deleting etc) some time back and don't remember finding any problems with it.


How to print all the elements of a specific column from a table from database in custom module? I have a  custom module. I would like to see all the blocks in it . For that i have written a query in my costom.module file . But it will show me the following error.

Query:-

 $result = db_query('SELECT *FROM  `block` ORDER BY
`block`.`delta` ASC LIMIT 0 , 30');
 while ($node = db_fetch_object($result)) {
 print_r("$result");
 }

Why this is not working, Where am i going wrong ?

You made 4 errors:

You should use {} around table names, not ``.
print_r does not like objects Drupal uses, for testing purposes it's way better to use

while($row = $result->fetchAssoc() ){
}
$node may be already used elsewhere, it's not wise to use common names if you don't mean it.
SELECT *FROM should be SELECT * FROM (kudos for Clive)


Search API: Custom relationship? Q: Can I combine two (geofield) field instances from different relationships into one aggregated Search API field?

So far I tried search_api_combined, which seems ok, but does only support the default field types, but not geofield LatLong for proximity search.

I was thinking that I could somehow craft a custom relationship that, for a given (product) node fetches one of the two profiles, or one of the two field instance values.

I guess all I need to know really is where the relationships in Search API are coming from.

Use case details:

Two profile2 profile types: Private person, merchant. Usually one person has only one such profile. In case of doubt, I would pick one and ignore the other.
Both contain a field instance of "field_coordinates" geofield.
Both contain a postal address field that acts as a geocoding source for the geofield, but with different granularity (private person only specifies postal code, merchant specifies full address). (This is one of the reasons why I'm using profile2) (This is not central to the question, just to give a better idea about the problem space.)
Search API and Facet API.
Product nodes with authors.
Profile2 geofield field_coordinates should act as the location for products.
Search index for products should combine the field_coordinates from different profiles into one aggregated field.

Oh, this turned out to be easy. Use hook_entity_property_info_alter() to define a new property.

/**
 * Implements hook_entity_property_info_alter().
 *
 * @see profile2_entity_property_info_alter()
 */
function MYMODULE_entity_property_info_alter(&$info) {
  // Add related profiles to the user object.
  $properties = &$info['user']['properties'];
  $properties['MYMODULE_profile2'] = array(
    'type' => 'profile2',
    'label' => 'Profile 2 (MYMODULE)',
    'description' => 'The first profile2 profile that can be found on the user.',
    /* @see _MYMODULE_get_profile2() */
    'getter callback' => '_MYMODULE_get_profile2',
    # 'bundle' => $type_name
  );
}

/**
 * Entity property callback.
 *
 * @param object $account
 * @param array $options
 * @param string $name
 *
 * @return object|null
 *
 * @see profile2_user_get_properties()
 */
function _MYMODULE_get_profile2($account, array $options, $name) {
  $profiles = profile2_load_by_user($account, NULL);
  return reset($profiles) ?: NULL;
}


How to add multiple conditions on a single field in views? I have two fields in my content type. State and test . State have two values active and inactive and test is a boolean field.

I want to display the content of this content type using views which will display:

active content
inactive content if test is FALSE

How can I do this in views?

I tried with views filter groups and it generates this condition.

WHERE ((( (node.status = '1') AND (node.type IN  ('mycontnt')) AND (state = 'active') )OR( (state = '4') AND (test = '0') )))

But this is not displaying the correct content as I want.

So far as there is no support for nested groups in Drupal 7, we shoud do it slight differently.

Join general filters (Published and Node type) in first AND group. May be we also should to add there "State IS NOT NULL" condition to exclude content with empty State field.

In second group we should place State = 'active' OR test = 'false'. This group - OR group.  In the Views admin interface in would be somthing like this:


What is the Aegir make_working_copy SCM option mean? If one creates a platform and chooses to preserve the working copy, does this initiate a .git clone that the aegir user from CLI, could update and merge branches to?

  Create a new platform:

    Drush make option:

      Normal - Discards SCM files
      Working copy - preserves SCM files

Where is the working copy directory?

The 'Drush make option' field in the Aegir user interface (when creating a new platform based on a makefile) simply determines whether or not the --working-copy option is passed to Drush make.

The --working-copy option for Drush make "preserves VCS directories, like .git, for projects downloaded using such methods." (source: Drush.org)

Passing the --working-copy option leaves the .git directories intact (as if you had done a manual git clone) and hence allows you to pull in updates, etc.
However, this is not the recommended way of updating modules in Aegir, so the 'Normal - Discards SCM files' option is preferred.

The aegir_make_working_copy module provided this functionality for Aegir 1.x, before it was merged into Aegir core 2.x.


tableselect does not work for me somehow 1 Array
(
    [table] => Array
        (
            [#type] => tableselect
            [#header] => Array
                (
                    [field_name] => FIELD NAME
                    [field_type] => FIELD TYPE
                    [no_of_values] => NO OF VALUES
                    [display_fields] => DISPLAY FIELDS
                    [field_label] => FIELD LABEL
                    [required] => Required
                    [product_type] => Product Type
                )

            [#options] => Array
                (

            [field_colour_pro] => Array
                        (
                            [field_name] => field_colour_pro
                            [field_type] =>
                            [no_of_values] =>
                            [display_fields] => 1
                            [field_label] => color
                            [required] => 0
                            [product_type] => shirt
                        )

                    [field_description] => Array
                        (
                            [field_name] => field_description
                            [field_type] =>
                            [no_of_values] =>
                            [display_fields] => 1
                            [field_label] => description
                            [required] => 0
                            [product_type] => test_pro_v
                        )

                )

            [#multiple] => 1
        )

$header = array(
    'field_name' => t('FIELD NAME'),
    'field_type' => t('FIELD TYPE'),
    'no_of_values' => t('NO OF VALUES'),
    'display_fields' => t('DISPLAY FIELDS'),
    'field_label' => t('FIELD LABEL'),
    'required' => t('Required'),
    'product_type' => t('Product Type'),
  );

  $rows = array();
  foreach(commerce_product_types() as $product_type => $product_type_array){
    $field_info = field_info_instances('commerce_product',$product_type);
    foreach($field_info as $machine_name =>$field_details){
      $rows[$machine_name] = array(
        'field_name' => $machine_name,
        'field_type' => $field_details['type'],
        'no_of_values' => $field_details['cardinality'],
        'display_fields'=>1,
        'field_label' => $field_details['label'],
        'required' => $field_details['required'],
        'product_type'=> $product_type,
      );

    }
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
  );

//  print_r($form);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

return $form;

I tried to get the tableselect form #type into operation it does not work and gives empty row even when each row has values,I would like to help me find any silly mistake which I am making out here

Here is image of how the table select looks which is empty

I copied your code from and commented the variables and/or functions you're using since I don't know what they are for and just replaced a simple array to loop through.

/**
 * Implements hook_menu().
 */
function leomod_menu() {
  $items['leoo'] = array(
    'title' => 'asd',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('leomod_asd_form'),
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Form.
 */
function leomod_asd_form($form, &$form_state) {
  $header = array(
    'field_name' => t('FIELD NAME'),
    'field_type' => t('FIELD TYPE'),
    'no_of_values' => t('NO OF VALUES'),
    'display_fields' => t('DISPLAY FIELDS'),
    'field_label' => t('FIELD LABEL'),
    'required' => t('Required'),
    'product_type' => t('Product Type'),
  );

  $rows = array();
  $tests = array('1', '2', '3');
  //foreach(commerce_product_types() as $product_type => $product_type_array){
  foreach($tests as $test) {
    // $field_info = field_info_instances('commerce_product',$product_type);
    //foreach($field_info as $machine_name =>$field_details){
      $rows[$test] = array(
        'field_name' => $test,
        'field_type' => $test,
        'no_of_values' => $test,
        'display_fields'=> $test,
        'field_label' => $test,
        'required' => $test,
        'product_type'=> $test,
      );
    //}
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#multiple' => TRUE,
  );

  //  print_r($form);
  $form['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

Since your table structure is working, I suspect there is something wrong with these lines:

foreach(commerce_product_types() as $product_type => $product_type_array) {

and

$field_info = field_info_instances('commerce_product',$product_type);
foreach($field_info as $machine_name =>$field_details) {

Also make sure you:

Flushed caches
Show all errors while developing since you're dealing with functions there that may return some errors that aren't displayed
Check the variables and functions if they return anything by using print_r() or Devel module's dsm().


How to make a single query with multiple records How do I make this as a single query?

$result = db_query("SELECT replace(source, 'node/', '') as source FROM {url_alias}  where source like 'node/%' limit 11");
foreach ($result as $record) {
$result2 = db_query("SELECT fci.* FROM {node} AS fci LEFT JOIN {node_access} AS fdfp ON fci.nid = fdfp.nid where fci.nid = :item_id AND fdfp.nid IS NULL", array(':item_id' => $record->source));
  foreach ($result2 as $record2) {
    echo '<pre>';
    print_r($record2);
  }
}

This works for me.

$result2 = db_query("SELECT fci.* FROM {node} AS fci LEFT JOIN {node_access} AS fdfp ON fci.nid = fdfp.nid where fci.nid IN(SELECT replace(source, 'node/', '') as source FROM {url_alias}  where source like 'node/%') AND fdfp.nid IS NULL");
foreach ($result2 as $record2) {
  echo '<pre>';
  print_r($record2);
}


Drupal Views field handler: how to unserialize an additional field data? I'm developing custom Views field handler, which renders a "Reorder" button on Commerce Line Item View. I need to access to the 'data' field, which is a serialized array.
What is the best way to get serialized field data?

/**
 * Implements Reorder Line Item button field.
 */
class commerce_reorder_lineitem_handler_field_commerce_reorder_lineitem_button extends views_handler_field {

       ...

          function construct() {
            parent::construct();
            $this->real_field = 'line_item_id';
            $this->additional_fields['line_item_id'] = 'line_item_id';
            $this->additional_fields['order_id'] = 'order_id';
            $this->additional_fields['data'] = 'data';
          }

          /**
           * Render form element placeholder.
           */
          function render($values) {
            return '<!--form-item-' . $this->options['id'] . '--' . $this->view->row_index . '-->';
          }

       ...

}

The views data can be altered in the handler's render() method.

  function render($values) {
    $values->commerce_line_item_data = unserialize($values->commerce_line_item_data);
    return '<!--form-item-' . $this->options['id'] . '--' . $this->view->row_index . '-->';
  }


How does 'access content' permission string works? I've written a question and gotten an answer. The is fine but not fulfill my requirements.
The question is below:

It will be helpful, if anyone explain the full meaning of the string 'access content' because I've not found 'access content' string on '/admin/people/permissions' page. On the other hand, if I use following code, it will be work.

function custom_menu_menu(){
    $items = array();
      $items ['status'] = array(
        'title' => 'My Status',
        'menu_name' => 'main_menu',
        'page callback' => 'status_page',
        'access arguments' => array('access content'),
      );
    return $items;
}

/*
  *Definition of the menu callback function.
  */
function status_page() {
    return 'Hello world!';
}

My Questions:

Is 'access content' a 'permission string'? if answer is 'yes' then please explain how does it works? [note: it is not listed in '/admin/people/permissions' page. So, How determinate that user's rules has this permission]
What is the meaning of 'access content' permission? example: 'Page: Create new content' permission means if user has this permission then user can create 'Page' content but if user has 'access content' permission then what can do user on this link page.

Read: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7

'access content' means 'Node: View published content' on permission list. Check this link for list of permissions provided by node module: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_permission/7
'access content' will be passed as a first argument to user_access() which is default access callback for new menu items. You can change default access callback like this:

function custom_menu_menu(){
  $items = array();
  $items ['status'] = array(
    'title' => 'My Status',
    'menu_name' => 'main_menu'
    'page callback' => 'status_page',
    'access callback' => 'custom_menu_access_callback',
    'access arguments' => array('access content', 'something else'),
  );
  return $items;
}

function custom_menu_access_callback($arg1, $arg2) {
  // arg1: access content
  // arg2: something else
  // if this function returns TRUE user will get access to page callback
  // if this function returns FALSE user won't get access to page callback
}


How to highlight current node in views I made a panel for showcasing individual nodes. That panel has a left column that contains a view with a list of all nodes (think teasers), and a right column with the node content.

In the view which generates the list of nodes in the left column,
how can I highlight the current node?

If you list complete node teasers, it means, the nodes are rendered by node.tpl.php. So just add a class to the node template in _preprocess_node something like this:

$node = $vars['node'];
$menu_object = menu_get_object();

if ($menu_object && $menu_object->nid == $node->nid) {
  $your_custom_class = 'this-is-the-actual-node';
}


How to override custom block methods in drupal 8 i have created a block with all its methods like blockAccess()... i would like to override one of those in other module, in my project i have used page manager, then i cant call hook_block_access()..because blocks added with page manager doesnt get into this hook.

Your other module can implement hook_block_access().

The example code in Drupal core looks like this:

function hook_block_access(\Drupal\block\Entity\Block $block, $operation, \Drupal\Core\Session\AccountInterface $account) {

  // Example code that would prevent displaying the 'Powered by Drupal' block in
  // a region different than the footer.
  if ($operation == 'view' && $block
    ->getPluginId() == 'system_powered_by_block') {
    return AccessResult::forbiddenIf($block
      ->getRegion() != 'footer')
      ->addCacheableDependency($block);
  }

  // No opinion.
  return AccessResult::neutral();
}

Since it's a hook, you would have to replace the word "hook" in the function name with the machine name of your module, and place this function in the .module file.


How to get rid of text box artifact with Fivestar module? I'm using Drupal 7.14 and Fivestar 7.x-2.0-alpha2.  There is a text box artifact displayed below the stars on all nodes with a Fivestar field (see screenshot below).

Here is the HTML/CSS source for this screenshot:

great

Reader Rating:&nbsp;

3

I suspect that

 is what is creating this empty text box.

This empty box being shown is despite having chosen No text in the Text to display under the stars dropdown menu for the Fiverstar field at /admin/structure/types/manage/$content_type/display (where $content_stype is a dummy for whatever content type I am editing).

Am I missing something?

Is there another option somewhere to get rid of this annoying text-box?
Is this the default behavior of Fivestar/would I need to manually modify Fivestar to fix this?
Or is this a bug that noone has reported yet (I couldn't find anything that sounded like this issue here)?  I would think that if this was a bug someone would have reported it already (it is pretty noticable) so I'm inclined to think I am just missing something--but if people think that this is a bug, please indicate as much and I will remove the question and file an issue!

Thanks in advance for any help.

Can't you get rid of it with CSS? display: none;


Is it a good idea to mix node api and entity api? I have a custom module that depends on several contrib modules. One of the contrib modules has a new version out and has switched to using entities. The code in the custom module is using node api hooks. I update it just for the change in the contrib module, there will be one hook that is using entity api e.g. hook_entity_presave().

Should I update everything to use entity api or will mixing the two be okay?

As long as you are sure everything you get will always be a node, there is no problem with mixing. Nodes are entities, after all, and node hooks and functions never got "obsolete" mark. It may be even beneficial, because you are making sure other node-related modules will continue to work with your module in a way you expect them to.

On the other hand, if you are getting something from that other module, and you can't guarantee it will always return a node, you should assume it might be any other entity, and either switch to entity approach totally, or filter what you got to make sure you only use node functions on nodes.


Get URLs of taxonomies terms in Link field I am having a link field in drupal 8. It can accept both internal and external links with autocomplete feature. But it works only with nodes means with content but i want to use it with taxonomy terms as well.

How can i achieve this ?
Any Help

Nodes and taxonomies both use fields but they're stored slightly differently.  You will need to recreate your field for the taxonomy you wish to apply it to, it won't show up in Use existing field.


Hide menu items from non-authenticated user Possible Duplicate:
  Hiding link from anonymous users

I have 2 nodes on Drupal 7 site, that only authenticated users can access. But even if I logout, links to these nodes appear in the main menu. When I click any of them, it gives:

Access denied
You are not authorized to access this page.

Which is correct. As far as I know, Drupal must hide the links, that the user can't access. But for these items it doesn't.

How to fix?

Follow Below things:

1) Make sure that in admin/people/permissions "View published content", "view own Unpublished Content are "Unchecked" for the "anonymous user".

2)  Still if you are getting those "Disclaimer and Policies" menu links.
   i) Create a  new menu and add those links in to that menu. While adding links Give the Parent menu link to "Main Menu". and save the menu.
   ii) Then admin/structure/block, configure the menu block: Give the permission to access only to Authenticated User  and save the block


Access violation with Drupal 7 multisite using shared DB I'm building a Drupal 7 multisite and I want to have a separate database for each site but with some shared tables. So, I have two sites called siteone and sitetwo. I also have 3 databases - oxone (for first site), oxtwo (for second one) and oxshared (where I want to keep shared tables for both sites.

I used the following config for settings.php (for siteone), but it shows me a PDO exception... What I'm doing wrong? Will be very appreciate for any help or advice.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'oxone',
      'username' => 'oxone',
      'password' => '*********',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
         'default'   => 'oxone.',
         'users'     => 'oxshared.',
         'users_roles'     => 'oxshared.',
         'sessions'  => 'oxshared.',
         'role'      => 'oxshared.',
         'role_permission'      => 'oxshared.',
         'authmap'   => 'oxshared.',
     ),
    ),
  ),
  'oxshared' =>
  array (
    'default' =>
    array (
      'database' => 'oxshared',
      'username' => 'oxshared',
      'password' => '**********',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

The exception is:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'oxone'@'localhost' for table 'users': SELECT u., s. FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid; Array ( [:sid] => _5UERN3eEWligNxBusEYCq3Lnf48pfvWDu9FDQDZUI8 ) in _drupal_session_read() (line 102 of /home/qsoul/public_html/siteone.dev.lo/includes/session.inc)

Why doesn't Drupal use the oxshared user when accessing the tables in the oxshared database, as defined in the prefix array? It uses the oxone user instead.

The question is closed. It seams to be that to have some tables in a separate database:
1) that second db should be placed at the same host as default one.
2) the user who has access to the default db should also has access to the second db.

Adding one more db to settings.php is not needed. It my case the correct settings.php db config has to look like:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'oxone',
      'username' => 'oxone',
      'password' => '*********',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
         'default'   => 'oxone.',
         'users'     => 'oxshared.',
         'users_roles'     => 'oxshared.',
         'sessions'  => 'oxshared.',
         'role'      => 'oxshared.',
         'role_permission'      => 'oxshared.',
         'authmap'   => 'oxshared.',
     ),
    ),
  ),
);


Database Pager for a new entity type I have implemented a new entity type that requires paged access to DB and meet a probem with several pagers for independent entities on the same theme page.

The problem is that that entity can be used along with the node, thus two (or more) pagers may co-exist on the same page. The element property of PagerDefault apparently does not work (see discussion). In addition, PagerDefault simply uses $_GET['page']) to find required page number, which leads to even bigger confusion - both absolutely independed DB queries share same HTTP page query parameter.

What do you believe is good solution of this problem?

Further investigations have revealed a bug with EntityFieldQuery::pager()

I'm not sure I understand your problem ... Are we talking about like a node/edit page or a View? Or is this a menu page callback where you want node(s) and this entity both with paged output on a single html page ... ?

If you have written custom PHP/SQL/EFQ in a menu page callback, I see no reason you cannot explicitly set $element uniquely as needed in your queries.

Where is your http page query parameter coming from? A view? A url() you created by hand? If you have 2 pagers, you should have 2 $GET parameters ...

Edit: this is what I mean blog example


How do I add a class to a specific input type? Using Drupal 8. I am trying to add class="input" to an input with type="text"; any other type (i.e type="button") should not have that class added. I modified input.html.twig to the following:

<input{{ attributes.addClass('input') }}/>{{ children }}

The problem with this is that it adds the class to all input types. Is there a way to specify the input type in which the class should be added in Drupal 8?

Template files are available by default for each input type.

Copy the input.html.twig file and rename it input--textfield.html.twig
Put it in the folder of the theme
Clear the cache and the new template will be used for all text-field form fields
You can add <input{{ attributes.addClass('input') }}/>{{ children }} in that file

If you want a more customized input field, you implement hook_theme_suggestions_HOOK().

function YOUR_THEME_NAME_theme_suggestions_input_alter(array &$suggestions, array $variables) {
  // To see available variables use kint().
  kint($variables);
  if ($variables['element']['#type'] == 'textfield' && $variables['element']['#name'] == field__--------- ) {
    $suggestions[] = 'input__customized';
  }
}


Add javascript scolbar & effects to Block from module I have a block that was created with Social Feed Module. The block aggregate social feeds. I want to add a scroll-bar to the block it self. I have seen some examples:http://mydrupal.com/add_scrollbars_in_blocks

However, I would like the block scroll-bar to be visible ONLY when the user hovers over the scroll-bar. I would think I would need to use javascript with the scrolbar? Any suggestions?

It's probably bad usability because you would want your users to know that a block has scrolling content, but you could do something like this.

$(".block .content").hover(function(){
  $(this).css("overflow","scroll");
  },function(){
  $(this).css("overflow","hidden");
});


Drupal 7 html.tpl.php vs page.tpl.php variables questions/thoughts First off I am very new to Drupal but not very new to other frameworks and CMS's (symfony, cake, codeigniter, wordpress)

So I am trying to make a theme and it seems like I want to put a lot more stuff in html.tpl.php then drupal wants me to?

Like for example $logo, why is that not available in html.tpl.php, I don't want to include that in every variation of the page template, do I?

Or should I be thinking of page.tpl.php more as the wrapper than html.tpl.php.

I basically think the page template should only display content for that page, anything around that (ie, nav, logo, footer) should be in html.tpl.php. but drupal seems to be set up opposite? Why does this feel wrong to me?

Something to keep in mind is that Drupal doesn't work with templates the way a traditional MVC framework will. Ideally you want to have as few templates as possible in your theme, i.e having only one page.tpl.php with some conditionals would be best. If you do need to split things up you can define additional templates with hook_theme() in your theme's template.php and move your header/footer section into there, but in general you'll have better results by not having lots of template variations.


How to get the Object based on File ID (FID) I'm inside mytheme_image_formatter($variables) function and I got the image's FID (from $fid = $variables['item']['fid']).

Question:
Is there a way to know which object is using the image file?

Using file_usage_list(file_load($fid)), I can see which objects may use the file. But I want to know which one is using the image file, inside my function.

Tried to use mytheme_preprocess_image(&$variables), but I also found the same situation.

This is the same problem as discussed here, without a solution.

Thanks

You can use an EntityFieldQuery, e.g.

$field_name = 'field_something';
$fid = 123;

$query = new \EntityFieldQuery();
$query->entityCondition('node')
  ->propertyCondition('type', 'the_type')
  ->fieldCondition($field_name, 'fid', $fid);

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  // $nodes contains all nodes that reference the given file via field_something.
}


getting Drush to cooperate with Mercurial I just tried to update a site on my local machine from Drupal 7.14 to 7.15 with "drush up". I use Mercurial (hg) for version control. (I know that most Drupal sites use Git, but we standardized on Hg before we started working with Drupal.)

I was surprised to see that the update process pretty much hollowed out the .hg folder, which is where Mercurial stores all of its information. I got the following warning from drush:

rmdir(C:/Dev/mysite/.hg): Directory not empty filesystem.inc:141

Is there something I need to do to tell drush to please leave that folder alone? I googled this issue and didn't find anything helpful.

[update 08/29/2012]
I thought I'd post an update to this, since I still haven't solved the problem.
I tried to update a fairly vanilla test Drupal site from 7.14 to 7.15 this morning, and got the same error. Drush failed to update Drupal, and pretty much destroyed the .hg folder in the process. Here's a full dump of the messages from Drush as it did this:

    Code updates will be made to drupal core.
    WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
    Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

    Do you really want to continue? (y/n): y
    rmdir(C:/Dev/drupal-7-test/.hg): Directory not empty filesystem.inc:141              [warning]
    string(2) "\037ï"
    array(1) {
      [1] =>
      int(35615)
    }
    string(2) "\037ï"
    array(1) {
      [1] =>
      int(35615)
    }
    Destination directory C:/Dev/drupal-7-test/drupal-7.15 already exists.                 [error]
    Project drupal was updated successfully. Installed version is now 7.15.
    Backups were saved into the directory                                                     [ok]
    C:\Users\ahuey/drush-backups/drupal_7_test/20120829131850/drupal.
    Backups were restored successfully.                                                       [ok]
    rmdir(C:/Dev/drupal-7-test/.hg): Directory not empty filesystem.inc:141              [warning]

I'm running Drush 5.5. I'm OK with having to update Drupal manually for now, but it's a weird problem, so I may spend some more time on it, if I can spare the time.

wow ... drush up to my knowledge shouldnt touch any (dot) hidden files or directories. Drush up just looks for more recent module packages and updates them, which has nothing todo with .hg or .svn or .git directories.

Are you talking about a global .hg directory for your projects, or like an .hg directory within a module folder somewhere!?


Getting the exposed form to show up I'm trying to get the exposed form to show up for one of my views, but it doesn't seem to be working.

I've got filters exposed in the "Filter Criteria" section, the "Exposed Form In Block" section is set to "Yes", and the block itself has been activated and placed into one of the sidebars, but its still not showing up.

Am I forgetting to do something here?

Edit: Forgot to add that I'm using Drupal 7

Edit 2: Found a post that says to turn Ajax on to get the form to display, but that doesn't work either.

Edit 3: So turning off the "Exposed Form in Block" option gets the filters to display, but for theming purposes I really need this stuff in a block.

Are you filtering your block to only display on certain pages? It could be that the block is not displaying because of your filtering constraints.

Another thing to check is to make sure the region you have placed the block in exists on that particular page.