Find legacy id of newly created node I have 3 non-drupal tables : items, item_actions, actions.

 items(id, title, body, published_at);
 item_actions(item_id, action_id);
 actions(id, name);

I were able to migrate items to drupal 7. Now i want to migrate actions but since i don't know the node_id of the newly migrated items just the legacy id it is throwing an error.
How do i find the node_id knowing the legacy_id so that it finds the right node and migrate related content.

$query = Database::getConnection('default', 'for_migration')
  ->select('actions', 'actions')
  ->fields('actions', array('id', 'name'))
  ->orderBy('id', 'DESC');
// Join values from the action_items.
 $query->leftJoin('action_items', 'ai', '(actions.id = ai.action_id)');
 $query->addField('ai', 'item_id', 'item_list');

Here is the error:

The referenced entity (node: 123456) is invalid.

update
   The migration was done with the migration module. So i had to write class migration and use queries like the one above to migrate to D7 the items table.
Can i create a table in the drupal DB and add the ids(old and new) for example: migrate_nodes(legacy_id, drupal_node_id) .
How do you capture the node_id?
I am new to drupal so this is still a learning process, thanks.

How did you migrate the content from the nond-drupal tables to nodes?  Module or custom code?

I would suggest a 'custom' migration routine/module (if it is a lot of data you can do this as a cron and/or batch job - that is a separate discussion).

Any case, in your custom routine, when you migrate each record (so read a record form your table and create a new node) from items and actions - you will be able to 'capture' the node id (nid) if the new node.  Save this value to your 'old' items/actions tables (new field required).  Now when you step through your item actions table you can use the nid saved in items and actions as reference values.


Why does my select list not translate to another language in Views? I have a View for Search in property, which has many fields and some of them are drop-downs (select lists).

When I switch the language to Arabic, everything is translated, but the drop-down is still in English (= default language).

I performed these steps:

I translated my select list in Manage fields and translate the options there
then I put them in Manage display to default translated.

But it's not working. Check the image for more details:

Any ideas about how to solve this problem?

I found the answer for this finally ...

After doing all the steps like the image that I attached before,
you should delete the old FILTER CRITERIA and add the New translated one to make the select list translate :

After doing so, the select list will be translated.


Load old cart order in commerce As I understand it commerce gets the users highest numbered order that is not yet completed (on the customers end) and uses that when a user adds an item to their cart or views their cart however I created a module that will allow a single user to create many carts (lets call these quotes) for their customers and i need a way for them to be able to go back and edit a previous quote or complete checkout on a previous quote right now i have a list of quotes in a view (any order that has not passed the checkout review page) and I want to add a column containing a link or button that will allow them to load that order number as the current cart I tried using a custom module function with a call to

commerce_cart_order_load(1);

(from a menu link) which is a previous order on my account however that appears to do nothing

Can anyone explain what I'm doing wrong/ what I need to do to make this work?

I would be perfectly happy doing this with views php if there is a function to set the users cart order that I'm missing, or by storing an OrderID hidden on the users profile

Thank You

After much playing and breaking I wrote some code in a custom module to save the current order to load to the users profile in a un-editable field

    function create_new_quote_menu() {
  $items = array();
  $items['create_new_quote'] = array(
    'title' => 'Start New Quote',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  $items['quotes/%/Load'] = array(   // assuming you want to make this dynamic
    'title' => 'Quotes',
    'page callback' => 'create_new_quote_LoadQuote',
    'page arguments' => array(1),   // references %, i'm assuming this is all dynamic
    'access arguments' => array('access content'),  // don't do this, whatever permission you want goes here
    'type' => MENU_CALLBACK
  );
  return $items;
}

function custom_callback () {
  global $user;
  $currentOID;
  $user_full = user_load($user->uid);
  $currentOID = commerce_cart_order_new($user->uid);

  $updateUserParams = (array) $user_full;
    $updateUserParams['field_currentcartorder'][LANGUAGE_NONE][0]['value'] = intval($currentOID->order_id);

    unset($fullUser->pass);
    unset($updateUserParams['pass']);

    user_save($user_full, $updateUserParams);
drupal_set_message(t('You have Created a New Quote #'). $currentOID->order_id,'status');
drupal_goto('moulding');
}

function create_new_quote_LoadQuote($quote_to_load) {
  global $user;
  $user_full = user_load($user->uid);

  $updateUserParams = (array) $user_full;
    $updateUserParams['field_currentcartorder'][LANGUAGE_NONE][0]['value'] = intval($quote_to_load);

    unset($fullUser->pass);
    unset($updateUserParams['pass']);

user_save($user_full, $updateUserParams);
drupal_set_message(t('You Loaded Quote #'). $quote_to_load,'status');
drupal_goto('quotes');
}

function create_new_quote_commerce_cart_order_id($uid) {
  global $user;
  $user_full = user_load($user->uid);
  $orderidentifier = $user_full->field_currentcartorder['und'][0]['value'];
  $orderidentifier = intval($orderidentifier);
  return $orderidentifier;
}

excuse my uncommented code and poor module name but I got it working this this code set so I can now create and change orders from my view by pasing Quotes/[orderid]/Load via a link


Specify the view mode when the node is displayed on modal window (ajax) Is possible to specify the view mode using the default modal Ajax functionality?

I'm using this and it works, but I need to theme the node in a different way inside the modal

Open Modal

The way you are doing it will always show the full view mode, as you are linking to the canonical entity page - which is the page to see the full view mode. If you want to show a different view mode, then I would suggest creating a custom route (or path if you're using D7), and in the callback, generate the output programmatically with the view mode you want. I'd probably use the following for the path:

node/[NID]/teaser

And in there I would output the teaser view mode.


Get file name upload via form api? I made a module to upload file in form, below is my code snippet, I am able to save file in proper folder but I want to get name of file uploaded so I can save it in database and make reference for it, I tried lots of thing but was not able to do it.

class MyForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'my_forms';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['resume'] = array(
        '#type' => 'managed_file',
        '#title' => t('File'),
        '#required' => TRUE,
        '#upload_validators'  => array(
            'file_validate_extensions' => array('pdf doc docx'),
            'file_validate_size' => array(25600000),
        ),
        '#upload_location' => 'public://myfile/',
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#button_type' => 'primary',
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
    public function validateForm(array &$form, FormStateInterface $form_state) {

    }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('name'))));
    // echo file name here
   }
}

The 'managed_file' FormElement plugin specifically stores the uploaded file as a managed file entity. This plugin stores the file entity id inside form state value as part of its validation.

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('name'))));
    // Use the fid to load the file entity. Unfortunately ManagedFile loads the file entity, but does not store it in form state.
    $fid = $form_state->getValue('resume');
    $file = \Drupal\file\Entity\File::load($fid);
    // Do something other than "echo" $file->getFilename() here.
  }


Removing the "File Browser Tab" for certain roles How would I go about removing the "File Browser Tab" from the user profile page for certain roles?

I only want authors, editors and administrators to be able to browse through and upload the files.

No need to do any coding. We can do it through admin dashboard itself.

Just go to below link:

  /admin/config/media/imce

Under "Role-profile assignments" just choose "Public Files" as NONE against a user role to whome you don't want to show the "File Browser".


WHERE NOT IN using an Array My issue here is that I would like to execute Query 1, return an array of values from Query 1, and then exclude those values from Query 2.  The reason for this is I will be performing an insert function in between (and want to leave my insert function untouched).

Query 1:

$notquery = db_select('uc_packages', 'p')
           ->fields('p', array('package_id'))
           ->condition('p.order_id', $order_id)
           ->condition('p.sid', NULL)
           ->execute()
           ->fetchAll();

foreach($notquery as $foo) {
  $notarr->pid = $foo;
}

Insert function:

uc_shipping_package_save($package);
...

Query 2:

$query = db_select('uc_packages', 'p')
             ->fields('p', array('package_id'))
             ->condition('p.order_id', $order_id)
             ->condition('p.sid', NULL)
             ->condition('p.order_id', $notarr, 'NOT IN')
             ->execute();

This returns an error:

  Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute() (line 2139 of /var/www/seven/includes/database/database.inc).

It is understandable. My question is how do I pass my array through that query.

Try for the first query:

$notarr = db_select('uc_packages', 'p')
           ->fields('p', array('package_id'))
           ->condition('p.order_id', $order_id)
           ->condition('p.sid', NULL)
           ->execute()
           ->fetchCol();

That way, you'll get the array of package_id, without needing the additional foreach, and avoid the stdClass string conversion error

Presumably also query 2 should be checking package_id instead


Why no pid in node object? I am setting an alias programatically, using path_set_alias() in Drupal6.

Looking at the code of path_set_alias in path.module, I see that if I pass the pid (path id), the old alias(s) for that node will get deleted, which is what I want.

When I load the node, though, I see no pid property set on the node, but the record for the node's alias exists in url_alias table.

Why doesn't pid exist on the node object? Must I retrieve the pid from the url_alias table and then pass that in to path_set_alias to remove the old alias?

It looks like a bug, see http://drupal.org/node/633916

It's optional to path the pid to path_set_alias() so it should work without passing it.


Contextual menu link I'd like to know if it is possible to create a link only if a certain condition is respected.
Example with my current menu:

function mymodule_menu() {
  $items = array();
  $items['mycontent/%my_object/my_place'] = array(
     ---(code)---
  );
  return $items;
}

The link created by this menu should not be available for each instance of my_object. This menu should only be used by objects that have for example $my_object->flag set to TRUE.

In my page callback I could check the object and exit the form if the flag is not set, however the link would be still displayed and people could click on it.

Do you have any idea ? Thank you.

You can use an access callback for that sort of thing:

function mymodule_menu() {
  $items = array();
  $items['mycontent/%my_object/my_place'] = array(
    'access callback' => 'mymodule_foo_access',
    'access arguments' => array(1),
    ...

  );
  return $items;
}

function mymodule_foo_access($object) {
  // Contrived example, use something better
  return $object->flag === TRUE;
}


Simple AJAX callback I'm looking to a way to make a call to a PHP function in my Drupal 6 module, and return the result asynchronously to the page.

I'm familiar with jQuery AJAX, but I don't understand how to post to a function using it. Does anyone have experience on doing this?

Disclaimer: I've never done this with Drupal 6.

You want to use a menu callback: You create a menu item (which is just a path associated to a PHP function), and point your query request at that path.


Exposed date filter adds a timezone offset in query In Drupal 8, when creating a view with an exposed filter on a Date field (which is in date only mode), the resulting query removes some hours based on my timezone.

I'm in the UTC+2 timezone, so a date filter of 2016-04-20 creates a query of DATE_FORMAT('2016-04-19T22:00:00', '%Y-%m-%d'). And so, none of the nodes I want are displayed...

How to avoid that?

The following helps when rendering views programmatically:
$event_date_time = new \DateTime($query->get('date'), new \DateTimeZone('America/New_York'));
$event_date_time->modify('+1 day');
$event_date = $event_date_time->setTimezone(new \DateTimeZone('America/New_York'))->format('Ymd');

$view = \Drupal\views\Views::getView('events');
$view->setArguments([$event_date]);
$output['events'] = $view->preview();


how to delete modules which are alredy uninstall? I have set of modules in my system but those modules are not properly un installed
from the file system i have removed all modules but name aad path of the module still remains
in system table

Any one please suggest me how to clear this garbage ?

Unless you disable and uninstall the custom modules you should not remove that custom module . This can cause performance and other issues. Get back those modules from backup. Then disable and uninstall them. Then you can remove the module.

There is even a module in Drupal 7 which will tell you deleted but not disabled modules which I'm not able to remember.


Hide certain field on form alter using AJAX I have a webform created using interface, and need to hide some fields through button. Using form_alter I have added that button added AJAX call with it. Now I want to remove/hide certain element using that button and AJAX.

Below is the sample code

function xyz_user_signup_form_webform_submission_form1_form_alter(array &$form, FormStateInterface $form_state, $form_id) {

  $form['#attached']['library'][] = 'xyz/xyz.global';

  $form['start'] = [
      '#type' => 'button',

      '#ajax' => [
        'callback' => 'xyz_user_signup',
       ],
      '#value' => t('START >>'),
  ];

}

function xyz_user_signup(array &$form, FormStateInterface $form_state) {

    $elements = &WebformFormHelper::flattenElements($form['elements']);

    $elements['field1']['#access'] = FALSE;

    return $elements;
}

On clicking start button I want to hide field1.

Your AJAX needs to have a target ID where it will put your AJAX output. You declare that ID in the wrapper key.

In your form_alter

  '#ajax' => [
    'callback' => 'xyz_user_signup',
    'wrapper' => 'load-me-here-id', // This element is updated with this AJAX callback.
   ],

Then you need to wrap the field with this ID so AJAX replaces it.

 $form['elements']['field1']['#attributes'] = ['id' => 'load-me-here-id'];

In your ajax callback

return $elements['field1']; // so it doesn't return the entire form.


Creating QuickTabs programmatically not working I'm trying to create some QuickTabs programmatically like it's documented on the website, but for some reason, my code bellow doesn't generate QuickTabs at all!
What do I do wrong or am I looking at the wrong documentation here?

function quicktabsmenu_block_info() {
  $blocks['quicktabsmenu'] = array(
    'info' => t('Dynamic QuickTabs menu'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function quicktabsmenu_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'quicktabsmenu':
       //set tab content
        $block['subject'] = t('Syndicate');
        $block['content'] = _create_quicktabs();
        return $block;
      break;
  }
  return $block;
}

function _create_quicktabs() {
  $tabs['tabcontent'] = array(
    'title' => t('Tab 1'),
    'type' => 'freetext',
    'text' => t('Free text'),
  );
  $quicktabs['qtid'] = 'my_new_quicktabs';
  $quicktabs['tabs'] = $tabs;
  $quicktabs['style'] = 'Zen';
  $quicktabs['ajax'] = FALSE;;
  $var = theme('quicktabs', $quicktabs);
  return $var;
}

Well, after some thinking and searching, I managed to solve my own question. All I needed was this:

$tabs = array(
   $tabs[] = array(
      'title'   => t('Tab one'),
      'type'    => 'node',
      'nid'     => '24',
      'weight'  => 0,
    ),
    $tabs[] = array(
      'title'   => t('Tab two'),
      'type'    => 'node',
      'nid'     => '23',
      'weight'  => 1,
    ),
);

// Configure the QuickTabs options
$quicktabs_options = array(
   'style'   => 'Bullets',
   'ajax'    => FALSE,
);

$quicktabs_name = 'dynamic_quicktabs_menu';
$quicktabs = quicktabs_build_quicktabs($quicktabs_name, $quicktabs_options, $tabs);
return $quicktabs;


How can I get the taxonomy term name from a term ID? I'm trying to get a taxonomy term name by term ID. According to another post, I should load the term first:

$term = \Drupal::entityTypeManager()->getStorage('taxonomy')->load($tid);

But then I get this error :

  Notice: Undefined property: Drupal\Core\Entity\Plugin\DataType\EntityReference::$target

What am I doing wrong? How can I get the term name?

Or you can simply use The entity Term class:

use Drupal\taxonomy\Entity\Term;

and in your code:

$term = Term::load($tid);
$name = $term->getName();


How do I test a CKEditor text format field with Behat/Mink? I am using an @javascript test in Behat on CircleCI to check my Drupal 8 site.
When I use the standard I fill in "my field" with "value" step, it works for fields with the plain text format, but it fails for fields that use CKEditor.
How can I fill in fields on CKEditor?

This doesn't yet have official support in the Drupal Extension.  The linked thread has some examples that use traits.
However, I found this gist by johnennewdeeson to be a faster, easier solution for me, just cut and paste into FeatureContext.php:
  /**
   * @Then I fill in wysiwyg on field :locator with :value
   */
  public function iFillInWysiwygOnFieldWith($locator, $value) {
    $el = $this->getSession()->getPage()->findField($locator);

    if (empty($el)) {
      throw new ExpectationException('Could not find WYSIWYG with locator: ' . $locator, $this->getSession());
    }

    $fieldId = $el->getAttribute('id');

    if (empty($fieldId)) {
      throw new Exception('Could not find an id for field with locator: ' . $locator);
    }

    $this->getSession()
      ->executeScript("CKEDITOR.instances[\"$fieldId\"].setData(\"$value\");");
  }


Limiting users to edit other users I have a hierarchical user structure, so every user has a entity reference field that points to another user - his/her supervisor.

The thing is that I need to give every user the permission to modify/delete the users that are under him/her in the hierarchy but to no one else.

It is a bit more complicated due to the fact that the hierarchy can be quite high, so a user has to be able to modify even users that points to someone (as to their supervisor) who points to him.

I've Googled for quite a few minutes but didn't find any solution whatsoever. I also need to implement it with my module so programmatic approach would be proffered to another module.

You need to define your own access call back for the menu items.
For example: implement hook_menu_alter and changes the access callback for item['user/%user/edit'] and item['user/%user/cancel'] to your own custom access callback. I have not tried this myself yet, but it is something along these lines:

/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function MYMODULE_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'MYMODULE_access_callback';
}
/**
 * Callback to disallow access for the anonymous user.
 */
function MYMODULE_access_callback(){
  global $user;
  // if the global user (current user) satisfy the criteria
  // then return true else false.
  // you might not have to load the user from the menu item
  // as it may be already loaded and passed to the page and access callback
  // see hook_menu
}

It might be a better idea though to define your own menu items and handle the operations on your own instead of altering the user menu items.


Create custom entity type programmatically maybe my title is not correct but I have written a module that creates a new entity. Now I would like to create a few of these entities on hook_install. I can create a new entity, that's not the problem, but I cannot create the entity types.

This is my code I use to create a new entity:

/**
 * Implements hook_install()
 */
function skilt_badge_install(){
  $entity = entity_create('skilt_badge', array('type' =>'test'));
  $entity->title = "Testtitle";
  $entity->description = "Testdescription";
  $entity->save();
}

Now, when I create a new Skilt badge type with the machine name "test" in the drupal interface it works. But first I would like to know how I create the Skilt badge type programmatically.

I've tried something like this first, thinking the type is also an entity:

/**
 * Implements hook_install()
 */
function skilt_badge_install(){
  $entity = entity_create('skilt_badge_type');
  $entity->title = "Testtitle";
  $entity->description = "Testdescription";
  $entity->save();
}

But that didn't really work because entity create requires a type...

Could you guys help me?

As some have commented, Entities are VERY complicated. The reason your code is not working is because entity_create() is used to create an INSTANCE of an entity of an already defined entity type. What you are doing in the UI creates the entity type.

You must first create your entity type in your module before you can create an instance of that entity. Refer to the links in the comments above on how to do this. And get ready to spend a little time if this is your first time doing this -I assume it is.


Is it possible to load different versions of the same module? I am running Drupal 6, in a multisite installation. While I fully understand the problems with having varying versions of the same modules running concurrently, I guess I want to know if there's a way to match a specified version of one module to only process requests, or handle calls made by another module?

I currently have Views 2.x in sites/all/modules. It doesn't work w/ Views Slideshow: Cycle 3.x. I want a way to also have Views 3.x in sites/www.mysite.com/modules, and force it to only process requests that would normally be made by Views Slideshow: Cycle 3.x - but nothing else, as Views 2.x would pick up the rest.

I sort of envision it in the same way Blocks work - where you may have regular expression matching for specified URLS. Thanks for any help in advance.

I'm afraid this simply isn't possible without hacking at Drupal core and the Views module(s) in ways I can't even imagine.

As you know Drupal will only ever let you have one version of a module installed at any one time, and there's no mechanism to 'swap' a module based on a condition (such as the current URL).

Conceptually this would be almost impossible for quite a lot of reasons; the most obvious that jumps to mind is the fact that one version would have to be uninstalled before the other could be enabled, thus destroying all of the data that exists for the first version. By the time you 'swap' back to the other version, you've lost all of your original Views data.


Display nodes with the same parent node Let's say I have a Region content type that have multiple entity reference to a City content Type.

When I'm on a City page, I would like to display Cities of the same Region as the City page.

How can I achieve this through a view?

Keeping in mind that I also need to display cities of a Region at some point, switching the relation owner (City having the entity reference field to Region) might no be a solution here.

If it was me, I'd probably use a Region reference on the City so that you only need a single-value field, but this should be quickly accomplished in Views either way.

Assuming a City reference on the Region:

Create a View of Content entities of type City with a Block Display.
Add a Node ID Contextual Filter with Default Actions set to Provide Default Value > Content ID from URL.
Add a required Relationship to Region/Content using your reference field.
Add your reference Field to the display using the Relationship and uncheck/disable Multiple Field Settings > Display all values in the same row.
Add a Contextual Filter for your reference field using the Relationship with Default Actions set to Provide Default Value > Content ID from URL. Then check/enable the More > Exclude option.

Now just place the block in a theme region on your site so that it shows up on the City page. #1-4 should get a View showing all Cities that share a Region with the current one. #5 should remove the current one from the results.


Module recommendation needed for recurring monthly membership plan? I’m building a site that features yoga/excercise videos and will require users to sign up as members which will require a recurring monthly payment. Could someone recommend which modules to use for this? i see there are a few different options available. Any experience with something like this or advice would much appreciated, thanks!

i also need to make these videos inaccessible to non-members, something else to consider

There are a few options available.

I've seen this: https://www.drupal.org/project/commerce_recurring which integrates with Drupal commerce. It doesn't have a stable version though.

For something more stable, and which is independent of the Drupal commerce module, try Recurly
https://www.drupal.org/project/recurly

Recurly is a 3rd party subscription billing system.

Using the Recurly roles module: https://www.drupal.org/project/recurly_roles

You can have people subscribe to your website, and assign a paid membership user role after signup and subscription. If a user stops the subscription, then you can take away the role.

Then configure your videos to only be accessible to the paid member role.


Where to insert .js code using the webform module for google tracking a submit button? I am trying to insert a google tracker to a form submit button/form using the webform module (drupal 7).  Here is my code:

Drupal.behaviors.basicWorks = function(context) {
  // Track submission events.
  $('#webform-client-form-198', context).submit(function() {
    ga('send', {'hitType': 'event', 'eventCategory': 'PDTestlinktoDrupal', 'eventAction': 'clickAction', 'eventLabel': 'PDConversionTest' });
  });
};

My question is:

Where do I place this code?  Inside the webform.js inside the /js folder?  Or do I create my own file inside the /js folder and upload?

Been working on this issue for a few days now and I could really use some insight.

you have 2 option:
1- using #attached to the $form element. use hook_form_alter

function YourMODULE_form_webform_client_form_1_alter(&$form, &$form_state) {
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'YourMODULE') . '/js/your_script.js',
  );
}

2- add it in your custom module with drupal_add_js() function, Also it will be much better if you just load the js on only that page (web form page) so you will avoid loading it on every page.


How to display programmaticaly default user picture? I want to display programmatically default user picture if the user is not uploaded any. For that I have written code php code but its displaying user uploaded user picture correctly but not the one default when user doesn't upload his/her own. How to do that? help me.

$user = user_load($user->uid);
$account = user_load($user->uid);
print theme(
    'image_style',
    array( 'account' =>$user,
      'style_name' => 'x-small',
     // 'path' =>!empty($user->picture->uri)?$user->picture->uri:variable_get('user_picture_default'),
      'path' =>!empty($user->picture->uri)?$user->picture->uri:variable_get('user_picture_default',''),
      'attributes' => array(
        'class' => 'avatar'
      )
    )
  );

Its very straight forward. If you want to add a default picture then go ahead and add the picture from the admin page as the other answer suggested. Programmatically,
The default picture is loaded via the variable user_picture_default.
So you can do,

$user = user_load($uid);
print theme('image_style', array('path' => $user->picture->uri, 'style_name' => '<image-style>'));

if (!empty($user->picture)) {
  print theme('image_style', array('path' => $user->picture->uri, 'style_name' => 'CUSTOM_STYLE'));
}
else {
  $custom_default_image_path = 'public://default_image.png';
  print theme('image_style', array('path' => variable_get('user_picture_default', $custom_default_image_path), 'style_name' => 'CUSTOM_STYLE'));
}

However, you can also make the default image theme dependent/independent via the hook


How to load sliders on subsequent pages in GD Infinite Scroll? Here is my Testcase.
If you scroll down, the feed will automatically extend: It is an infinite scroll-feed.
However, the slider images of subsequent pages are not being loaded.
As soon as the page is being refreshed, all visible sliders are loaded.

In the scenario I use the following two Drupal modules:

GD Infinite Scroll
Zurb Orbit

How can I get sliders of subsequent pages to work properly?
(Additionally: If the last page is being scrolled down, the infinite scroll would literally keep scrolling this very page infinitely. Is there a way to prevent it and just stop upon hitting the last post of the last page?)

user gooddesignusa kindly showed me a solution:

scripts.js in the theme folder has to be like this (can also be created if no scripts.js is there):

(function ($, Drupal) {

  Drupal.behaviors.STARTER = {
    attach: function(context, settings) {
      // Get your Yeti started.
    }
  };

  //runs on document ready.
    $(function(){
    //checks for autopager function and checks if ID of view is on page
    if($.autopager && $('#gelaendespiele').length){
      //binds ajaxSuccess
      $(document).bind('ajaxSuccess.autopager',function(event, xhr, settings){
        //rerun function after ajax is done loading
        $(this).foundation('reflow');
      });
    }
  });

})(jQuery, Drupal);

Then I had to uncomment line 72 of my info file (make sure scripts.js is included)

Finally clear all caches.


Switch site language after IP to locale redirect I have a Multilingual Drupal 7 website. using i18. I redirect my visitors based on IP address with IP to locale module. Now e.g. visitors from Holland (Dutch IP) are redirected to http://landberg.at/nl

But now I am not able to select another language, with my language switcher? E.g an English person who lives in Holland must be able to switch to the English version. http://landberg.at/en

How do I have to achieve this? Is this anyway possible with language redirect based on IP?

(currently on my site I switched IP 2 locale OFF)

You have tried Language Switcher module but you are not getting any result. Once try to use Language Switcher Dropdown module.

  Language Switcher Dropdown is a very simple module that exposes a new
  block, similar to the default Language Switcher block provided by
  Locale module. The new block allows site visitors to switch languages
  using a drop-down select list instead of using hyperlinks.


View, flag, and followers I have a user flag that is called "follow" and am trying to setup the following views in Drupal 8.

I want to create 3 views for my website's user profile pages:

A list of users flagged by a user (for example, a "people I'm following" block)
A list of users flagging a user (for example, a "my fans" or "my followers" block)
A list of nodes from all the users that have been flagged by a user (for example, a news feed for nodes created from the users a user flagged)

This has been done before for older versions of Drupal (see View of users flagged by a user, users flagging a user, and nodes from users flagged by a user), but I can't get it to work on Drupal 8 because many of the fields are different.

Even after playing around with different values, I can only get to the point where I display the users the currently logged-in user is following, but that is not what I need.

How do I get a list of users flagged from a user account when I am watching its profile?

Whether you're creating content or user Views, you have to add the Flags Relationship (User flag in your case). This is the first step to introducing the flags information into the Views, and in most cases you'll want to set that Relationship to Any user, and use Contextual filters to restrict the results to your needs.

List users flagged by a user

This answers your first question, a page you can add to user profile pages (as a Drupal tab for example).

Create user Views, Page Display
Add the User flag Relationship and configure it:
Include only flagged content
Follow
Any user
Add the Contextual filter User ID from the Flagging category (not the User Category!) and configure it:
It will use the Flags Relationship by default
When the filter value is NOT in the URL
Show "Page not found"
When the filter value IS in the URL or a default is provided
Specify validation criteria
User ID
Change the Path to user/%user/flags
Add a Menu tab if you wish to show on user profiles
Add No results behaviour This user is not following any others.
Add a Field Created from the Flagging Category to show when the flagging occured.

When you visit a person's page you'll see a list of users they follow.

List followers of a user

Duplicate the Page from above
Override the Contextual filters, remove the flagging one, and add User ID Contextual from the User Category and configure like the one above
Change Path to user/%user/followers and Menu tabs
Adjust the Title, No results text etc.
Override Fields, remove the Name (it will always show the user who's page you're viewing so it's redundant)
Add a Field User ID from Flagging Category (Label it Who flagged)

List content from users that are Followed

Duplicate the first Page from above (List users flagged by a user)
Add a new Relationship Content authored from the User Category, require it so you don't see people in the results that haven't authored any content
Edit the Path to user/%user/flags/content or whatever makes sense to you, add the Menu tab
Override the Fields and add the Title Field from Content Category
Remove the Field showing the date when Flag was created
You can Group by user Name under Format, to group Content by authors if you like

You can create Blocks instead of Page using similar logic, just configure the Contextual filters to react to use a default value from context, when it's not in URL.


Why is search cron so slow? Search cron on my sites takes about 2-3 minutes, no matter how frequent I run it.
I was under the impression only new nodes added since the last run get added to the index. Apparently it's working differently?

Would a SOLR search index update be quicker?

One quirk that I have run into is that everything that happens during a node_load and node_view happens during indexing.  Take a look at _node_index_node start tracing backwards to see the process.

This means that any expensive operations that happen when a page gets viewed also happen when a page gets indexed.

For example, I had a site a while ago that queried an external webservice during node_load and I also noticed that search indexing was slow.  In my instance, the external webservice calls were adding up and not needed during indexing.  I solved it by doing something like

function foo_node_load ($nodes, $types)
{
  if (arg(0) != "node") return;

  // rest of hook
}

So, I would take a look at what else could be going on in your hooks and preprocess/process functions that could be slowing the process.


How do I display the raw value of a CCK field securely? I have a CCK field that I can print out by doing:

print $node->field_cck[0]['value'];

Are there any security concerns with doing this?

Yes! Lots of security concerns. You'll want to use check_plain(), check_markup() or one of the other functions to output that securely.

Check out Writing Secure Code for more information.


How to disable panel cache for user menu? I have a panel page and this page is front-page of my site. This page is not for anonymous users and having a user menu with welcome message like.
Welcome [Username], then other user related menus.

But sometime it shows wrong welcome user name. For example there is two users UserA and UserB.
First time UserA logins into site and it shows "Welcome UserA" after logout UserA other user UserB logs in to the site then welcome message is stills showing with UserA which is not correct.

This is may be due to Drupal cache because when I clear the all cache then it shows the Welcome message for UserB.

I have set the nocache from the panels pan setting for user menu.

How can I disable the cache for that page?

Thanks in advance.

Drupal has a lot of caching levels so you might need to "peel" each one off to know which level is caching the results. Since you're authenticated, it's not the page cache. And since you mentioned that you set the panel to "No Cache", then it's not the panel cache either.

You're probably facing the block cache here. You can either modify the block caching definition in code using hook_block_info_alter (see hook_block_info for the different caching levels), or use Block Cache Alter module to do that same thing via the admin interface.


Converting a content type into a Profile2 profile I'm working on a site that's a user-contributed directory of local businesses. Each business that registers gets a user account.

I've thus far built the entire site using "Place" as a content type. However, in order to get users to contribute their listing as soon as they register (And to let the user easily edit that node), using Profile2 might make sense.

So, either one of two questions:

a. Is there any way of easily exporting a Drupal content type into something importable into Profile2?

b. Is there a way to get users to create a node just after or as they're signing up?

Thanks!

To your first question, create a view of the required information and using the Views Data Export module you can export it to a csv file.

Then you can import the information to users and profiles using the User Import module.

To your second question, Rules will do it for them. Create a new rule executed on the event 'After Saving New Account' with the action of 'Create an Entity' and define the node you want created, using the new user as author.


How can I display a user avatar in Drupal 7? I'd like to know how to display a user avatar in Drupal 7. I want to display the avatar in full size, and as thumbnail.

The code used from user_user_view() is the following one:

$account->content['user_picture'] = array(
  '#markup' => theme('user_picture', array('account' => $account)),
  '#weight' => -10,
);

For example, if you want to output the HTML code to show the picture associated with the currently logged-in user in a form, you could use code similar to the following one:

$form['user_picture'] = array(
  '#theme' => 'user_picture',
  '#account' => $GLOBALS['user'],
);

This is similar to the following code used in node_admin_nodes(), which uses a different theme function.

$form['nodes'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $options,
  '#empty' => t('No content available.'),
);

The content of "#header," "#rows," and "#empty" are used to populate the content of the $variables array that is passed to the theme function ("#header" becomes "header," etc).

theme('user_picture') works even when the Image module (the one that defines theme_image_style()) is not enabled; in that case, it uses theme_image() instead. When the Image module is enabled, it uses the default style as contained in the Drupal variable "user_picture_style." In both the cases, the user image is a link to the user profile.

As the theme function is using a template (user-picture.tpl.php), the relevant code is in template_preprocess_user_picture(); if you look at the code for theme_user_picture(), you would see there is no code.


Programmatically creating a node I am trying to create content from a cron job with a custom node type that contains just a title and body; the content type is mycontent (for argument sake).

I am trying to use the Entity API module because apparently it is supposed to be simpler.

Working from examples, I wrote the following code.

$values = array(
    'type' => 'mycontent',
    'uid' => $user->uid
  );
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('My Title');

Clearly I am missing something here because I get an exception (EntityMetadataWrapperException: Unknown data property title).

So I changed it to the following.

$values = array(
    'type' => 'mycontent',
    'uid' => $user->uid
  );
$entity = entity_create('mycontent', $values);
$ewrapper = entity_metadata_wrapper('mycontent', $entity);
$ewrapper->title->set('My Title');

Now I get a different error, an obtuse Invalid data value given.

Why cannot I get the Entity API module to work as advertised?

The current user in this case is user 1, not the anonymous user. If I add the content using Drupal standard functions, it works. So I know I am not having a permission issue.

I looked at this example, to write my code, and then proceeded to google a lot.

This will work for you:

$node = new stdClass();
$node->title = "My title";
$node->type = "mycontent";
node_object_prepare($node);
$node->uid = $user->uid;
$node->status = 1;
$node = node_submit($node);
node_save($node);

More details you can see at
https://www.drupal.org/docs/7/howtos/create-a-node-in-code


Creating 'index' content views for L1-LX within a taxonomy Note: This is a follow-on question from Creating a displayable 'index' of content nodes within a path

Ok, starting to find my feet again within Drupal, and still getting up to speed with views.

What I'm needing help with

How do I update my view for /documentation, to display the results in a proper HTML ordered and numbered list that follows the taxonomy structure? (i.e. 1. SOP, 1.1 HR and People, 1.2 HACCP, and so on)
How do I then easily duplicate the view's functionality to the L2, L3 and beyond, so this kind of display runs at every level of the taxonomy when it is accessed - i.e. /documentation/hr-people, /administration/fleet/maintenance etc. Does doing this require a content view to be created for every single level/tree in my Content zone taxonomy (which I would think is cumbersome and laborious), OR is there a way to have only a single view with the intelligence to know what page it's being run on within the taxonomy and only display the relevant results at that level?

(I hope the way I've framed this question and the supporting materials below make perfect sense)

Explanation

Following on from the assistance of Hodba Khalaf, I've been able to create my documentation taxonomy (called content zone) for my site, which looks a little something like this:

I've also been able to create a View (called Content zone), targeting the Content zone taxonomy:

This works fine at L1 (/documentation) - with the exception that I'm not entirely sure how to make display the resulting information in an ordered and numbered list relevant to how the taxonomy is laid out, rather than the alphabetical order in which it is displayed.

And from there, clicking on one of the links for a L2 within my taxonomy (say /documentation/marketing) will show all the content assigned to that L2 within the taxonomy; but won't show the L3 headers and links (i.e. /documentation/marketing/advertising, /documentation/marketing/email-waf) of the taxonomy associated with the L2 of Marketing

I hope what i'm trying to achieve has made sense, and appreciate all and any help to point me in the right direction for achieving this.

There are features in Views concerning taxonomy hierarchy, displaying terms with depth, you should look into it. There is also Group by field option under Format in Views where you can, for example, group by Parent field (Parent of the Taxonomy term). You may need to add a Relationship for the Taxonomy field first before you can see those extra Fields/Filters. Contextual filter with depth might also be useful.
You should look into displaying Menus with depth, since each Taxonomy Vocabulary already has a Menu block. You can learn more about it here: Primary and Secondary Navigation in Drupal 8

Generally speaking, you want to get to a point where you have correctly nested HTML list items. Then you can use CSS to adjust the numbering to go into levels 1.1, 1.2 etc.

Or if that numbering is so important you could add a field for it on your Vocabulary, so each item has that textual bit of data associated with it (not numbers because the sorting won't be correct, you want 1.10 > 1.1). Sorting in Views can still be done with the term weight (the sorting you saved in Taxonomy).


Can I safely use the same UUID on independent sites? I'm trying to create a site building workflow which uses some sort of blueprint site, providing a shared, tested set of the Drupal core, modules, content types, paragraph types, a base theme, etc. for all our client work.

Projects/websites shall initially start with the same configuration as the blueprint site, but later on those projects are otherwise completely independent (different clients, different themes, modules will be added/removed, content types will change, ...)

From what I've read this should be possible with config export/import and by manipulating the UUID of the sites.

The question is:
Is it a problem when ALL our projects share the same UUID? In the long run I'm going to end up with about 30-50 projects, each project will a dev and a prod environment, so in total there will be ~ 60-100 installations with the same UUID.

Updating the core and shared modules shall also be done and tested on the central blueprint site, and then pulled and merged by all projects.

This is a perfect use case for Features. You can export shared sets of functionality and configuration without worrying about UUID stripping or collision.

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

  Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.

  Examples of features might be:

  A blog
  A pressroom
  An image gallery


How do I hide the entire parent (top) level in superfish? Using the Superfish module, I need to show just the second level and below. That means, hide the entire first (parent) level and only show the child level based on the current page.

Is this possible?

I tried editing the Superfish block and changing the menu depth, but it doesn't allow me to choose the depth to exclude above it.

Menu block module allows you to choose which level to show, and how deep.

It won't integrate with superfish module, but allows you to build the submenus you're looking for. Moreover, those submenus may be themed to use basic superfish:

function THEMENAME_menu_tree__menu_block__1($variables) {
    return '
'. $variables['tree'] .'
';
}

1 in the function name is the delta of the custom menu_block created.

Although posible, there's no straight way to leverage advanced superfish configuration / styling within a menu_block: APIs are not isolated enough as to theme a menu_block with a complex superfish style in a few of lines.

Just note also that a closer integration of both modules is feasible (I think of superfish using menu_block API).

So, although incomplete, I think menu_block + superfish is the best alternative.


get rid of decimal scale of stock field in commerce product shows stock as 1.00 -> how do i get it to show 1
(i get this to work in admin lists : admin/commerce/product
but when showing in start screen or product detail page its 1.00..

how can I get rid of .00 ?

notice: I have and create some product and in admin/commerce/products/types/product/fields/commerce_stock  stock field property it is disabled

edited
I update the module to new released , I unnistall fully pervious version and install new, all stock set 0, in display of product display I can do it that dont show scale digits .00, but in edit of product display it is 0.00 with 2 digit scale yet

That bug has been fixed a long time ago; update from 7.x-2.0-alpha4 to 7.x-2.0-rc1. https://drupal.org/project/commerce_stock and that will fix it, along with a lot of other issues.


Edit node as text link in Twig How to write the same code in Twig?

<?php print l(t('Edit this node'), 'node/' . $entity->nid . '/edit'); ?>

See this example from Functions - In Twig Templates:

{# Link to node page. #}
{{ 'View node page'|t }}

in which you need to use the route to edit the node: entity.node.edit_form


Drupal views custom template array issue I have made a view named services which fetches the fields of content type services, fields name : services_text and services_image.
I have made a custom tpl named views-view--services.tpl.php with my own structure and want to access fields like $row['services_text'] in for each, but it comes out as undefined index, as i can figure it out, by using var_dump, that this tpl is not getting any row rather plain html string for output so I even tried with views-view-unformatted.tpl.php, but still no use.

Kindly help.

Use views-view-fields--.tpl.php and render the field with your custom markup

For example:

<?php print $fields['field_images']->content; ?>

<?php print $fields['title']->content; ?>

<?php print $fields['title_1']->content; ?>

<?php print $fields['another_field']->content; ?>


How are entities and libraries for the Apache Solr server organized? I'm trying to understand some basics about Apache Solr server, and particularly how its entities and libraries are organized.

I've tried to read the documentation but it is hard to understand it without good knowledge of the Java language.

My goal is to integrate Solr with Drupal 7's Search API location module. I have already got working and configured Solr server but it also requires Solr to be extended with Lucene localation library, and this is actually the part that I don't clearly understand.

There is a version of Solr with an already compiled location library, but it means that the existing one should be deleted. What I was thinking about: is it possible to just copy the apachesolr/solr (with geo library) directory from that version into existing Solr server as new instance?

Any explanations about this?

Iv updated solr to 3.6 version, it has integrated support for spatial search.


FedEx Address Validation module setup help I am trying to force accurate city, state and zip code entries when a user inputs their address. the Address Field module by default doesn't require any accuracy. For example i can type "fake city" and it will accept that.

I found the FedEx Address Validation module, but as stated on the module page there is no user interface for connecting your FedEx credentials.

Does anyone know where to add my credentials?

  This module has no User Interface, so you must set the following variables:
  fedex_address_validation_environment - must be either "test" or "live".

Live credentials are made up of the following 4 values:

fedex_address_validation_live_key
fedex_address_validation_live_password
fedex_address_validation_live_account
fedex_address_validation_live_meter

Test credentials are made up of the following 4 values:

fedex_address_validation_live_key
fedex_address_validation_live_password
fedex_address_validation_live_account
fedex_address_validation_live_meter

I tried adding to settings.php

$conf['fedex_address_validation_environment'] = 'test';
$conf['fedex_address_validation_live_key'] = 'LIVE KEY';
$conf['fedex_address_validation_live_password'] = 'FEDEX PASSWORD';
$conf['fedex_address_validation_live_account'] = 'ACCOUNT NUMBER';
$conf['fedex_address_validation_live_meter'] = 'METER NUMBER';

with no change. status still "Not configured for test"

Unless you desperately need those vars to be administered through the UI (in which case a small custom module would be the way to go), you can just add the variables through settings.php, using the following format:

$conf['fedex_address_validation_environment'] = 'test';
$conf['fedex_address_validation_live_key'] = 'foo';
$conf['fedex_address_validation_live_password'] = 'bar';
// etc...


Configuration management with different database and websites We have a central code base (Git repo). From this code base we deployed several websites already.

Till now we used features. The websites which are already in production they have a filled database with a lot of content.
From now we switch over to drupal 8 Configuration management.

In the central code base we have set $config_directories[CONFIG_SYNC_DIRECTORY] = 'config/base';. This directory contains all the configuration, from where we deploy our new added configuration, after a drush cex -y.

But after I do:

first a new install off the site with Configuration installer module and import all the existing configuration, everything works fine. I can import and export configuration without problems
but then I have to copy the production database (from the site which is already in production) back into this database. After that I am not able to import configuration anymore.

But I need to copy this database back in, because we need all the content from the existing site (which was based on Features)

I get an error the UUID is not matching etc... Is it possible what I want? And how do I get it working?

(I tried already manually copy/paste the correct uuid: in system.site.yml, but it still didn't work).

Update:
I use docker for my local Drupal 8 environment

Basically you need to make sure both sites share the same UUID.

Do you have drush? If so:

In the shell of your old site (copying from) get the UUID

drush cget system.site uuid

(You'll get something like 'system.site:uuid': bfb11978-d1a3-4eda-91fb-45decf134e25 - copy the value)

Then in the shell of your new site (copying to) set the UUID

drush cset system.site uuid <your_uuid>

EG: drush cset system.site uuid bfb11978-d1a3-4eda-91fb-45decf134e25

Then if you get an error something like "placeholder ... These entities need to be deleted before importing." run this command:

drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'

After all that, drush cim sync -y should allow you to sync the settings between your environments.

Source


How to do a redirection in drupal I have a node page that should redirect to another node's page instead of displaying itself...

How can I do that ?

Many thanks !

Rather than using a node to redirect to another one, I would implement hook_menu() to define a new menu callback that renders the other node, or redirect to the other node.
The alternative would be implementing hook_node_view() to add the other node to the node being viewed (when it is the correct one). For example, the following code would work.

function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->nid == $node_to_alter) {
    $node->content['my_module_additional_content'] = node_view($the_other_node);
  }
}

This is the approach followed by Drupal where, instead of using the PHP filter (which would make a node editable only from Drupal.org administrators), a custom module is used to add content to specific nodes.

A node that redirects to another node would create problems because:

If you are doing the redirect when rendering the node, you would create problems with all the functions that render a node. The assumption is that a node is rendered when it is going to be visualized, but that is always true, as (for example) node_search_execute() renders the node while executing a search for a set of key words. There are other 10 functions that call node_view(), including the one rendering multiple nodes; all of them would have a problem, if the user is redirected in the middle of what they are doing, which means PHP stops its execution as exit() is being executed.
If you are using the PHP filter to execute PHP as node content, that is not suggested to do. If you need to dynamically render a node content, you should implement a module which could be implement an input filter, or other hooks, depending from the needs.
If you are using a custom module to redirect the users when the node is being loaded, or rendered (e.g. implementing hook_node_load(), or hook_node_view()), you would have the same problem I described first. Plus, as you are already using a custom module, then you can implement one of the solutions I have proposed.

As for other suggestions:

hook_menu_alter() is used to alter the existing menus. For the nodes, the menu callback is the one associated to node/%node, which is invoked for every node. It is possible to use this hook to alter the page callback with a different one that first check which node is being viewed, and then redirect the users to the other node. In this case, there would not be problems, as the function is called when the node is being viewed, not when a node is being loaded, or being rendered in memory.
IMO, it would be a sub-optimal solution. I would rather implement hook_menu() to define a new menu callback.
The Path redirect allows to set static redirects from the UI. This doesn't help if the intent is having a dynamic redirect, which seems the case here.
The Rules module can be useful, but I would rather use it if you need it for more than what you are trying to achieve here. It is a better solution that enabling the PHP filter module to execute PHP code inside a node body, but it would probably require you to write PHP code that is executed through eval(), which should generally be avoided.


How can I get the content type name inside the hook_form_BASE_FORM_ID_alter() hook? I need to obtain the content type name inside an implementation of the hook_form_BASE_FORM_ID_alter() hook for the node edit/add form to made some validations.

I can't find any node object reference using kint() to access to the $node->getType() value.

I need to do a validation like this:

if ($node->getType() == 'article') {
...
}

So, how can I get the content type name inside the hook_form_BASE_FORM_ID_alter() hook?

You can get the node from the form object.

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function yourmodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /* @var \Drupal\node\NodeInterface $node */
  $node = $form_state->getFormObject()->getEntity();

  if (!$node->getType() == 'article') {
    // ....
  }
}

Note that getEntity() doesn't exist on \Drupal\Core\Form\FormInterface, which is why it doesn't show up as a method in an IDE. It only exists on \Drupal\Core\Entity\EntityFormInterface, you can add an explicit instance of for that.


Views, Taxonomy, Tokens and URL I am building a website for multiple summer resorts. I am now concentrating on the restaurants section.

I have a content type - Restaurant.

It has multiple fields but I will just put down the ones that are connected to this question;

field_resort: Term Ref.
field_restaurant_category: Term Ref.

And then the url pattern;

[node:field-resort]/restaurant-guide/[node:title]

I need a block in the restaurant parent page [node:field-resort]/restaurants that then displays a grid with each individual taxonomy term [field_restaurant_category].

What the problem is is that I want to have a page that once you click on one of those categories, takes you to a page that displays teaser views of all the restaurants for that specific food categorie from only that resort while appending the url to keep the resort as the parent.

resort-1/restaurant-guide/[field_restaurant_category]
resort-2/restaurant-guide/[field_restaurant_category]
resort-3/restaurant-guide/[field_restaurant_category]

In Views the pattern for the path cannot have a contextual filter as the first part of the path.

Contextual filters and paths

  The normal way a view gets values for contextual filters is by the
  view path. The easiest way of doing this is to append filter values to
  the path, separated by slashes. It is also possible to have contextual
  filter values within a path. This is done by using a percent sign
  where the view expects a contextual filter value in the path of the
  view (for example user/%/comments).

So your pattern needs to change to something like this:

resorts/%/restaurant-guide/%

as in resorts/[resort]/restaurant-guide/[restaurant-category]

Then two contextual filters:

**content resort (field resort)**
Taxonomy term ID from URL
Validator: Taxonomy Term
Vocabulary: resort
Filter value type: Term name converted to Term ID

**content restaurant category (field restaurant category)**
Same as above but with Vocabulary: restaurant category

Then keep in mind that you might need to deal with spaces in your taxonomy terms


Modelling one-to-many relationships with content types So I'm trying to build a web app, and I've got it set up so far to have two content types, "Client" and "Client Contact".

Now the schema I've put together makes a one-to-many relationship between client and client contact, i.e clients can have one or more client contacts, and each client contact can be associated with only one client.

I'm trying to model this relationship through Drupal 7's content types, but I can't seem to find a way to do it. I thought it could be done through the 'existing fields' section of the 'manage fields' tab on the 'content types' page, but it doesn't seem to work.

Is there any way this can be done or do I need to download a separate module to get it to work?

From my understanding of your question,I think you need to use Entity Reference


How to offset only a subselection of a set of nodes in a view Sorry for the cryptic title, but could not find a better descriptive title. Suggestions welcome.

Situation: There is a newssite with on the frontpage two blocks:

1) a block of the latest 6 'promoted to frontpage' articles in form of an image caroussel
2) a block with the latest 12 newsheadlines, contains both 'promoted' as 'regular' articles

What should happen is:

block one displays the latest 6 'promoted to frontpage' articles
block 2 does not only contain older 'promoted to frontpage' articles, but also regular articles
when an article shifts out of bock 1 it should shift towards block 2, assuming it is not older than the 12th article in this block
there should be no overlap in articles between block 1 and 2, ie: the articles displayed in block 1 should not be displayed in block 2

Problem:

The problem is block 2. I can't figure out howto establish what I want without having an overlap between the two blocks.

The view of block 2 is pretty easy: select 12 nodes of the type 'article', order by date.

Question:

But how do I make sure that this selection takes out the first 6 promoted to frontpage articles? Offset 6 won't work, because then it might also skip regular articles. Only the promoted articles should be offsetted.

Is this feasible with some custom php code?

--- update ---

I think the most feasible solution would be either:

1) merge two views (one that selects the latest promoted articles with an offset of 6 and one that selects the latest regular articles together with some sort of union functionality and then limit it to 12
2) remove duplicates: so create a view that displays the latest 12 articles of any type, but which has been filtered in order to remove duplicates between the articles that are displayed in block 1

Haven't found a solution on either though...

Here is one approach.

Make a view that lists all articles, no filter on "promoted to front page"

Now sort first by "promoted to front page", descending (so promoted articles come first), then by post date (or what ever else you want)

Now  limit it to 6 items.

Clone the view (or block display)

Change the limit setting so there is an offset of 6 (if you cloned the block display) make sure you save the new setting only for the new block (an override)


Field To Display Message Is there any Field to display Message and Images instead of taking values ??

In Drupal Commerce I have created few fields to take Custom Measurements on Order Settings page.

Now I need to display a Picture and a text message on the page where I am taking measurements.

You can use Markup module using which you can add text or HTML which will display a picture..

Project page says

  This module adds the ability for site admins to add "Markup" widgets
  to the form. These essentially let designers of cck content-types
  insert additional markup into the node/edit form to display to
  content-authors. This is the equivalent of adding additional elements
  to $form of the type '#markup'.


Programmatically attaching files I have created the "Gallery" content type, and added two fields: "photo," and "document." I then used the following code for uploading a file in the "document" field:

$file = file_save_upload('document', array(
    'file_validate_extensions' => array('txt doc'), // Validate extensions.
));

// If the file passed validation:
if ($file) {
// Move the file, into the Drupal file system
if ($file = file_move($file, 'public://')) {
  $file->status = FILE_STATUS_PERMANENT;
 // $file->file_display = 1;
  $file = file_save($file);

} else {
  $output = t('Failed to write the uploaded file the site\'s file folder.');
}
 } else {
$output = t('No file was uploaded.');
 }

I am attaching this file to the node using the following code:

$customNode->field_document[$customNode->language][0] = (array)$file;

When I call node_submit() function, I get the following error:

  Integrity constraint violation: 1048 Column 'field_document_display' cannot be null

Does anybody know what I am doing wrong?

I usually don't throw the (array)$file line because really the only thing the field data needs is the fid, description and display. So I usually do the following:

$node->field_image[LANGUAGE_NONE][] = array(
  'fid' => $file->fid,
  'display' => 1,
  'description' => '',
);
node_save( $node );

This way if the display is required, I don't get an error. But that's just me...


Open search results in new tab I am using Apache Solr Search on my site, and would like links on the search results page to open in a new window/tab.  How can I accomplish this?

You should install Custom Search module as it does provide an option to open results in new tab or lightbox.

https://drupal.org/project/custom_search

Otherwise you can always look into using custom functions or js to achieve the same in your search template.

Updated Answer

Since you are using solr and search-result.tpl.php you should have a line like:

<a href="<?php print $url; ?>"><?php print $title; ?>

change it by adding target value like:

<a href="<?php print $url; ?> target='_blank'><?php print $title; ?>


Sending variable from php to js file not working I've followed this : how to send variable from .php file to .js file?.

But following my code isn't working

What I want to do is whenever anybody logs in I want to send the login/password to browser javascript which will send it to another server.

It's only for a test case and not for production environment.

Details:

cyberoam.js

(function($) {
  Drupal.behaviors.cyberoam = {
    attach: function (context, settings) {

        alert(Drupal.settings.cyberoam.login) //on commenting this below alert works

      alert("hello");
    }
  };

})(jQuery);

In the cyberoam.module

function cyberoam_from_alter_submit(&$form, &$form_state)
{
     $username = $form_state['values']['name'];
     $password = $form_state['values']['pass'];

     dsm($username.':'.$password); //working fine

     drupal_add_js(array('cyberoam' => array('login' => $username )), 'setting');
}

What could be the problem? I've read same solution in multiple places but mine isn't working. In the Firebug console it shows TypeError: Drupal.settings.cyberoam is undefined

You shouldn't set the values in the submit hook, you should use hook_init().

In the submit hook you should set a variable ( variable_set("name", "value") ) and read it in the hook_init using variable_get("name", "dafault_value");

On the other hand, you should NEVER add the password in js variables. It's a huge security risk.


Show only objects with the latest date How can I show objects having the latest post date? I.e. if 1 was posted yesterday, and 2 -- today, then show only 2 but if they both were posted yesterday and all the others before that, then show 1 and 2.

Is it possible with Views?

Since there's logic involved (check records based on this date, if there are no results, check the previous date) I would do this with a custom module making use of Entity Field Queries.


How does apache solr search recognize my changes by mysql query in my database I would like to use mysql query to modify some of my data. But I found that apache solr doesn't index all my changes.

For example, I modified some products' category in the field_data_field_category table through query yesterday. When I went to those products' content edit page, the category shows correctly. However, I found that Apache Solr doesn't count any of them into Remaining Item.

Does anyone know how does apache solr search work? Or what kind of query I should use to achieve my goal.

Solr maintains in own search index separated from the database. A process is required to index content from your database into Solr's index. Usually, this is done transparently by the Drupal Solr integration modules. These integrtions rely on usage of Drupal API for content changes. These API allow integration code to be executed on changes. This code will either index the change directly, or mark the content for re-indexation during the next cron run.

By accessing the database directly, you bypass Durpal's APIs and prevent the integration module to see your changes.

If this is a one off operation, you should be able to mark all content for re-indexation from the administration page of your Solr integration module.


Simple newsletter not diplaying images I am using Simplenews module for sending newsletter to users. I have created a view and the view will be the newsletter body. The view has title and images. When I send email to users, images in view are breaking. But other iamges such and footer images are displaying. When inspected the URL itok='' is missing from the image. I am using Mime Mail for email sending. Is any configuration to be made in Mime Mail for displaying the images. Thank You

Please set E-mail format Plain Text to Full HTML in Mime Mail Settings


Website is getting very high load due to "UPDATE cache SET data..." It's a high traffic website, but I guess high load is not because of traffic because many times it runs smooth on same traffic. I researched a lot and optimized Apache, switched off logging modules to save resources and done whatever may be cause of load.
Then finally I installed devel on site and check using "Collect query info", "Display query log" and I found that this particular query taking too much time (more than 2000 ms)

UPDATE cache SET data = 'a:2:{s:7:\"profile\";a:36545:{s:32:\"c21f969b5f03d33d43e04f8f136e7682\";a:17:{s:6:\"layout\";s:7:\"default\";s:14:\"layout_desktop\";s:7:\"default\";s:15:\"layout_handheld\";s:2:\"-1\";s:13:\"layout_iphone\";s:2:\"-1\";s:4:\"menu\";s:13:\"primary-links\";s:10:\"menu_style\";s:4:\"mega\";s:11:\"option_font\";s:1:\"0\";s:14:\"option_layouts\";s:1:\"0\";s:11:\"option_menu\";s:1:\"0\";s:13:\"option_screen\";s:1:\"1\";s:13:\"option_t3logo\";s:1:\"1\";s..........................................................

and page getting loaded and loaded to infinite time, it never completes.
I am sure this is the only reason for high load on server.

APC is already installed on my seerver.

Given your server already has APC installed, you do not need to keep cache in database at all. And probably shouldn't.

Install APC module (for older Drupal versions see Cacherouter or Cache Backport) to move your cache from MySQL to RAM. Without it, APC only caches opcode, not Drupal's cache data. Also, APC Status or APC Admin module helps with monitoring.

It might be wise to exclude form cache from APC and keep it in database, but that's material for another question.

For APC optimization, see this question.


Content Moderation: how to make a button to move between states? I want to allow authenticated users to fill out a node (Draft) and then, when they are ready, submit the node (to give it the Submitted state).  An admin will later decide whether or not to publish the node.

I'm experimenting with the improvements to the Content Moderation module on Drupal 8.4-rc2 (new UI is in the 8.4 series, so 8.3 and before will look different).

I have the following workflow states defined:

Draft
Submitted
Published

There is a transition called Submit to move from the Draft state to the Submitted state.  Authenticated users have permission to use this transition.

The problem is that the core UI for this looks very complicated.

This is a node edit page:

And this is a node view page:

I want to hide this moderation UI and instead provide users with a single button, "Submit for approval."

I hid the moderation and revision UI from auth users (only admin have permission to edit workflows) like this:

function mymodule_form_content_moderation_entity_moderation_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser();
  if ( empty($user) || !($user->hasPermission('administer workflows')) ) {
    $form['#access'] = FALSE;
  }
}

function mymodule_form_node_mycontenttype_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser();
  if ( empty($user) || !($user->hasPermission('administer workflows')) ) {
    $form['revision_information']['#access'] = FALSE;
    $form['moderation_state']['#access'] = FALSE;
  }
}

function mymodule_form_node_mycontenttype_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $user = \Drupal::currentUser();
  if ( empty($user) || !($user->hasPermission('administer workflows')) ) {
    $form['revision_information']['#access'] = FALSE;
    $form['moderation_state']['#access'] = FALSE;
  }
}

So this cleans up the UI and hides all the Content Moderation options.

But how do I create a button to move from one state to another?  Specifically, I want the bottom of the form to look like this:

Save button (saves the node in the same (Draft) workflow state)
New button that saves the node and activates the transition to the Submitted state

This is basically the same thing as what core does when it provides an option to Save as published and a second option to Save as unpublished-- I just want to do this with my workflow states.

I think you should be able to do something like this. (But I did not test).

The first code block adds an additional submit button and gives it a custom submit handler. (Button specific submit callbacks should run before form submit callbacks.)

function mymodule_form_TYPE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Add second submit button (Also check if user can see this).
  $form['actions']['submit_publish'] = [
    '#type' => 'submit',
    '#value' => t('Submit for approval'),
    '#submit' => ['mymodule_submit_callback'],
  ];
}

And the submit callback, which simply sets the new value for the moderation state.

/**
 * Submit callback to submit for approval
 */
function mymodule_submit_callback(array &$form, FormStateInterface &$form_state) {
  $form_state->setValue('moderation_state', 'MODERATION STATE ID');
}


Form multiselect item and url encoding with GET method I have a form on a Drupal 7 site, which is submitted using the GET method to refresh the page's display using the query parameters.
One of the parameters uses the select box, with the multiple option.  This results in the query parameter using the format option%5B%5D=39&option%5B%5D=54

Is there a way to have the form submit and merge the query parameters into something like option=39+54

I am not sure if this is gonna work, but I think it might help you a little bit.

$query = explode('&', $_SERVER['QUERY_STRING']);
$combined = '';

foreach($query as $key => $value) {
  if ($key == 'option') {
    $combined .= $value;
  }
}

drupal_goto($_SERVER['REQUEST_URI'] . '&option=' . $combined);


How to prevent the conversion of text URL to link? I am creating a basic page having some text links as follows:

http://localhost:8080/student
http://localhost:8080
http://localhost:8080/login

D8 automatically converts this text URL to links as follows

http://localhost:8080/sutdent

http://localhost:8080

http://localhost:8080/login

I don't want to convert the text URLs to links. I also checked the text filters but did not work for me.

How to prevent this conversion?

As far as I know this is not a problem if you a using CKeditor.

I tried to write some text URLs in both Basic HTML and Full HTML format. It worked fine, if you want to see how I did I have made a little video for you:

https://vimeo.com/234845994


Is there any way to adjust the items per block options? In Drupal 8, whenever you create a view block, you have the option to specify the number of items displayed in that view block which is awesome.

Currently, you can choose between 1, 5, 10, and 20. Is there any way to change this to include 1, 2, 3, 4, 5" or just be able to manually enter a number?

I was really excited about this feature and need to use it, but I need to really choose between 1, 2 or 3 items per block.

Edit: I'm referring to the block management screen, not the views configuration screen.

Thanks to the answer @Berdir provided, I've been able to replace the restrictive select field with a more flexible number field.
In mymodule.module
The form_id is block_form (andpanels_edit_block_form and panels_add_block_form for Panelizer). Change the #type to number to make it so that you can input a number. Unset the #options to avoid validation errors (Invalid choice).
/**
 * Implements hook_form_alter.
 *
 * Changes the input type of the "Items per block" setting of
 * a view-block in Blocks/Panelizer from 'select' to 'number',
 * so that amounts other than 5, 10, 20 and 40 can be chosen.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (in_array($form_id, ['block_form', 'panels_edit_block_form', 'panels_add_block_form'])) {
    if (isset($form['settings']['override']['items_per_page'])) {
      $form['settings']['override']['items_per_page']['#type'] = 'number';
      unset($form['settings']['override']['items_per_page']['#options']);
    }
  }
}


From template.php to tpl.php I define variables in template.php file preprocess_page but it come undefined in tpl.php files. What can be a problem? Here is code

template.php file

$user_profile = profile2_load_by_user($uid, 'user_profile');
$vars['user_profile'] = $user_profile;

tpl.php file

print_r($user_profile);

Firstly, check to see that profile2_load_by_user is a function available via a .module file and not something you will need to load via module_load_include() - which will load other files, such as .inc files.

Second, check the argument list for the preprocess hook. Did you define it as &$variables and mistakenly assign it to $vars which would mean nothing in this context? Did you forget to pass by reference via & which makes the array  modifiable?

Third, if you just added this code, clear your site caches so the changes are picked up.

Fourth, the function name isn't preprocess_page. It should be
 MYTHEME_preprocess_page.


How can I get the invoicing and shipping profiles for a user? How can I get two separate profiles, one for shipping and one for invoicing? I can get the default profile for a user, but there does not appear to a type associated with it.

In Drupal 7 I could use commerce_addressbook_get_default_profile_id to get the default profile per type, but I don't see this function or an equivalent in Commerce 2.

I'm porting a custom module from a Drupal 7 online shop to a Drupal 8 online shop. This custom module synchronizes user and order data to Navision which has separate fields for shipping and invoicing.
Ideally I'd also be able to use hook_profile_update to sync the profile updates to Navision.

I ended up doing this in a roundabout way:

Get the most recent order for the user
Get the shipping and billing profile for this order

If there are no orders, the user's unlikely to have shipping and billing info


Using Drupal Bootstrap, I want the 'title' of my parent menu item to be a glyphicon and to drop to the search bar! I am having 2 issues with Drupal Bootstrap, I have no idea how to set a leaf specifically in the menu to not only be a glyph of a search icon, but also how to add the search block to the dropdown.

I am going to probably stop using the main-menu and just add a few regions for it!

If you're wanting to theme the menu items, you can:

Use theme_menu_link() in your theme template to alter markup / attributes before rendering
Use a contrib module https://www.drupal.org/project/menu_attributes to add a custom class name e.g. icon-left icon-myname
Select the menu item via css and manually inject it there e.g.:

.menu-class .mid-class:before {
font-family: 'glyphicon';
content: '\utf-char-code';
/* other css here */
}

Adding the search block to the dropdown depends how you want to set this up, we'd need more specifics on what behaviour you're trying to achieve. Bear in mind that you can alter individual menu items through hooks in your template (e.g. theme_menu_link() above), and you can also render blocks programatically.


How can I add a pager to the top of a forum? I am using the standard forum module that comes with Drupal 8. The problem is, when I view a forum node, it shows the pager the bottom. I want the pager to also appear at the top.

The closest I've been able to come is editing the "comment--comment_forum.html.twig" template. If I put random text at the top of this template, then I can see the text appearing at the right spot I want. But if I put this:

{{ pager }}

Then nothing shows. So the comment--comment_forum.html.twig template doesn't know what "pager" is.

Does anyone know where the correct place is to add a pager to the top of forum posts?

Pager is known within the "views-view.html.twig" file: /core/modules/views/templates/views-view.html.twig

If you are using a contributed or custom theme you can override that file and move the pager output where you'd like. So your new file would live here:
/themes/custom/MY_THEME/templates/views-view.html.twig"
 for example.

As near as I can tell there's no setting for this in core currently, although it's been requested.

See also: https://api.drupal.org/api/drupal/core%21modules%21views%21templates%21views-view.html.twig/8.7.x

https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/function/template_preprocess_views_view/8.7.x


What will happen if a custom module has the same name as a contrib module? What are the consequences of two modules sharing the same machine name?

For instance, if I write a custom module named 'views' and do not have the contrib module 'views' enabled, will the update manager attempt to update my custom module according to the contrib project status?

I write a custom module named 'views' and do not have the contrib module 'views' enabled, will the update manager attempt to update my custom module according to the contrib project status?

No it won't. The update manager looks at the packaging information added to the .info file for released modules, as long as your module doesn't have that data in the .info file (no reason why it would), then you won't have any problems.

The other answers are of course correct insofar as you can't have both modules enabled at the same time. You'd never even get to the point of seeing the fatal errors though, Drupal simply wouldn't let you install a module that has the same machine name as another module that's already installed.

You should aim to name your modules differently than the most popular module in existence, though, if only to save the sanity of the poor developer who eventually takes over the project from you.


Drupal 7 custom form date_popup element Given this form

  $form['date'] = array(
  '#prefix'=>t('When do you want to start the featured campaign?'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '0:+1',
  '#type' => 'date_popup',
  '#weight'=>0
  );

is there a way to display only future dates in the javascript popup ?
I can't seem to figure it out.
Thanks alot.

Custom datepicker options are now supported (as of Date module version 7.x-2.6) by setting the necessary values with #datepicker_options. Alex's use case of a custom form element to display only future dates would look like this:

$form['date'] = array(
  '#prefix'=>t('When do you want to start the featured campaign?'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '0:+1',
  '#type' => 'date_popup',
  '#weight'=>0,
  '#datepicker_options' => array('minDate' => 0),
);


Emergency message on site with rules(?) In the event of an emergency I would like the site administrator to push a message to all screens (to any anonymous viewer on any page). The push should not require the visitor to refresh their page or visit another page. The message must push out to all pages without requiring the viewer to take action.

Perhaps after a cron run?

Additional nice-to-haves:

the message is a node of a specific content type
upon creating this node, the author must "activate" the node before the message is live

Any suggestions?

I think this is what you want Rules action with node.js  module

In order to do this, you have to install the node.js on your server. They have a tutorial video for that Installation of Node.js integration module for Drupal


Date is wrong in storage but correct on display? I am trying to programmatically load a node and get its date time value. The default format is HTML5 date, long date. I load it and I get the field value with the following code.

dpm($record['nid_value']);
$entity = \Drupal\node\Entity\Node::load($record['nid_value']);
dpm($entity->get('field_date_range')->value);

The output is the following one.

740
2018-02-23T02:00:00
734
2018-02-23T00:00:00

Why is it stored as 2018-02-23T02:00:00 when the real date is Thursday - February 22, 2018 - 4:00pm to 5:00pm?

The field type is date range; the display type is smart range. When you view the node, it looks perfect. The display is correct. If I create a view, it also outputs the incorrect date, no matter what format I chose on the field output. Time zone has been forced.

Can anyone point me in the right direction here?

UPDATE - Here was the solution to my problem

$nid = 411;
$entity = \Drupal\node\Entity\Node::load($nid);
$dval = $entity->get('field_date_range')->value();
$dt = new DateTime($dval, new DateTimeZone('UTC'));
$dt->setTimezone(new DateTimeZone('America/Los_Angeles'));
$date_to_print = $dt->format('g:ia \o\n l jS F Y');
//$date_to_print = $dt->format('m-d-Y h:m:i');
echo $date_to_print;
//output: 12:00pm on Saturday 24th February 2018

Datetime and Daterange fields are stored in UTC in the database (the storage) and converted to the time zone on output. This is done because the system supports users across the world, so everything is normalized to UTC.

Basically, when you use the UI the field widget takes the input value, and converts it from the user's time zone per system configuration to UTC (see DateTimeWidgetBase::massageFormValues()).  The actual format in storage is the ISO equivalent to the PHP format Y-m-d\TH:i:s.

When output, it takes loads the UTC value, and converts it to the user's time zone per system configuration or uses the forced time zone (the time zone override).  See DateTimeDefaultFormatter::formatDate() for an example, and also DateFormatter::format().

By default, views output field values using the formatters, so the same rules apply.
It sounds like you may have an override in the view settings for the field.


Different menu links depending on user account I need to create menu that has to be diffrent for each user.

/user/%username%
/user/%username%/purchases
etc.

Is there way to do something like that? Thanks

Yes . You can use  Menu Token. (Menu Token module provides tokens, that could be used in title or in path of menu items. For example, if you create a menu item with path: "user/[current-user:uid]", the url will be changed "on fly" to: "user/1" )


How to add a custom display field to a content type in Drupal 6 Hi i am trying to add a custom field to a content type which would be un editable. And view able.

A php code to do some database access and prepare a xml file.

call a Swf animation will.

When user wants to post a content of the type he will give all the information in the form except this field, but once he submits it the info he entered will be hidden and this swf animation will show the data from xml.

Is there any way/ module which allows to add a extra display field? and module which executes a php code upon viewing the node.

About uneditable custom field, here is a resource with several suggestions: http://drupal.org/node/1034768

about how to use a php code for pull data inside a custom cck field (If I understood well), I guess that you can build a module for use your respective code inside this module, and show the desired data inside a custom cck. This page have information related about How to create a CCK content type and fields from a module http://drupal.org/node/1044248

I hope information be useful


Views: showing similar terms on term page by another term reference field I've got 2 vocabularies, for example, artists and styles.

When viewing one of the Artists term i want to show another artists terms in a block, marked with the same term from styles vocabulary by reference field.

How to achieve it?

I tried to set the relation to Taxonomy Term: Styles (field_styles) and various contextual filters but without success.

Any help is appreciated! Thanks in advance

Assuming that you have a term reference field attached to the Artist vocabulary showing terms from the Styles vocabulary, and assuming that you wish to display a list of other Artists with the same Styles in a block ...

Create a block view showing taxonomy terms from the Artist vocabulary.

Set a Conceptual filter on Taxonomy term: Tid and provide a default value of Term ID from URL.

Add a relationship on Taxonomy term:Styles (field_styles) and check Require this relationship.

Add a second relationship to Taxonomy term: Taxonomy term using Styles. Configure it to use the relationship *term from field_styles* and check it as required.

Go to your view fields and edit the Taxonomy term: Name field. Configure it to use the *field_styles* relationship.

Go to Advanced > Other > Query options and select Distinct. This type of query can produce duplicates.

Place the block on your taxonomy pages and it will give you a list of Artists with the same Style(s) as the current Artist.


How to get the row added by ajax in the right place? I have a table form created from a custom entity:
  public function buildForm(array $form, FormStateInterface $form_state, $contract = NULL)
  {

    $form['subscriptions'] = [
      '#type'       => 'table',
    ];
    $form['subscriptions']['#header'] = [some stuff here];
//  here is the query to retrieve data from entity...
    $results = db_query($query);
    foreach ($results as $key => $value) {
      $myKey = $key * 10;
      $form['subscriptions'][$myKey]['somefield'] = ['#markup' => $value->designation];
      $form['subscriptions'][$myKey]['anotherfield'] = [
        '#type'          => 'number',
        '#default_value' => $value->$sTemp,
      ];
      $form['subscriptions'][$myKey]['addRow'] = [
        '#type'  => 'submit',
        '#name'  => $myKey,
        '#value' => '+',
        '#ajax'  => [
          'callback' => '::ajaxAddRow',
          'wrapper'  => 'my_form_wrapper',
        ],
      ];
    }

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

    $form['submit'] = [
     '#type'  => 'submit',
     '#name'  => 'submit',
     '#value' => $this->t('Submit'),
    ];
  return $form;
  }

The ajax callback:
  public function ajaxAddRow(array &$form, FormStateInterface $form_state)
  {
    $myKey = $form_state->getTriggeringElement()['#name'];
    $form['subscriptions'][$myKey + 5] = $form['subscriptions'][$myKey];
    return $form;
  }

The submitForm:
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    if ($form_state->getTriggeringElement()['#name'] == 'submit') {
        do some stuff then exit the form
    }
    else {
      $form_state->setRebuild();
    }
  }

When I click on '+' in some row, the form is displayed again with a copy of the row added to the table.
But the copy is added at the end of the table.
How can I have the copy added just after the original one?

I finally made it work this way:
  public function ajaxAddRow(array &$form, FormStateInterface $form_state)
  {
    $myKey = $form_state->getTriggeringElement()['#name'];
    $formBis = [];
    foreach ($form as $key => $value) {
      switch ($key) {
        case 'subscriptions':
          foreach ($form['subscriptions'] as $key2 => $value2) {
            $formBis['subscriptions'][$key2] = $form['subscriptions'][$key2];
            if (is_numeric($key2)) {
              if ($key2 == $myKey) {           << Here is the row to be copied
                $keyfornewrow = $key2 + 5;
                $formBis['subscriptions'][$keyfornewrow] = $form['subscriptions'][$key2];
                foreach ($formBis['subscriptions'][$keyfornewrow] as $key3 => $value3) {
                    << some code here to initialize content of copied row >>
                }
              }
            }
          }
          break;
        default:
          $formBis[$key] = $form[$key];
      }
    }
    return $formBis;
  }


How we can have layout options at time of node creation just like we select in panels and display suite How we can add layout selection option of display suite or panel during node creation. Any solution available. The layout selection should be at the time of node selection.

It sounds like what you really want is something like the Paragraphs module:

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

It's a good solution for creating flexible, yet structured, content.

Take a look at this video for a good idea of the promises (and pitfalls) of this approach:

https://www.oomphinc.com/notes/2018/11/component-based-design-system-drupal-8-paragraphs/

EDIT: It's not a video, but here's a good place to start with Paragraphs for Drupal 7:

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

And since you are familiar with Display Suite, you might find this to be helpful:

https://stackoverflow.com/a/40479965


User can input multiple terms, results can tagged as some or all of those terms, but not other terms I think I'm going to have to make a custom operator for this, but I figured I might as well ask in case I'm missing something obvious.

Let's say I have (in D7) three nodes tagged with colours:

Node 1

blue
green

Node 2

yellow
red

Node 3

blue
red

Node 4

blue

The user selects red, blue, and green from the exposed filter in a view. This view should return Node 1, Node 3, and Node 4, but not Node 2 (as it is tagged with yellow). Using the "has taxonomy term" filter, the operators "is all of" and "is one of" don't work here, as the first one returns nothing, and the second returns Node 2.

To make things even more complex, I'll need to do this with two different filters in the view (with different sets of taxonomy terms), as well as have a standard "is one of" filter on a third taxonomy term set.

Am I missing a simple solution with this, or do I need to write a custom operator/filter? Thanks!

So if I understand this correctly, you only want the nodes that have all the checked values (and not a subset). So if I checked only blue, only node 4 will be returned and not 1 and 3?

I think you'd be best of to write a custom filter, based on the 'is one of' filter. With that you can select nodes that have the terms attached and than drill down the filter.


Entity Malformation Exception Error When I try to access some specific pages, I get the following errors in my log, one after the other:

  Notice: Trying to get property of non-object in ds_field_formatter_view() (line 1233 of /var/www/sites/all/modules/ds/ds.module).

Followed by

  EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7729 of /var/www/includes/common.inc).

And the page serves the following error:

  Error
  The website encountered an unexpected error. Please try again later.

I had the modules taxonomy and taxonomy manager enabled. I disabled taxonomy manager, but no effect. I wanted to disable taxonomy too, but could not because there was a field with data in it. This has made almost 44 pages of the site with good content in accessible, so any help will be greatly appreciated.

The error was happening due to the fact that database records where not removed when a taxonomy term reference field was deleted. The solution was to install taxonomy orphanage module which removes such references.