Call to undefined function node_load_multiple() function my_module_getcategory() {
  $nodes = node_load_multiple(db_query('SELECT nid FROM {node}')->fetchCol());
  $data = array();

  foreach ($node as $nid) {
    print $nid;
    $data[$nid] = drupal_render(node_view($nid, 'full'));
  }

  $json = drupal_json_encode($data);
}

The above code give me the following error:

  Fatal error: Call to undefined function node_load_multiple() in C:\xampp\htdocs\new_task\sites\all\modules\my_module\my_module.module on line 5

How can I fix this error? I verified the Node module is enabled.

If you call node_load_multiple() from hook_boot(), then the function is not found because at the time hook_boot() is invoked, only the modules implementing it are loaded. Once Drupal completes the bootstrap, all the enabled modules are loaded, and you can call every function implemented by those modules.

The same is true when you call node_load_multiple() from your own PHP file that doesn't bootstrap Drupal before to call any Drupal functions.

Suppose that you have a example.php file that is invoked as http://example.com/example.php; if the file doesn't contain the following code, then Drupal will not bootstrap, and every Drupal function is not available.

define('DRUPAL_ROOT', getcwd());

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

In other cases, you should not get the error you are getting. The only possibility is that the node.module file got corrupted when it was copied, but at that point I would expect something else to not work too; for example, if the content of node.module is corrupted, and  node_load_multiple() is read as ode_load_multiple(), then you would get the same error when you are looking at a node page (e.g., http://example.com/node/1).

As side note, hook_boot() has been removed from Drupal 8; if you are using that hook in Drupal 7, you will need to change your code, since it would not work anymore with Drupal 8.


Retrieve authro/owner of term I am loading a term and trying to get the author or owner of the term, however I can not see any function under the Term Class

On the other hand I can see the translation author being present on the edit page.

Any way to retrieve author for Term?

This is not part of Drupal core. There's a module which provides this capability for D7,  Taxonomy Term Author Info but it's not been officially ported to D8 although there is an unofficial port at https://github.com/worthingtonlibraries/term_authoring_info


Fatal error: Call to a member function execute() on a non-object - db_select() addExpression I'm fixing up a module and I have the following db_select() code, but I'm getting the following error:

  Fatal error: Call to a member function execute() on a non-object in
  /var/www/xxx/sites/all/modules/xxx/xxx.module on line 414

I think it has something to do with the addExpression line, but I'm unsure of what this line does or what is the equivalent of addExpression in sql? What is MAX(poss), poss -- mean?

$query_poss = db_select('saved_lists', 'saved_lists')
  ->condition('saved_lists.lid', $lid)
  ->addExpression('MAX(poss)', 'poss')
  ->execute()
  ->fetchField();

The addExpression method returns the unique alias that was assigned for this expression, and thus cannot be chained.

Please look at this example and the document.

$q = db_select('parser_subtasks', 'st')
 ->condition('QueueID', $task['ID'])
 ->condition('IsDone', 0);
$q->addExpression('MIN(Delay)');
$min_time = $q->execute()->fetchField();


How to change the order of form elements in a modal user login form I have a modal form for user login. I want to rearrange the links. I enabled captcha for user login form. Now i want to display 'Create New Account' and 'Forget Password' links to be displayed below the 'Login' submit button. I need help on how to do this. Thanks in advance.

@jags: Always make sure to mention what version of Drupal you are working on as the answers could be sightly different for different Drupal versions.

You essentially have to change the HTML that gets generated to render the form. Such 'theme override' can be done at multiple places. In your case a good place to do so is the theme layer. Assuming that you are on version 7, the below is what you will need to do -

In your theme's directory edit the file called 'template.php' to register a new theme function

/**
 * Implementation of HOOK_theme().
 */
function THEME_NAME_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  // Add your theme hooks like this:
  $hooks['FORM_ID_FOR_THE_FORM_YOU_WISH_TO_EDIT'] = array(
      'arguments' => array('form' => NULL),
    );
  return $hooks;
}

Now create the new theme function and make changes to the '#weight' property of the desired elements to change the order in which they appear in the form

function cio_st_FORM_ID_FOR_THE_FORM_YOU_WISH_TO_EDIT($form) {
  dsm($form); // This line will show you the content of $form and help you know which attribute you would like to edit. You will be able to use this function only if the devel module is turned on.

  // Make the changes in the '#weight' attribute of the desired elements to change the order in which they get rendered.

  return drupal_render($form);
}

The line dsm($form) is just for your help. Do not forget to remove/comment it once you are done with the changes.
NOTE You will be required to clear you sites theme registry cache to see the changes take affect.

Hope this helps :-)


Enter OG audience to a node with Rules How to add a specific Organic Group to a node in the action-step with rules (7.2)?

I can't figure out which action and which options i should use. Now i've something like

**action**
Set a data value
Parameter: Data: [node:og-group-ref:0]

But this isn't correct. How can i give the og-group-ref the correct value (the OG is in this case nid 180).

This is not the correct answer, but i found a different way. If the og_group_ref is set to checkboxes (these checkboxes are essential) (look at admin/structure/types/manage/[YOURCONTENTTYPE]/fields/og_group_ref), you can set the default audience.
Now i just hide the field 'audience' for certain roles and new nodes are saved to the right OG.

Again, this isn't the way i asked to do it with rules. When someone knows the right answer how to do it, i'm eager to hear it.


Hide path on frontpage redirect In a custom module i'm using an EventSubscriber to redirect different people to different frontpages. Below is the simplified code I'm using.
//GET PATH
$nid = 1;
$domain_url = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid);

//FRONTPAGE REDIRECT
$response = new RedirectResponse($domain_url);
$event->setResponse($response);

The module is working but there is one detail I can't seem to solve.
For example on my website domain.com I have node/1 that has an alias path /home.
When going to domain.com it is, because of my module as expected, redirected to domain.com/home. But what I want is the url not to show the home part. Is it possible to show the content of /home but keeping the url domain.com?

You can add the path to your homepage from admin/config/system/site-information
And replace /node/1 to /home.
You don't need an even subscriber to do that.


Style the reset password link I want to give the reset password link a different class so I can style it. How can I do this in drupal 7? my layout here http://www.lusciousanime.com/

If you mean the link in the right hand login block I'm pretty sure you've already got enough surrounding CSS to target it without adding any more classes, e.g:

.block-user #user-login-form a { color: blue; }


In my checkboxes if i have a 0 value it select this checkbox I have in my form a type 'checkboxes' form.

    // Form for the severity checkboxes.
    $kkkk_severity_levels = variable_get('kkkk_severity_levels', array());

    // Declare empty options array.
    $kkkk_severity_options = array();

    // Loop through each severity level and push to options array for form.
    foreach (watchdog_severity_levels() as $number_select => $severity) {
      $kkkk_severity_options[$number_select] = drupal_ucfirst(
        $severity);
    }

    // Checkboxes form.
    $form['kkkk_severity_levels'] = array(
      '#type'          => 'checkboxes',
      '#title'         => t('Type of log messages'),
      '#options'       => $kkkk_severity_options,
      '#default_value' => array_values($kkkk_severity_levels),
      '#required'      => TRUE,
    );

In these lines of code the watchdog_emergency has a key 0 so when i select something from checkboxes i take selected also emergency always as it gets me out : e.g if i select 'info' with key 6 it gets me out:

6 (String, 1 characters ) 6
0 (Integer) 0
1 (Integer) 0
2 (Integer) 0
3 (Integer) 0
4 (Integer) 0
5 (Integer) 0

7 (Integer) 0
and so it selects also the 'emergency' with key as 0... How I can solve this problem?

That's how the form API handles multiple selections for form elements.

You can easily solve it with standard language features:

$selected = array_filter($form_state['values']['kkkk_security_levels']);


Remove the language prefix from the file URL We have a multilingual site on Drupal 6. which seems to work fine, we created a rotor view on the default language (en). This views looks great on default language which loads without any language prefix on url.

But when we switch to any other language (example fr) the views images doesn't load because the file path it queries for is prefixed with language code. I have tried the same on drupal 7 it works outof the box. But not sure if we can do this in drupal 6. I have tried couple of module like pathologic, redirect module but doesn't seem to help in my case.

File path for default language: example.com/sites/all/files/test.jpg

File path for other language:  example.com/fr/sites/all/files/test.jpg  [which doesn't exists on server]

I have fixed this issue now, since the site was on nginx, I have written the redirect rule which removes language prefix while fetching files.

Insert this line in your server configuration:

rewrite ^/fr(/.*)$ $1 last;

If your site is on Apache you can add redirect rule on your server configuration or on .htaccess file.

RewriteEngine on
RewriteRule ^fr/(.*)$ $1


Selectively purging views from varnish cache We are trying to optimize our site's performance with Varnish together with the Cache Expiration module to selectively purge only the updated content from varnish.

However, one problem has come up, since we are listing content with Views, the expire module has no way of knowing which pages the updated content is listed on, and can't purge these at the same time the node url gets purged.

I guess we could purge all content from Varnish at regular intervals using cron, but that would also remove lots of perfectly valid content from the cache.  Has anyone manage to solve this in a nice way?

If the views are blocks you can use something like http://drupal.org/project/block_refresh and set a short expiration for the ajax callback that module uses.

If you want to get more advanced, you could strip the JS stuff out of that module and use its ajax callback, then use edge-side includes to have varnish pull in the block content dynamically.


How to pass extra information to search results page using hook node_api I want to show some extra information on the search result page in Drupal. I want to implement it in a module (and not in the theme).

I am using this code in my custom module:

function custommodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch ($op){
     case 'search result':
      return 'TEST';
      break;
    }

When I debug the statement, the line return 'Test' is executed.
I would expect this extra information to show up at: search-result.tpl.php in the variable $info.

However this extra information is not included. Has anyone got a clue how to pass this extra information so it shows up at the result page?

You could try this

<?php

function your_custom_module_name_preprocess_search_results(&$variables){
    $var['info'] = 'the_value_you_want_to_include';
}
?>

Now you can use the variable $info in search-result.tpl.php.


Show Block when Listing one Content type I have a silly question, i have one content type "ABC" and i have create a view page for listing all contents of that type with path "/abc". Next, i create a block which is listing all content of type "DEF", and configure the block "DEF" to show only when i'm listing the content "ABC", but not work.

Only work when i'm configure the block and put on "pages" restriction page like "/abc" path.

I'm doing something very wrong.

Any hint?

Please follow these instructions carefully:

1) Go to /admin/structure/block and click on "Pleace block" button in the region you want to add your view block, for example "Content" region.

2) Now you will see at least three tabs:"Content types", "Pages", "Roles"

3) In tab "Content types" select "DEF" type content

4) Be sure on tab "Pages" is selected the radio button option "Show for the listed pages", leave empty the text area on this tab.

5) Save block.

Hope this help.


Send out mails to registered users after certain time period When a user registers in my site(drupal 6) they will receive a welcome mail.I would like to send out mails to registered users after some time period (say for example,2 months),so the newly registered users will receive mail after two months from their date of registration.I tried Rules module but the users receives mail as soon as they registered.Is there any module to implement this?Anyone could help me?

you can use hook_cron() to send email using drupal_mail() and then comparing current date with the published date (timestamp of two dates) in the hook_node.
If current_date is equal to (published_date + 2 months) then send email


Why is user_role_change_permissions() throwing an error? I want to change the permission of anonymous user to view content hits only for a blog section. I came across user_role_change_permissions(), but it is throwing an error when I use the following code.

 if ($user->uid == "0") {
   $custom_role = user_role_load_by_name('anonymous user');
   $custom_rid = $custom_role->rid;
   $custom_permissions = array(
     'view content hits' => TRUE,
   );
  user_role_change_permissions($custom_rid, $custom_permissions);
 }

The error I get is the following:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot be null: INSERT INTO {role_permission} (rid, permission, module) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => view content hits [:db_insert_placeholder_2] => ) in user_role_grant_permissions() (line 3154 of C:\xampp\htdocs\capacad\modules\user\user.module).

  Notice: Undefined index: view content hits in user_role_grant_permissions() (line 3152 of C:\xampp\htdocs\capacad\modules\user\user.module).

I tried also with user_role_grant_permissions(), but it doesn't work too.

How do I set a new permission for a role?

It should be like this:

if($user->uid == "0"){
  $custom_role = user_role_load_by_name('anonymous user');
  $custom_rid = $custom_role->rid;
  $custom_permissions = array('view content hits');
  user_role_change_permissions($custom_rid, $custom_permissions);
 }

Here you have given

  $custom_permissions = array(
      'view content hits' => TRUE,   );

TRUE should not be there.


Iterate through multiple value content field in Twig template I need to take control over the rendering of a field_admin_tags field in a node.html.twig template.

This WORKS:

{{ content.field_admin_tags }} — Renders everything (label + all field values)
{{ content.field_admin_tags.0 }} — Renders only the first value in the field, and no label

PROBLEM: I have no control over the markup surrounding the tags, e.g.

...

.

So my idea was to iterate over the render array.

But that DOES NOT work:

{% for tag in content.field_admin_tags %}
  {{ tag }}
{% endfor %}

I get: Exception: Object of type Drupal\node\Entity\Node cannot be printed.

I think I'm iterating over the keys/values of the render array vs the items inside the field (if I print out an "X" in each loop, I get 20 X's while I only have two or three values in this field).

I'd like to iterate over content.field_admin_tags.0, content.field_admin_tags.1, etc.

Any idea how to fix this? Thanks.

Agree with 4k4 the field template is the best place, if you really want it in the entity template (e.g. node) you can do something like this:

{% for key, item in content.field_tags if key|first != '#' %}

{{ item }}

{% endfor %}

But honestly I think it's a bit ugly, the field template is the right place.


View is using original template rather than new custom template I have copied the views-view-grid.tpl.php file from the views module theme folder into my sites themes/my_theme/templates folder and renamed it views-view-grid--panel-pane.tpl.php, as was suggested in the 'Theme: Information' tab.  After a rescan and flushing of caches, the views-view-grid-panel-pane is bold in the tab, however, my changes are not reflected in the preview.  Am I missing a step?  I copy/pasted the file name, and triple check it, and it's bold, so I feel pretty confident that's not the issue.

Thank you

After a rescan and flushing of caches, the views-view-grid-panel-pane
  is bold in the tab, however, my changes are not reflected in the
  preview.

The view's preview does not use template files from your custom theme. It uses the admin theme.

Thus, you can add the template files to your admin theme. The Drupal default admin theme is called "Seven".

Another option would be to just go directly to the view page url or where the view block gets displayed and just ignore your view preview.


How do I implement a block suggesting other relevant content? I want to put a block in the left column on my products page, to suggest similar products. Can I do this with a block based on the "search API" module? Does this module allow to propose products in a block, similar to the viewed page?

Try to use Similar Entries module for this.

  Similar Entries provides lists of links to site content related to the current node being viewed. Links can be displayed in standard blocks or as part of custom views.


How to do it with views? I have two content types
BLOG and PROPERTIES

In BLOG, I have an entity reference field called "Related properties" that will point to the PROPERTIES content type.

Every BLOG node is gonna have a unique set of entity reference values i.e Content/Contents of PROPERTIES content type.

Now what I want is to list the entity referenced contents of content type PROPERTIES in a view with respect to the nid of the content of type BLOG.

How can I do this using Views?

Create a new view of type content

Then add contextual filter "Content: Nid". Here you can add different settings depending on your needs.

Under "Relationships" you should be able to select the entity reference field. This brings in all information about the referenced properties.

As fields you can now add any field from the references properties - just add this relationship


How can I add a separate template for the user login form? So I want to create a separate user login page for my website.

I create a twig file called page--user--login.html.twig which is great for the outer container. I still want to edit the form divand or the block div. But with debugger on It doesn't give me suggestions for creating a custom form or block twig file just for just the login form.

I can create individual form elements for the login but I want to edit the form div or block div itself without affecting anything else.

Any suggestions?

You can add a theme name suggestion in a hook_theme_suggestions_HOOK_alter:

function mytheme_theme_suggestions_form_alter(&$suggestions, $variables) {
  if ($variables['element']['#form_id'] == 'user_login_form') {
    $suggestions[] = 'form__user_login_form';
  }
}

If you want to add suggestions for form elements you need some more code. See the file themable_forms.module from the module Themable forms. This is the only code file in this module and it is a good example how you can approach this in form alter, preprocess form element and theme suggestions hooks.


Send email with custom tokens on event? I am trying to make a rule which when acted upon will send an email with custom details based on the rule arguments.

I made my rule event and that's all working fine it shows up, but when I add an action to "Send mail" and then look at all of the Replacement patterns non of my tokens show up, only site-information tokens show up.

Token Functions

/**
 * Implementation of hook_token_list()
 */
function mahjong_token_list($type = 'all') {
  if ($type == 'all' || $type == 'mahjong') {
    $tokens['mahjong'] = array(
      'package_name' => t('The name of the package'),
    );
  }

  return $tokens;
}

/**
 * Implementation of hook token api
 */
function mahjong_token_values($type, $object = NULL, $options = array()) {
  $tokens = array();
  var_dump($object);
  if ($object) {
    if ($type == 'mahjong') {
      $tokens = array(
        'user_name' => $object->name,
        'user_email' => $object->email,
        'user_score' => $object->score,
      );
    }
  }

  return $tokens;
}

Rules Function

function mahjong_rules_event_info() {
  return array(
    'mahjong_won' => array(
      'label' => t('A person won the mahjong game.'),
      'module' => 'mahjong',
      'group' => 'Rules',
      'arguments' => array(
        'user' => array('type' => 'mahjong', 'label' => t('The user who won the mahjong game.')),
      ),
    ),
  );
}

What am I doing wrong? How can I get the data from the rules argument pass to the action to send an email?

If "mahjong" is just an arbitrary object type, you need to declare it to Rules using hook_rules_data_info and specify the "token type" so that Rules knows what to pass to the token API.

But if the "mahjong" object is a Drupal User entity, you shouldn't need to implement hook_token_* at all.

Instead, when you define your Rules event, the argument should be of type "user". Rules will then know what fields are defined on the entity.


Form validation after drupal_build_form in hook_node_view In hook_node_view of one node I add a node form of a different content type as follows:

global $user;
$node_form = (object) array('uid' => $user->uid,
                            'name' => (isset($user->name) ? $user->name : ''),
                            'type' => 'my_type',
                            'language' => LANGUAGE_NONE
                            );
//create form state
$form_state['build_info']['args'] = array($node_form);

form_load_include($form_state, 'inc', 'node', 'node.pages');
$form = drupal_build_form('my_type_node_form', $form_state);

//change default save button
$form['actions']['submit']['#value'] = t("Nice Save");
$form['#validate'][] = 'my_module_my_validate';

//hide few fields
if(!in_array('administrator', $account -> roles)) {
    $form['field_field_1']['#access'] = FALSE;
    $form['field_field_2']['#access'] = FALSE;
    $form['field_field_3']['#access'] = FALSE;
}

$node -> content['my_form'] = $form;

All of above works great. Form is nicely displayed, fields are hidden, submit button value is changed and additional validation handler seems to be added correctly as debug($form['#validate']) returs:

array (
  0 => 'node_form_validate',
  1 => 'my_module_my_validate',
)

default validation is trigged as one of the fields in embedded form is required and left empty Drupal as expected returns: My required filed field is required. Node is created just fine using this form.

The problem is that for some reason my custom validate handler is not called at all.

/*
 *
 */
function my_module_my_validate($form, &$form_state) {
    debug('test');
    form_set_error('', 'error');
}

Am I missing something? I could potentially use hook_form_alter but I would like to get this working correctly.

You do need a form alter. You're modifying the form array after it's already been built, which includes caching the form and processing the input.

  Form is nicely displayed, fields are hidden, submit button value is changed

Those are handled at render time, whereas the input processing (and therefore handler execution) are done at form build time. Or to put it another way, consider the form returned by drupal_build_form() as nothing more than a render array that happens to render a form. If you want a form array proper, you need to get the form via an alter (ie before drupal_process_form() is called on it).

You can use hook_form_FORM_ID_alter() if you want to target just one content type form, or hook_form_BASE_FORM_ID_alter() if you want to target multiple types or be dynamic. If you need to know within the form alter whether the form's embedded via a hook_node_view() you can pass that state via $form_state.


Disallow /node/ in robots.txt I have given alias to the above pages as

  www.example.com/node/123

(to)

  www.example.com/about

and

  www.example.com/node/145

(to)

  www.example.com/contact

When search with a keyword in google, google crawler takes this page as www.example.com/node/123 and not as  www.example.com/about. same in the case of contact page. Please advice me whether i can add Disallow : /node/ to my robots.txt to solve this issue. Will this affect my about and contact page from crawling. Will this affect only nids or the alias too. Thanks in advance.

Having you pages accesible both via /node/* and /somealias leads to duplicate content and should be avoided as this can cause an SEO penalty. Under normal circumstances you could take a look at the global redirect module

  GlobalRedirect is a simple module which…

  Checks the current URL for an alias and does a 301 redirect to it if
  it is not being used. ...

It saves you from alteting robots and comes with some additional benefits.

Related to your question:

Since they are different paths, blocking one does not affect the other. And as explained above it is advised to prevent crawlers from indexing both. It should be safe to block one of them.

However, for Google indexing your /node paths, they might be in use somewhere. So first check your existing links and make sure there is nothing linking to those paths. Then add it to robots. (If it is still in use when you block it, you risk certain parts of your site not getting indexed.)


Migrate from WordPress (with buddypress plugin) I have a Wordpress 3.2.1 site with many users, and BuddyPress plugin installed. I want to move all the users and profile fields, the BuddyPress comments, and the blog content into a fresh Drupal 7 website.

What is the easiest, or best way to do this?

I did a Wordpress import this summer into a Drupal 6 system.  While I ended up doing a manual import for a variety of reasons, a decent amount of my code was based on Wordpress Import.

This module has been suplamented by Wordpress Migrate which uses the Migrate framework.  Since you mentioned Drupal 7, this approach would be worth exploring.

Both of these use the WXR format, so you are likely to lose less data than with other methods, and you can generate the backup file right from the WP admin interface.

Personally, I would take a backup of your site (like with Backup and Migrate), and try out Wordpress Migrate before trying to use Feeds.

Keep in mind that Wordpress RSS and WXR files may not always be valid XML, so you may run into parsing issues.  I have had problems because of WP plugins that add embed code or <script> blocks directly into the post/page, and then WP doesn't wrap everything properly in a CDATA section.

It is also worth noting that you may end up losing any markup that would be the result of short-tags in the post/page body, and just import the sort-tag.


Drupal 7 Update Manager not working Update manager takes me to the page where I select the checkbox for the updates I need. I check the box of the module and then it downloads the update. After the download it tells me I should put my site in maintenance mode with a checkbox that is on by default. The button says "Continue" to install the updated module.

My problem lies after this point. No updates are installed and after clicking "Continue" I get booted to my home page with the message "Operating in maintenance mode. Go online."

So currently the only way to update my modules is manually. Update manager doesn't work for me. Any pointers as to why it behaves the way it does?

Does yoursitename.something/update.php runs after you put it your browser location.
I can only guess maybe your site hosting space is full or you might not have given update permission to the role by which you are updating the site.


Set the message field as not required in a custom contact form I have tried many things to set the message field as not required.

1-The more obvious in form_alter

$form['message']['widget'][0]['value']['#required']=false;
$form['message']['widget'][0]['#required']=false;
$form['message']['widget']['#required']=false;
$form['message']['#required']=false;

2-Set a white space as a value (if field is empty) in form_validate

$msg= $form_state->getValue('message');
if(!isset($msg['value'])){
    $form_state->setValue('message',
        [
            'value' => '  '
        ]
    );
}

3-Set not required in after build

function alter_contact_ds(&$form, FormStateInterface $form_state, $form_id)
{
    $form['#after_build'][] = '_remove_msg_required';
    ...
}
function _remove_msg_required($element){
    $element['message']['widget'][0]['value']['#required']=false;
    $element['message']['widget'][0]['#required']=false;
    $element['message']['widget']['#required']=false;
    $element['message']['#required']=false;
    return $element;
}

4- In form_alter, I have used the #state to set the required property

$form['message']['#states'] = ['required' => ['select[id="edit-object"]' => [
    'value' => 'info'
]]];
//Note that ['select[id="edit-object"]' => ['value' => 'info']]]
//is used succesfully on another field (but not the requied part)

The best I could get is not having the regular behavior explaining that the field must be completed (and no red asterix near the field to mark it as required)

But each time I press on the submit button, I get a drupal_set_message("This value could not be null",error) [freely translated from french]

SOLUTION:

Following the idea of Alireza Tabatabaeian, I could solve this problem by

1-Set the field as not required in form alter

$form['message']['widget'][0]['value']['#required'] = false;

2-Set my validation function de first one in form_alter

$form['#validate'] = ['my_validate_contact','::validateForm'];

3-In my validate function set the value of the field equal to a space if the field is empty (it is not really nice, but I could accept it)

$msg = $form_state->getValue('message');
if (! isset($msg['value'])) {
    $form_state->setValue('message', [
        [
            'value' => '  '
        ]
    ]);
}

I've solved this issue this way:

function hook_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'contact_message') {
    if (isset($fields['message']) && $fields['message'] instanceof BaseFieldDefinition) {
      /* @var BaseFieldDefinition $field */
      $field = &$fields['message'];
      $field->setRequired(FALSE);
    }
  }
}


What's the best way to put in a link to a translated node in a D8 template? There just has to be a better way to insert a link to an alternative translation than this:

function THEME_preprocess_node(&$variables) {

  $node = &$variables['node'];

  // Current language
  $current_language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $variables['current_language'] = $current_language;
  $variables['current_language_url'] = $node->toUrl()->toString();

  // If this is a multi-lingual node, get links to alternative language.
  $languages = $node->getTranslationLanguages();
  foreach ($languages AS $langcode => $language) {
    $node_ja = ($langcode == 'ja') ? $node->getTranslation('ja') : null;
    if ($node_ja && is_object($node_ja) && $current_language == 'en') {
      $node_url = $node_ja->toUrl()->toString();
      $variables['node_url_ja'] = $node_url;
      $variables['node_url_ja_translation'] = 'Japanese';
    }

    $node_en = ($langcode == 'en') ? $node->getTranslation('en') : null;
    if ($node_en && is_object($node_en) && $current_language == 'ja') {
      $node_url = $node_en->toUrl()->toString();
      $variables['node_url_en'] = $node_url;
      $variables['node_url_en_translation'] = 'English';
    }

  }

  // Display link to alternate translation.
  $variables['node_url_translation'] = ($current_language == 'en') ? $variables['node_url_ja_translation'] : $variables['node_url_en_translation'];

}

It works, but it's just not at all graceful. How should this be written?  I just want to put in a link like this into a templates/node.html.twig file:

{{ node_url_translation|raw }}

The easiest method of providing language switching links would be using the language manager's getLanguageSwitchLinks() method. However, this might - depending on your language settings - also provide fallback links, if the node is not translated to the target language. An abstract example:

use Drupal\Core\Language\LanguageInterface;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();
  $links = $language_manager->getLanguageSwitchLinks(LanguageInterface::TYPE_CONTENT, $node->toUrl());

  $variables['current_language'] = $current_language;
  $variables['translations'] = [
    '#theme' => 'links',
    '#links' => $links,
    '#set_active_class' => TRUE,
  ];
}

For your use case - to show links to translated content only -, your approach to using getTranslationLanguages() of the TranslatableInterface is on the right track.

But be aware, that it will return entity translation instances also for non-published - or otherwise limited - content translations, to which the current user may not have view access to. Hence, he will get an "Access denied" error after clicking the links.

Additionally, the code should be generic enough to allow for further languages being added using the admin UI in a later stage of the application's life-cycle, without having to touch your preprocessing/templates anymore.

Therefore some suggested improvements for your solution:

Check, whether the current user has access to the translation.
Avoid using hard-coded language identifiers. As I suppose you did so to not add further links for the current language, you should use your $current_language variable to do the checks.
Avoid using hard-coded language link labels. Consider using \Drupal\Core\Language::getName() instead.
Use a list of language links instead of a dedicated variable for each language, and pass that list to the template. This way you can just iterate over the links.
Don't return markup (the links) from within your preprocess hook, but allow creating the links within the templates.

This sums up to something like this:

use Drupal\Core\Template\Attribute;

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  $language_manager = \Drupal::languageManager();
  $current_language = $language_manager->getCurrentLanguage()->getId();

  $links = [];
  foreach ($node->getTranslationLanguages() as $langcode => $language) {
    // Skip any translation that cannot be viewed.
    $translation = $node->getTranslation($langcode);
    if (!$translation->access('view', NULL, TRUE)->isAllowed()) {
      continue;
    }
    // Get URL of the translation.
    $url = $node->toUrl('canonical')
      ->setOption('language', $language)
      ->setAbsolute()
      ->toString();
    // Optionally provide an 'active' class.
    $classes = [];
    if ($langcode == $current_language) {
      $classes[] = 'active';
    }
    // Construct information for a link.
    $link = [
      'language' => $langcode,
      'is_current' => $langcode == $current_language,
      'url' => $url,
      'title' => $language->getName(),
      'attributes' => new Attribute(['class' => $classes]),
    ];
    $links[] = $link;
  }

  $variables['current_language'] = $current_language;
  $variables['translations'] = $links;
}

In your template, you can then create the links like this:

{% if translations %}
  {% for item in translations %}
    {# Optionally skip current language #}
    {% if not item.is_current %}
      {{ item.title }}
    {% endif %}
  {% endfor %}
{% endif %}


Is there any way to display an image as background? I have a picture in a field and I want to be displayed in its exact look but as a CSS background... is this even possible? Is there any mechanism how does that?

You can use Background Images and Background Images Formatter modules to achieve this. Note in the Background Images Formatter description that it can take images from a field and add it to the background.

Otherwise you can create your own module that generates the appropriate css and adds it to the page with drupal_add_css


How to bulk/mass import/create webform components? Apart from his module : webform_auto_field, is there any way to bulk import or create multiple components in a webform. Even if it is one type of component at a time.

I've already googled on, and didn't get sufficient response..

Thank you all in advance...

Maybe the Webform Share module can solve your problem?


How to debug invalid plugins derived by the GraphQL module? I'm currently using the GraphQL module in combination with the Brightcove module.

When I visit /graphql/explorer, all I'm getting is a totally white screen. When I visit /graphql/voyager, I end up with an "invalid syntax" error. My supposition is that one of the derived Brightcove plugins has invalid definitions. Unfortunately, GraphQL doesn't seem to throw any sort of error message.

Any ideas on how I can debug GraphQL?

I am a little late but you can enable dblog core module and see if any errors are printed to the watchdog table by running drush wd-show after an attempt to access the explorer page.


OG Subgroups - call function _og_subgroups_get_inherited_users I am trying to create a custom rule for OG Subgroups to email the members of a subgroup when content is added to it.

In og_subgroups.common.inc I can see the function I wish to use to return the inherited users of a subgroup

function _og_subgroups_get_inherited_users($group_type, $group_id, $states = array(OG_STATE_ACTIVE))

In my custom rule action I'm not sure what I should be passing to the function as $group_type and $group_id parameters. I have tried things like "node" and the NID of the group:

$array = _og_subgroups_get_inherited_users("node", 27);

Once I get it working with a hardcoded node e.g. node 27 I will then try to pass the details of the parent groupd that content has been added to.

I'm using OG Subgroups 7.x-2.0-beta1. For the full background into why I'm creating this custom rule action you can see my original drupal answers question

I was able to solve this by creating a custom og_subgroups.rules.inc file. For details of this see my answer in: Email all Organic Group members when a subgroup is created

The line in question above needed to be:

$inherited_users = _og_subgroups_get_inherited_users("node", $nid);


Remove fields from dialog window How can I remove fields from the CKEditor dialog window?
In my case, I need to remove the "Caption" field from the "Table Properties" window. How can I do that?

The solution is simple: remove the caption tag from the allowed HTML tags in "/admin/config/content/formats" :-)


How do I use a referenced entity in a Views contextual filter? I'm building a media server for my university.   I have an "artist" content type for each performer, and then a 'track' content type for individual track (there are no 'albums', BTW).  For each track, you can select the artist in edit mode, using an Entity Reference.  So far so good!

On each Artist page is a block view with a table listing that artist's songs (the filter is 'show all tracks with a contextual filter of "artist").  Still good!

On each track page, I want to show "all tracks by this artist" as a table.   I've tried "artist" as the contextual filter, and even tried both "referencing entity" and "referenced entity" as relationships, to no avail.    If I put an artist NID in to the fixed value in the 'artist' contextual filter, it works fine.  But I'm pulling my hair out, trying to get the artist to dynamically be referenced by the block's contextual filter, using the tracks 'artist' entity reference.

Am I missing something here?  It really seems like it shouldn't be that hard.    Thanks in advance!

For the curious, with Huelfe's help I solved it with a custom PHP code, in order to obtain the applicable NID for that contextual filter.  Seems like something that should be built in to Views already...!   I've successfully reused the string or several other projects as well.


Drupal 8.2.5 no internal pages on fresh install Just installed Drupal 8 on a Ubuntu 16.04 server.   Everything looked great until the final install and then there was no stylesheets on the site and all of the links give an

The requested URL /admin was not found on this server.

Apache/2.4.18 (Ubuntu) Server  ###########.net Port 80

error.  This error persists for all linked pages.

I installed it previously on the server with the same issue, except before it had the Bartik theme.   I realized I had built the database on it incorrectly and it was faster to reimage the server then go in and delete everything and put things back proper, plus I figured that way it would be fresh.

Thanks in advance for the help,
Joey

Try to clear caches using drush from the terminal.

drush cr

Also uncheck the following under Bandwidth optimization

External resources can be optimized automatically, which can reduce both the size and number of requests made to your website.

Aggregate CSS files

Aggregate JavaScript files

from
http://drupal.local/admin/config/development/performance


Extra checkbox in tableselect rows I have a list form in a module, which is giving me three columns, the first of which is a checkbox column.

function popups_list_form($form, &$form_state){
        global $base_url;
        $header = array("Title", "Popup");

        $result = db_query("SELECT * FROM popups");
        }
        # build the table fields
        $rows = array();
        $options = array();
        $ppups = array();

        foreach ($result as $row){
            $rows[$row->popup_id] = array($row->title, $row->popup_org_name);
         }

        $form['table'] = array(
            '#type' => 'tableselect',
            '#header' => $header,
            '#options' => $rows,
            '#default_value' => $ppups,
            '#empty' => t('No Popups Available'),
        );
        return $form;
    }

Why is it happening?

That happens because you are using a #tableselect form element, which is clearly described as follows:

  A table created with a far left column of radios or checkboxes. Build the table headings and columns with the #headers property, and the rows with the #options property. See Adding checkboxes to a table for a full explanation.

What you are looking for is a table, which is a theme function. See for example the following code, used by Drupal core.

function aggregator_view() {
  $result = db_query('SELECT f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image, f.block, COUNT(i.iid) AS items FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.hash, f.etag, f.modified, f.image, f.block ORDER BY f.title');

  $output = '
' . t('Feed overview') . '
';

  $header = array(
    t('Title'),
    t('Items'),
    t('Last update'),
    t('Next update'),
    array(
      'data' => t('Operations'),
      'colspan' => '3',
    ),
  );
  $rows = array();
  foreach ($result as $feed) {
    $rows[] = array(
      l($feed->title, "aggregator/sources/$feed->fid"),
      format_plural($feed->items, '1 item', '@count items'),
      ($feed->checked ? t('@time ago', array('@time' => format_interval(REQUEST_TIME - $feed->checked))) : t('never')),
      ($feed->checked && $feed->refresh ? t('%time left', array('%time' => format_interval($feed->checked + $feed->refresh - REQUEST_TIME))) : t('never')),
      l(t('edit'), "admin/config/services/aggregator/edit/feed/$feed->fid"),
      l(t('remove items'), "admin/config/services/aggregator/remove/$feed->fid"),
      l(t('update items'), "admin/config/services/aggregator/update/$feed->fid", array('query' => array('token' => drupal_get_token("aggregator/update/$feed->fid")))),
    );
  }
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No feeds available. Add feed.', array('@link' => url('admin/config/services/aggregator/add/feed')))));

  $result = db_query('SELECT c.cid, c.title, COUNT(ci.iid) as items FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid GROUP BY c.cid, c.title ORDER BY title');

  $output .= '
' . t('Category overview') . '
';

  $header = array(t('Title'), t('Items'), t('Operations'));
  $rows = array();
  foreach ($result as $category) {
    $rows[] = array(l($category->title, "aggregator/categories/$category->cid"), format_plural($category->items, '1 item', '@count items'), l(t('edit'), "admin/config/services/aggregator/edit/category/$category->cid"));
  }
  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No categories available. Add category.', array('@link' => url('admin/config/services/aggregator/add/category')))));

  return $output;
}

In your case, your code should simply be similar to the following one. (See also the comments in the code.)

function popups_list_form($form, &$form_state) {
  // This variable is never used; remove it.
  // global $base_url;

  $header = array("Title", "Popup");
  $result = db_query("SELECT * FROM popups");

  // The following bracket is wrong placed. Remove it from your code.
  // }

  $rows = array();

  foreach ($result as $row) {
    $rows[] = array($row->title, $row->popup_org_name);
  }

  $form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No Popups Available'),
  );

  return $form;
}


Available updates report does not list all available module updates I just noticed that the page admin/reports/updates highlights subsequent modules as I proceed with the upgrades. For example, initially the Webform and Token modules got the yellowish highlight, and then when I applied the updates to those two, refreshing the page highlighted subsequent modules, say: Date and Rules.

So, is there a particular logic in which the suggestions are made? And, can one get a COMPLETE list of update candidates at one shot?

In Drupal 7, two methods are used to fetch update information. One uses a setting update_max_fetch_time which is set to 5 seconds by default. On each cron run - whether from the server's cron or triggered by a visitor (poormanscron) - or page refresh of admin/reports/updates, this value is used. Not every module's status can be fetched within those 5 seconds, which is what you're seeing.

If you use the 'Check manually' link from the 'Available updates' page (admin/reports/updates/check), a batch operation is used instead, which should process all modules. There are however also reports that this doesn't always work correctly (Failed to get available update data for [number] projects message, you would then see the status of some modules in a grey box). You may also have to clear Drupal's cache first for this to work correctly.

The best thing to do is probably to set up a cron job to run each hour (for example). This will progressively keep the status of all modules updated.

Another workaround would be to override the update_max_fetch_time value and set it to e.g. 30 seconds (you can set $conf['update_max_fetch_time'] = 30; in settings.php, or with Drush do drush vset update_max_fetch_time 30). But if a cron run is then triggered by poormanscron, this could lead to a long page loading time.

This is from issue 952394 (still open).


Videos Stored in D7-s private file system do not play on Android devices I have .mp4 video files that I store on my D7 site's Private File system. I am using Video JS module for videos.
I am having issues on playing them on devices (Phone, Tablet) running Android OS.
Does anyone have a solution for this?

I had the same issue on iOS platform, the fix was using Resumable Downloads module for iOS.
For Android the problem still exists.

To make it work on android device you need to pass .webm format along with .mp4 of the same video. Please check sample shown below:

<video id="my_vid_id" class="video-js vjs-default-skin" controls preload="auto" width="640" height="264" poster="poster.png" data-setup='{}'>
   <source src="movie.mp4" type='video/mp4' />
   <source src="movie.webm" type='video/webm' />
</video>


No block to display at block settings in any contributed theme I am trying to use Simplenews module for newsletter, but there is no block to display at block setting in any contributed theme after enabling the module.

However it's show when I activate the core theme (Bartik).

My problem is if I use contributed theme, there is no block of Simplenews module for enable the block on the front-end (on the block setting page).

What should I do in order the block is displayed?

Go to the Block Layout page at /admin/structure/block, then Place a Block in the selected region and select Simplenews subscription. Once saved, the block should be available.

Source: Simplenews on Drupal 8 - subscription block.


Drupal Database Join I am creating a content type in Drupal - a content management system for our business rules.  This content type will ultimately contain about 40 fields.  I notice that for each field I create for the content, Drupal creates a table in MySQL.

It sounds like when I go to query the content in MySQL from a remote system using, say, JDBC, will I need to create a query joining 40 or so tables?

Does that sound right?  Can I be doing something wrong?  I cannot believe that a query, even with adequate indexes in place, would be performant when 40 tables are joined together.

40 fields on a single content type sounds a lot to me, although I'm aware of sites with a great deal more.

The very first thing you probably want to to, is use Entity Cache which should significantly reduce the query complexity for you, though honestly I haven't examined the module in detail.
Aggresively cache higher up the chain as well. Varnish, Page manager and Cache actions are all your friends here.
Is it possible for you to meaningfully break down the content type into pieces? If you can identify parts of the content type that will not always be necessary, use a Relation to a second content type. At the price of two optional extra joins, you can potentially skip a lot of them.
Still no luck? Define your own content type where all your data columns are properties instead of fields. This will store all data in the same table, at the cost of flexibility. It's probably also possible to make field api do the same thing with fields, but I have never even considered how to do that.


How to display both the taxonomy parent and child in a node? I have a simple two-level taxonomy in my site: parent level is responsible for the "kind of place" (wine bar, restaurant...), and the children terms make more precise disintctions (french, italian etc. for restaurants).

Now, if i display a taxononomy term, only the child appears (only "french", not "Restaurant French").

Is there any way to display both of them? I've found this http://drupal.org/node/1532198
but I am not sure how to use it.

Maybe there's a module that is more universal way, or a module that manages the display of the terms?

The answer you linked is correct. You need to write .tpl.php file and use provided code in place of default taxonomy renderer. In Drupal nodes belongs only to explicitly selected taxonomy element, not to it's parents. It was the design decision.


How to set programmatically Line Item Price? I just managed to add programmatically a line item (type: product) to my order.

I struggle to set the price for this item now.
How can I set the price at the same time when adding such an item (and having the total calculated accordingly)?

This is how I can successfully add a product:

 $product_id = XXX;

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
commerce_product_save( $product );

$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

I have struggled a bit with this, as have others apparently, but i found the solution in another thread.

Every time an order object is loaded the following function is fired:

commerce_cart_line_item_refresh()

In this function the unit price of the Line Item is set to the current price of the original product, so even if you change the unit price, when you create the line item, its changed back to the original price the next time you load the order object.

So rather than setting the unit price of a line item, when you create it, you have to do it every time it's refreshed - For this Drupal Commerce offers the following hook:

HOOK_commerce_cart_line_item_refresh($line_item, $order_wrapper)

Heres a coding example:

function YOUR_MODULE_commerce_cart_line_item_refresh($line_item, $order_wrapper){

$line_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

$label = $line_wrapper->line_item_label->value();

//Only alter price for a specific product type (you could choose other selection critirias here)
if ( $label == 'YOUR PRODUCT TYPE'){
    $new_price = calculate_new_price(); //I use a function to calculate a price, you could set a static price instead

    if(!empty($new_price)){
        $line_wrapper->commerce_unit_price->amount->set($new_price);
        $line_item->commerce_unit_price['und'][0]['data']['components'][0]['price']['amount'] = $new_price;
        $line_wrapper->save();
    }

}

}

function calculate_new_price(){

//Do what ever pricing logic you need here

//Here a static price of one dollor
$price = 100;

return $price;

}


How to change field value from a Views block? I have a content type named "Tasks" and it has a boolean field simple on/off checkbox. It controls tasks for done or not done.

I have a views block to list all task assigned to me.
I want to control this checkbox field from this block like this:

When I click the checkbox beside Task 1 it's value should change. How can I do that?

You can use Editable Views Module. The module provides a field to be editable when displaying using views.


field_get_items / value when creating new content I think I am about to lose my mind .. how in earths name do I get the value of a field in a widget during creation? I created a custom field widget, and during creation of new content I want to be able to do the following:

I want to create a custom field that I can attach to any content type. This custom field has two elements, a textfield to search for products in MySQL. And a selectbox. The selextbox should get filled with options that match the letters that the user types in the textfield.

I checked field_get_items and a lot more, but I just cannot get it. The code below has elements from a form that I made, so please just overlook those parts. I used DPM($something); everywhere trying to see if I can see the value of $element['searchfield'] anywhere ..

$items = field_get_items('node', $node, 'searchfield'); .. doesnt work, but from what I understand this is only to be used after the node is created .. ie to retrieve the added values, I NEED the values during runtime ...

/**
* Implements hook_field_widget_form().
*/
function field_zoekproduct_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  switch ($instance['widget']['type']) {
    case 'field_zoekproduct_field' :

      $element['searchfield'] = array(
        '#title' => t('Zoek naar een product'),
        '#type' => 'textfield',
        '#maxlength' => 115,
        '#size' => 55,
        '#weight' => 0,
'#default_value' => 'zoek...',
'#attributes' => array('onfocus' => "this.value = '';"),  //when textbox gets focus the default value will be removed
'#ajax' => array(
  'event' => 'change',
  'callback' => 'zoekproduct_zoek_getypte_text',
  'keypress' => true,
  //'effect' => 'fade',
  'wrapper' => 'dropdown-second-replace',
),
    );

// with the piece of code below in a form module I can get the value of the textfield in $selected and
therefor am able to fill my select with options from the database that match $selected .. now How do I do the same with a custom field????

$options_first = zoekproduct_maak_een_eerste_selectie();
$selected = isset($form_state['values']['searchfield']) ? $form_state['values']['searchfield'] : key($options_first);

$element['overzicht_producten'] = array(
'#type' => 'select',
'#title' => t('Overzicht producten'),
'#prefix' => '
',
'#suffix' => '
',
'#size'=>1,
'#validated' => TRUE,
'#options' => zoekproduct_zoek_naar_getypte_text($selected),
'#default_value' => isset($item['overzicht_producten']) ? $item['overzicht_producten'] : '',
'#ajax' => array(
  'event' => 'change',
  'callback' => 'zoekproductfield_selecteer_product',
  'wrapper' => 'find_product',
),
);

      break;
  }
  return $element;
}

One option would be to take advantage of states (see states and/or forms reference).

Here is an example... It's by no means perfect but hopefully it will give you an idea of how states work:

$options_1 = array('Option A', 'Option B', 'Option C');
$options_2 = array('Option D', 'Option E', 'Option F');
$element['overzicht_producten'][] = array(
  '#type' => 'select',
  '#title' => t('Overzicht producten'),
  '#options' => $options_1,
  '#states' => array(
    'visible' => array(
      // To make this select menu visible, type "Visible1" (no quotes) into the "searchfield" box.
      ':input[name="searchfield"]' => array('value' => 'Visible1'),
    ),
  ),
);
$element['overzicht_producten'][] = array(
  '#type' => 'select',
  '#title' => t('Overzicht producten'),
  '#options' => $options_2,
  '#states' => array(
    'visible' => array(
      // To make this select menu visible, type "Visible2" (no quotes) into the "searchfield" box.
      ':input[name="searchfield"]' => array('value' => 'Visible2'),
    ),
  ),
);

Hope that helps... :)


Create a view of the first entityreferenced child item from a multifield for a list of parent nodes I have a node type A containing a multifield of entityreferences to another node type B and using only the views admin interface I want to create a list of the first type B child entityreference on every node of type A.
I think its possible just can't quite figure out how to do it.
Thanks

We usually name the referencing nodes Children, and referenced nodes Parents (Children reference Parents), so I'll assume it applies here that you want to show the first Parent in a multivalue ER field.
You need to create a list of type A nodes in a Block Display, add the ER field and select to show only the one, first value under Multivalue settings for the field.
This will give you a list of A-type nodes that shows only the first B reference.
Now we need to filter out only the A node that we're currently viewing. This can be done through the ID Contextual filter (under Advanced View settings), configure it:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator: Content
Content type A
Set the option for the case when the argument doesn't validate, and all the other options, to something that makes sense to you.
When you add the Contextual filter, depending on what option you chose for when the argument doesn't validate, you may see no results any more. To bypass the Contextual filter enter all into the Preview field (unless you change that default).
You can test the Contextual filter with Views Preview. Enter the node ID of the A node into the Preview field. You should see only the one result in Views, the result relating to the A node with the ID you entered.
If you're seeing expected results save the Views and place the Block into a theme region, but don't forget to set the Context option on Block configuration too.


How to keep your Drupal 8 site synced with 8.x branch Is it practical to both A) develop/maintain a Drupal 8 alpha site and B) keep it up to date with the latest daily/hourly commits from the 8.x branch ?

If so, what would be your strategy to keep your site up to date, while maintaining the integrity/stability of the site itself?  How would you handle commits that affect the database?

My big concern is pulling in commits that affect the database structure.  If the database is affected in a particular commit, I'm assuming the site could easily break.

All those comments are correct. While running Drupal 8 for a simple blog, brochureware or similar site is a good idea to test it, doing anything more is most definitely not. Upgrading any code on a production site without testing it first is a bad idea, upgrading it with code which is openly declared to be possibly broken is a spectacularly bad one.

So: build you site, upgrade locally occassionally, be ready to export your content (somehow) and reimport it into the new one (somehow). Neither of these are supported. Writing migrate sources for D8 and a CSV source and target pair would be appreciated and quite possibly would work well for this scenario. You can find me in #drupal-migrate on freenode IRC should you want to work on this.


Generate Rate widget for specific user based on UID Basically, I'm going to be displaying a list of users who have voted on a node, but then show in a modal what their rating was. Now I can use the voting api to get what they voted, but I can't generate a display only widget for what they voted based on the user ID.

Any ideas? This is the function from the Rate module.

/**
 * Generate a widget.
 *
 * @param int $widget_id Widget id
 * @param string $content_type "node" or "comment"
 * @param int $content_id Node id (nid) or comment id (cid)
 * @param bool $teaser
 * @param bool $include_div
 * @return array
 */
function rate_generate_widget($widget_id, $content_type, $content_id, $mode = RATE_FULL, $include_div = TRUE, $just_voted = FALSE, $displayed = NULL) {}

What i understand that you want to display that Current logged in user Content ratings. for that you can use the (Votes) Votes: Current user (True) for filter

and if you want to display all the voted content User-wise than you can Make a relation with (Votes) Votes: User and remove the (Votes) Votes: Current user (True) as the following image.


Commerce without billing address We our developing a Drupal 8 Commerce website that does not need anything to do with addresses

The products are all virtual: membership and event tickets.
The billing is using PayPal express which takes care of billing address.

Therefore we don't want to prompt the customer to fill in an address, or store an address, or give them an "addresses" tab on their profile.  Please can anyone advise how to configure this scenario?

So far we have considered:

Edit the commerce flow.  The BillingInformation pane gets included via PaymentInformation.  If we remove PaymentInformation it does suppress the prompt for address and suppress the creation of a profile, but unfortunately it seems to stop the payment step from working properly.
Edit the customer profile form display to disable the address field.  This does suppress the prompt for an address, but we find that an empty profile is created for every order.
Delete the customer profile type.  We didn't try it yet because it seems likely to break the site as the Commerce core code has various hard-coded references to that profile type.

As an secondary question, we'd also prefer not to enter an address for the store as it does not have a physical address.  However the address seems to be mandatory and does not allow country=none.  We have entered a dummy value which seems to work as so far we haven't seen it used.  Can we trust the dummy address will never be used, and if so, would it be reasonable to say that the address ought to be an optional field?

The store address is used for calculating taxes. It doesn't have to be a physical store address, enter the address the business entity is registered to.

On the store edit form select a single "Allowed billing country".
That will hide the country selector on all of your address fields.

Then go to admin/config/people/profiles/manage/customer/fields/profile.customer.address and under "Field overrides" select "Hidden" for each field.
That will hide the other address subfields.

You need to be on the latest Commerce release for this to work.

(And yes, an empty profile with just the country code will be created for each order. There is no way around that currently)


Taxonomy view per vocabulary I want to create different view pages for different vocabulary types.

For each vocabulary I created a view and assigned a filter to limit to one vocabulary; as a page path I'm using taxonomy/term/% (on every view). It seems like only one view is working. For all others no details displayed (just an empty page is showing up).

Is this a valid approach? What can I do to display different taxonomy term pages for each vocabulary?

Also, the solution tvi doesn't work.

The best solution that I have been is the Taxonomy Display module.
It Can handle each view, no matter its URL! it's very powerful!

  The taxonomy display module allows administrative configurable term display pages. This allows administrators to override the default presentation of taxonomy term pages per vocabulary through the taxonomy term page's manage display form.


How to get values from $form_state with webform I'm using webform for submission and trying to simulate
GET parameters (though by default it uses POST).

Here's my code implementing hook_form_alter():

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $nid = 2;
  if ($form_id == 'webform_client_form_' . $nid) {
    $option['query'] = array(
        'name' => $form_state['values']['name'],
        'email' => $form_state['values']['email'],
        'gender' => $form_state['values']['gender'],
        'birthday' => $form_state['values']['birthday'],
        );
    $form['#action'] = url('path/to/myViewsPage', $option);
  }

Above code should take me to

'path/to/myViewsPage?name=tom&email=tom@gmail.com&gender=male&birthday=12/21/2013'

But I got following error:

  Undefined index: values in mymodule_form_alter()

Could someone tell me where to define the $form_state['values']? Isn't it predefined by Webform?

It's a bit hackish, but I think it would it be better if you set the path to your View in $form['#action'] and post the form directly to your View. Then on your Views page you grab the posted values from the form, in a contextual filter if you need that. In that way you also completely bypass the submission handling and nothing is saved.


Drupal Rules, create the SUM of a field decimal values I m running a drupal 7 installation and I need to create a special routine for my site.

I have 2 content types -> "Orders" and "Reports".

The "Order" content type has a field with decimal values called "final_value". Any user can create an order with different "final_value" each.

What I need is when a user creates a new report, a rule must trigger and calculate the SUM of all orders she created from the last time she logged in.

Any ideas??

You could enable PHP filter module (in core package), what will expose a 'run PHP' rule. There you could run some queries. Have a look at db_select and db_query for how to construct them (there are good advices in the comments as well.).

Proceed with caution though as you are communicating directly against the database. Sanitize the in- and outputs.

If it is only for display purposes, you could achieve a similar effect with Views and aggregation enabled. Enable aggregation in the advanced section. Add the final_value field, and select SUM. This is a much safer approach.

UPDATE

I suppose you are triggering the rule on the save event of the Order-node? In that case the Order is in the $node variable and you could go as follows;

$node->field_name = $calculated_value;
node_save($node);


Import REST API web Application to Drupal 7 I have a REST API web Application which is in core PHP. Now I want to change that application to Drupal 7. How to use those application in Drupal 7. I am new to REST API services..

You should use services module to create rest services in drupal 7. Simply install it and create end point by admin setting form. When will you create this then you can check your end point like this :

http://www.yoursite.com/{end-point}

If this will give success message then you successfully created end point and now you can move forward.

Services module will give some predefined service resource for user, node and comment etc. simply enable those and use them and if you want to create your own services then you should implement hook_services_resources hook, it will create a service resource. It will return an associative array which include api version, operations (create, delete, retrieve), actions etc. You can simply convert your services to drupal just follow some standard that is defined by services module and my recommendation is just look at any resource of this contrib module, for example look at user resource inside services module you will understand it.


Omega theme meta tag problem on Google I'm using Omega theme. But when search my site on Google, description is site menu items. I want change this area via spesific word.

So, open my template.php file and add this codes:

function site_page_alter($page) {
   $meta_description = array(
            '#type' => 'My Site Desc',
            '#tag' => 'My Site Desc',
            '#attributes' => array(
                'name' => 'My Site Desc',
                'content' =>  'My Site Desc'
            )
   );

drupal_add_html_head( $meta_description, 'My Site Desc' );
}

function manualMetaTags($path) {
    $description = "My Site Desc";
    $keywords    = "My Site Desc";
    print "<meta name='description' content='".$description."' />\n";
    print "<meta name='keywords' content='".$keywords."' />\n";
}

And add main.js:

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
<?php manualMetaTags($_GET['q']); ?>
  <?php print $styles; ?>
  <?php print $scripts; ?>
<script type="text/javascript">

After, send sitemap to Google. My description is seen but with menu items.

E.G.

My site desc on Google:

MAIN - NEWS - CONTACT

When add codes:

My Site Desc MAIN - NEWS - CONTACT

But i want only seen My Site Desc. How can i do it?

I'm afraid that's not really your decision to make...Google will take what it feels is the best representation of your site's description, whether that be the meta description tag or some text from elsewhere in the body.

The best you can do is make sure that you have <meta name="robots" content="noodp">   (which Google supports) somewhere in the document <head>. That will at least mean your title/description will come from somewhere in your page source, and not from the Open Directory Project (which is a distinct possibility otherwise).

The most important thing...don't expect instant results. Google will revisit your site when it's ready, and there's still no guarantee it will use exactly the text you want it to for the SERP description.

If you're not happy with that outcome, contact an SEO specialist who might be able to point you in the right direction.


How to get the custom class added to a view Views let people to add custom css class to a display. I'm looking to get this information and add to the body tag.

I try with this two functions and the dpm() function from devel:

views_get_view('name');
views_get_page_view();

But I'm not able to find the custom class that I add to the view.

Do you have any idea how to get this information?

If you only need to get this information, you can use template_preprocess_views_view

/**
 * Preprocess the primary theme implementation for a view.
 */
function YOURTHEME_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  switch ($view->name) {
    case 'your_view_name' :
      // print out the array with all options to see what you're dealing with
      drupal_set_message('<pre>' . print_r($view->display['display_name']->display_options, true) . '</pre>');
      break;
  }
}

But if you will need to override this custom class, you'll need to use hook_views_pre_render()

function YOURTHEME_views_pre_render(&$view) {

  switch ($view->name) {
    case 'name_of_your_view' :

      // override the view settings
      // for example: $view->field['fieldname']->options['label'] = 'Some label';

      break;
  }
}


By default, Shipping information fields should be shown In Drupal commerce kickstart Checkout page, by default Shipping information fields should show and the checkbox should uncheck. I tried JavaScript, but it is not working. How do I do this?

1) Go to Store Settings -> Checkout settings
2) Click the configure link for "Shipping information"
3) On the configure page,  uncheck the "Make copying information from this profile the default action, requiring users to uncheck a box on the checkout pane to enter a different address." checkbox.


Display comment box to the author of the node being referenced using panels I am creating a project that needs ONLY the author of a node being referenced AND the author of the referencing node to participate on comments on the referencing node, a sort of customer support Question/Answer system where ONLY the node author of the referencing node and the node author of the referenced node can participate in the comments section. I am implementing this with panels.

So far i can show the comment block only to the referencing node author (Question author) using the following code which checks to see if node-author-id = logged-in-user id:

global $user;
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

if($node->uid == $user->uid){
return TRUE;
} else {
return FALSE;
}

How do i also display this comment box to the author of the node being referenced?

Please note: The Question Content type and Answer Content type are two different content types

Thanks.

ps: I know about the Answers module as well as the Question/Answer modules. Somehow the best answer submodule included with the Answers7.x-4.0-rc2 module is able to let the author of the question flag an answer referencing his question as the best answer

Database query would help you.

function my_module_get_author_by_nid($node_nid) {
  $author = '';
  if (is_numeric($node_nid) && $node_nid != 0) {
    $uid = db_select('node', 'n')
        ->fields('n', array('uid'))
        ->condition('nid', $node_nid, '=')
        ->execute()
        ->fetchField();
    return $uid;
  }
}

// And then a slight change in your code

    global $user;
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      // Get the nid
      $nid = arg(1);

      // Load the node if you need to
      $node = node_load($nid);
    }

     // Get Reference Node Nid
    $reference_nid = $node->your_reference_field_name[$node->language][0]['target_id'];
    // Get Author for reference Node
   $reference_author =  my_module_get_author_by_nid($reference_nid);
    if($node->uid == $user->uid || $user->uid == $reference_author){
      return TRUE;
    } else {
      return FALSE;
    }


Accessing a field collection My content type uses a field collection (field_site_web) to allow users to enter multiple websites, consisting of a name (field_site_name) and an internet connection (field_link).

I want to use a foreach() loop to get those value, but I do not know how to access these fields. How can I do?

EDIT

how can I do to avoid the error in the line of the foreach? I tried so, but does not work:

if($fc_fields != false){
  // Extract the field collection item ids
  $ids = array();
  foreach ($fc_fields as $fc_field) {
    $ids[] = $fc_field['value'];
  }
}

The field collection is an entity in it's own right; the values stored against your node are a list of field collection item ids that you'll need to load manually to loop over. Something like this:

// Get the field collection items.
$fc_fields = field_get_items('node', $node, 'field_field_collection_field');

// Extract the field collection item ids
$ids = array();
foreach ($fc_fields as $fc_field) {
  $ids[] = $fc_field['value'];
}

// Load up the field collection items
$items = field_collection_item_load_multiple($ids);

// Loop through the items and extract field values
foreach ($items as $item) {
  $link_fields = field_get_items('field_collection_item', $item, 'field_link');
  $link = array_shift($link_fields);
  $url = $link['url'];

  $site_name_fields = field_get_items('field_collection_item', $item, 'field_site_name');
  $site_name = array_shift($site_name_fields);
  $name = $site_name['value'];
}


Add an item among those displayed in a Views block that links to the item creation page The goal:

How do I add the "Add new project" item as the first among the other projects shown in the Views block? The content would link to the project creation page (node/add/project) ?

Please suggest other methods/alternatives if this is not feasible.

Add a header to the view and style it to fit your needs.

You can chose between rendered entity: custom menu link or just add a textarea and enter your link. The first option might be better because it provides an access check.

You might need to customize some of the fields HTML within the fields style settings to make this work.


Dynamic Background based on field url Lets say I have a music site that a user can add a youtube URL in a box and then the video will play.
Is it possible to have the background of that page change based on search parameters in the field.
So if a user puts in a Daft Punk video, could I have my site query a website with fan art and load the fan art as the background of that page?

EDIT:
To elaborate more.

Popular media players (PLEX and XBMC) will often "srape" websites for information about tvshows, movies, and artists. They pull the content (biography, rating, fanart, etc.) from the different sites (imdb etc.) and display them in the media player.

I want to extend this functionality to my site.

Now this is where it could get complicated.

My website has an emfield that allows users to paste the URL's of different videos from youtube, vimeo and others that will display one video then create a playlist of the pending videos in the list.

Fortunately the emfield can also pull the artist and song title of the video from youtube.
I want to use this information to then query a search on a website such as fanart.tv and pull an image or even corresponding artist information and display said information on my site as the corresponding song is playing.

In short:
1. URL is entered
2. Emfield displays video, artist, and song title
3. Somehow a search is performed on a website to locate that same artist and display fanart and other artist biography information
4. Listen and learn.

You can do this but its probably more of a jquery problem than a Drupal one since you're changing the background of the page based on an asynchronous web call. Rough idea of how this would look:

attach an onsubmit handler to your form that would load the video from the url
add your logic to find the artist from this url (?) and then find the appropriate image
then modify the body background using this image, ex:

$('body').css('background-image', 'url(' + imageUrl + ')');


Hide node "edit" tab for certain content types and roles I am trying to hide node "edit" tab for certain content types and roles without removing or disabling access to the edit pages. An edit button is going to be created manually and displayed on node pages.

Used below snippet but it disables access to the edit pages too.

/**
* Set up a new permission for tabs.
* Grant access under admin -> user management -> permissions
*/
function mymodule_permission() {
  return array(
    'view hidden tabs' => array(
      'title' => t('Node tabs visibility'),
      'description' => t('Grant access to node tabs.'),
    ),
  );
}

/**
* Implementation of hook_menu_alter().
* Show/hide tabs according to permission settings.
*/
function mymodule_menu_alter(&$items) {
$items['node/%node/edit']['access callback'] = 'user_access';
$items['node/%node/edit']['access arguments'] = array('view hidden tabs');
}

Also tried using this code, which kinda works but disables edit tab on all content types and for all roles.

function mymodule_menu_alter(&$items) {
$items['node/%node/edit']['type'] = MENU_CALLBACK;
}

Obejective: Hide node "edit" tab for certain content types and roles in D7.

I had the same issue and could solve that using template_preprocess_page(&$variables).

Open template.php under [yoursite]/themes/[your-theme]

For example if you're using bartik theme and want to hide tabs (View and Edit) for Article content type for Editor role.

Paste the following code in your template.php

/**
 * Remove tabs on article content type
 */
function bartik_preprocess_page(&$variables, $hook)
{
    if (!empty($variables['node']) && $variables['node']->type == 'article' && in_array('editor', $variables['user']->  roles))
    {
    $to_be_removed = array('node/%/edit', 'node/%/view');
    foreach ($variables['tabs'] as $group_key =>$tab_group)
        {
            if (is_array($tab_group))
            {
                foreach ($tab_group as $key =>$tab)
                {
                    if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $to_be_removed))
                    {
                    unset($variables['tabs'][$group_key][$key]);
                    }
                }
            }
        }
    }
}

Clear your site cache and test.

This removes the View and Edit tabs on Article node pages for editor roles users. But they can access those pages via URL.

Hope this helps.


How to refresh block view of flags when the flag list is empty? Link operations issue I'm trying to have a simple block of flags for my site. I created a block view of content of my custom product type with a relationship to Flags: my_product (by any user).

The issue is have is that the block is only refreshed if I used the confirmation form link type. Is there a way to get the list to refresh (and the block to be updated) with using the other link types?

thanks in advance.

Since this tumbleweeded the answer is that there are a few modules that to time based refreshes of the view. Views by default, serves up content that ends up being static. Refreshing a view can be done a number of different AJAXY ways with custom code, but one of the more interesting involves using the Drupal node.js module and refreshing the view based on the execution of the flagging event. But using node.js you can have the view refreshed by server-side events (i.e. submissions by other users) all behind the scenes!.

Views Auto-Refresh is interesting but only has the on-click functionality in it's feature request que. I haven't developed a working implementation of this, but the node.js route is the one I would pursue at the moment.

A little more research turned up this little bit of jquery posted with a good explanation here Jquery views refresh

/**
 * @file
 * This JavaScript reacts to certain AJAX events on the view.
 */

jQuery(document).ready(function(){
  jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
})

/**
 * Function built on wireframe from
 * https://drupal.org/node/1781988#comment-6835168
 */
Drupal.behaviors.my_view_machine_name = {
  attach: function(context, settings) {
    if (Drupal.views !== undefined) {
      jQuery.each(Drupal.views.instances, function(i, view) {
        if (view.settings.view_name == "my_view_machine_name") {
          jQuery(document).ajaxComplete(function(event, xhr, settings){
            jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
            var response = JSON.parse(xhr.response);
            var resp_keys = Object.keys(response[0].settings.ajax);
            if (response[0].settings.ajax[resp_keys[0]].callback == "editablefields_form_update") {
              jQuery('#view-auto-refresh').click();
            }
          });
          view.$view.once('view-refresher', function() {
            var html = 'Refresh';
            view.$view.append(jQuery(html).each(jQuery.proxy(view.attachPagerLinkAjax, view)));
          });
          return false;
        }
      });

    }
  }
}


Taxonomy term parent widget alternative I have a huge hierarchical vocabulary of terms and adding a new child to a specific term can be hard using the default multi-value select list widget.

Can I use an autocomplete widget or -better- an entity browser instead?

I'm not sure if it would integrate with that widget automatically, but I really like Chosen. Doesn't work on mobile though.


Custom Content Type with Custom Fields creation I followed the examples given at: https://www.drupal.org/node/2629550  to create a new content type.  No problems there, the content type exists after I install the module.  However, when I uninstall, and re-install with the custom field yml files it says to have, I get errors saying that the field storage doesn't exists.   So I dug into core/modules/node/config/installand copied the field.storage.body and modified it for the field I wanted (username).  The field created, however, when I install the module now... It says:

Drupal\Core\Field\FieldException: Attempt to create a configurable field for a non-configurable field storage. in Drupal\field\Entity\FieldConfig->__construct() (line 94 of C:\xampp\htdocs\drupal-8.4.4\drupal-8.4.4\core\modules\field\src\Entity\FieldConfig.php).

Here is the yml for the custom content type:

#node.type.faculty_bio.yml
langcode: en
status: true
name: "Faculty Bio"
type: faculty_bio
description: "Faculty Bio"
help: ''
display_submitted: true

and the code for the custom field:

#field.field.node.faculty_bio.username.yml
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.body
    - node.type.faculty_bio
  module:
    - text
    - node
id: node.faculty_bio.username
field_name: field.storage.node.username
field_storage: username
entity_type: node
bundle: faculty_bio
label: Username
description: 'The username'
required: true
translatable: true
default_value: {}
default_value_callback: ''
settings:
  display_summary: true
field_type: text

I created the content type in a test environment, and populated all of the fields I wanted using the UI.  Then I went to the site configuration and did an export on the entire site. I pulled all of the yml files I needed for the fields and node types, and it works beautifully.


get taxonomy term from another database In a multisite installations where One site is as Master and has all the taxonomy terms defined. In second site i.e. Slave site, the content types are different but taxonomy terms are similar as of Master.

My quest is, how to get taxonomy terms from Master's database whenever taxonomy is called in Slave site, either be it content creation or Display.

The solution could be, db_set_active('Master') while any taxonomy term is called and change it to default db_set_active() after the taxonomy term is already displayed. But I am not sure where to place this.

Master has 4 taxonomy terms:

Bang
Dang
Chang
Nang

Slave has none, but while creating content in Slave there is a field type for Taxonomy reference, like:

Field Name: what is diyang?  (Taxonomy terms reference with 4 options in the select list) which should get the taxonomy term from Master.

Any hints or ideas?

You may need to share tables across database. You can read this note on how to share tables across instances. Though its not a good solution of what you want.

You can also use Services module to achieve this.


How to manually uninstall/purge modules? I have a module Media: YouTube which is being buggy when attempting to uninstall. I disabled it in the modules along with its dependencies, and when I go to the uninstall tab and perform the uninstall operation, it returns a blank screen. I go back to the module page, and it's still there (along with 3 other modules that need this one uninstalled first before the others can be removed).

Is there a general method of purging modules from the backend? I have full access to the server and database as well.

EDIT: Checked logs and found a PHP error:

  [Thu Jan 19 13:12:21 2012] [error] [client 192.168.xxx.xxx] PHP Fatal
  error:  Call to undefined function media_youtube_variable_default() in
  /var/www/drupal/sites/all/modules/media_youtube/media_youtube.install
  on line 19, referer:
  http://vulcan/drupal/?q=admin/modules/uninstall/confirm&render=overlay

Sounds like it's just a badly written module?

This is a known bug. Replace the module with the most recent DEV version, update, and then try uninstalling again


How to deal with this kind of node references, when creating a new instance of a content type? I'm new using Drupal, and I'm trying creating a database driven website in Drupal. I don't know what is the best way of doing the following:

I need to have three types of 'entities' (content types):

Worker
City
State

Every Worker lives in one and only one City, and every City is in one and only one State.

I could create those three contet types:

State
City, that will have a node reference to State
Worker, that will have a node reference to City

But...

When I someone creates a new Worker, I don't want Drupal to show a list with all the cities (because there could be cities with the same name in different states).

How could I add the feature of selecting first the State, and then the City, when creating a new Worker, or something like that that allows the user to differentiate?

Edit:

The module Dependent Fields would work in this case, but it forces me to add another field to the Worker content: A State. I don't want this, because it could be kind of redundant information (knowing the city of the worker, I can also know the state). Do you know what I mean?

I would create a taxonomy hierarchy that has nested State -> Cities. You can then provide a way for them to choose a state, and filter a drop-down by the parent taxonomy.

Hierarchical Select will do this for you.

If you need to create a content type for city, just apply the same taxonomy term to link the two together.

Kim


What module to edit theme css in my drupal site Is there a module that allows me to edit the theme css files within the drupal admin?

Live CSS is the module you are looking for:

  Edit CSS live within the page, and save the changes back to any css
  file if you have write access.

  Additionally, this module enables the ability to render and perform
  live editing of LESS stylesheets, included just like css files. Users
  without the live editing permission will still see properly rendered
  LESS displayed.


Showing referenced node in view I have a content type "Project" and a content type "Document". Using the "references" module, the "Document" content type relates to the "Project" content type.

I have a simple view that shows a list of all projects like so:

Project A
Project B
Project C

However, I want the related documents to show up in the list (the relation occurs from the document to the project, not the other way around):

Project A

Document J
Document K

Project B

Document L

Project C

Document M
Document N
Document O

I've looked at the eva module (seems to be the wrong tool for the job, but that may just be my inexperience with it.) I've tried using the built in "relationships" with views, but can't find if it's possible that way.

This can be done without installing module , simply you will use aggregation and group by Project .

Here is a great tutorial from nodeone.se of how to use agregation in drupal 7
See also this blog post , in the left image he is Grouping by the room(nodereference)


How To Display Image instead of Taxonomy name using Views to display my nodes? I Have Entity Module and already have a Taxonomy Vocabulary with terms and an Image Field created. Each term has a unique image.

I Have a Content Type with a Term Reference field set to allow multiple selections of my Vocabulary.

I now want to have my Nodes displayed in a Views Table, Title, Node Image, and Taxonomy terms as images rather than their names.

How do I make this possible? Here is a link to what the site currently is (HTML Table rather than a view - very limiting and slow for updating). http://dev.destinationsound.net/

The different color circles are what will be taxonomy terms.

Drupal 7

Note: This is not for a taxonomy term page but rather a list of nodes that have taxonomy terms associated with them.

Create a view of the appropriate nodes
Set the view output type to be "table"
Create a "relationship" in the view between node and taxonomy term
Now you can add the image field from the term to your views output
If you use multiple vocabularies, add a filter to select just the vocabulary you are interested in.

If you don't already have the imagecache module installed, I recommend it as it will let you control the size of the displayed image.


How to patch a file that is not in a module's git repo? I want to patch CheckoutCartEventSubscriber.php, which can be found in /web/modules/contrib/commerce/modules/checkout/src/EventSubscriber when installed via composer.
So I cloned Commerce from the drupal.org git repository, navigated to the /modules/checkout/src/, and found that there is no EventSubscriber directory.  All the other directories that can be found in the composer install exist except EventSubscriber.
The github repo browser doesn't show the EventSubscriber directory, either.
So where is this directory? How can I find the file to patch it?

That gihub repository looks to be outdated, as the last commit was made May 15, 2020
To see a module's repository, go to the projects page and click on on "Browse code repository"

Which will take you to the GitLab repository.

So where is this directory?

Well... that directory doesn't exist. Maybe your composer.json already contains a patch that creates it? OR someone manually added that folder and file, as that folder and file is not officially part of Commerce.


Ubercart refuses to believe it is updated I perpetualy get the "Security Update Needed" for Ubercart, even after updating.

The Update Modules page gives me: Ubercart (Security update)    Installed Version: 3.0  Recommended Version: 7.x-3.3 (Release notes)

But if I actually go to the modules pages, it shows that I have installed Ubercart 7.x-3.3

Is anything actually wrong? If not, is there any way to get rid of the constant update warning?

Thanks!

As requested by responses, here are the database system tables:

'uc_2checkout', 'sites/all/modules/ubercart/payment/uc_2checkout/uc_2checkout.module'
'uc_affiliate2', 'sites/all/modules/uc_affiliate2/uc_affiliate2.module'
'uc_ajax_admin', 'sites/all/modules/ubercart/uc_ajax_admin/uc_ajax_admin.module'
'uc_attribute', 'sites/all/modules/ubercart/uc_attribute/uc_attribute.module'
'uc_authorizenet', 'sites/all/modules/ubercart/payment/uc_authorizenet/uc_authorizenet.module'
'uc_cart', 'sites/all/modules/ubercart/uc_cart/uc_cart.module'
'uc_cart_links', 'sites/all/modules/ubercart/uc_cart_links/uc_cart_links.module'
'uc_catalog', 'sites/all/modules/ubercart/uc_catalog/uc_catalog.module'
'uc_credit', 'sites/all/modules/ubercart/payment/uc_credit/uc_credit.module'
'uc_cybersource', 'sites/all/modules/ubercart/payment/uc_cybersource/uc_cybersource.module'
'uc_file', 'sites/all/modules/ubercart/uc_file/uc_file.module'
'uc_flatrate', 'sites/all/modules/ubercart/shipping/uc_flatrate/uc_flatrate.module'
'uc_googleanalytics', 'sites/all/modules/ubercart/uc_googleanalytics/uc_googleanalytics.module'
'uc_google_checkout', 'sites/all/modules/ubercart/payment/uc_google_checkout/uc_google_checkout.module'
'uc_order', 'sites/all/modules/ubercart/uc_order/uc_order.module'
'uc_payment', 'sites/all/modules/ubercart/payment/uc_payment/uc_payment.module'
'uc_payment_pack', 'sites/all/modules/ubercart/payment/uc_payment_pack/uc_payment_pack.module'
'uc_paypal', 'sites/all/modules/ubercart/payment/uc_paypal/uc_paypal.module'
'uc_product', 'sites/all/modules/ubercart/uc_product/uc_product.module'
'uc_product_kit', 'sites/all/modules/ubercart/uc_product_kit/uc_product_kit.module'
'uc_quote', 'sites/all/modules/ubercart/shipping/uc_quote/uc_quote.module'
'uc_reports', 'sites/all/modules/ubercart/uc_reports/uc_reports.module'
'uc_roles', 'sites/all/modules/ubercart/uc_roles/uc_roles.module'
'uc_shipping', 'sites/all/modules/ubercart/shipping/uc_shipping/uc_shipping.module'
'uc_stock', 'sites/all/modules/ubercart/uc_stock/uc_stock.module'
'uc_store', 'sites/all/modules/ubercart/uc_store/uc_store.module'
'uc_taxes', 'sites/all/modules/ubercart/uc_taxes/uc_taxes.module'
'uc_tax_report', 'sites/all/modules/ubercart/uc_tax_report/uc_tax_report.module'
'uc_ups', 'sites/all/modules/ubercart/shipping/uc_ups/uc_ups.module'
'uc_usps', 'sites/all/modules/ubercart/shipping/uc_usps/uc_usps.module'
'uc_weightquote', 'sites/all/modules/ubercart/shipping/uc_weightquote/uc_weightquote.module'

It sounds like you may have two copies of ubercart in your drupal file system.

Check your database "system" table for the ubercart module path ( filename ).

e.g, raw SQL:

SELECT name, filename FROM system WHERE name LIKE 'uc_%';

Make sure the path matches what you expect.

If on linux, you could also run:

find /var/www/my-site -name 'uc_*' -type d

to list the uc_ folders ( type=directory )