How to programmatically modify fields of taxonomy terms? In D7, how do I programmatically add/modify fields to taxonomy terms? They are clearly fieldable and in UI I can add and edit fields in them just like I do in nodes but it proved to be no easy task in the code. Say I have a vocabulary named Fruit with terms like Apples and Bananas. I've added a field to it named main_article_id, so all terms have Name, Description and Main Article Id. When I create a node named Apples that has a reference to the Fruit vocabulary (field_fruit) and Apples term is selected, the code should update Apples term and set its main_article_id field to $node->nid. Here is my code:

//hook_node_insert fires after new node has been inserted into db
function MYMODULE_node_insert($node)
{
    $taxonomy_term_id = $node->field_FRUIT[LANGUAGE_NONE][0]['value'];
    $taxonomy_term = taxonomy_term_load($value['tid']);
    if($taxonomy_term != FALSE)
    {
        //doesn't work
        $taxonomy_term->field_main_article_id[LANGUAGE_NONE][0]['value'] = $node->nid;
        taxonomy_term_save($taxonomy_term);
    }
}

The column name for a field isn't always value; in the case of taxonomy term references it's tid, and in the case of node/entity references it depends on what module you're using.

For a field created using the References module the name is nid, and for one created using the Entity Reference module, it's target_id.

The following code should work a bit better:

//hook_node_insert fires after new node has been inserted into db
function MYMODULE_node_insert($node)
{
    $taxonomy_term_id = $node->field_FRUIT[LANGUAGE_NONE][0]['tid'];

    // $value['tid'] isn't defined anywhere in this function scope so I
    // assume you meant to use $taxonomy_term_id here
    $taxonomy_term = taxonomy_term_load($taxonomy_term_id);
    if($taxonomy_term != FALSE)
    {
        $column_name = 'nid'; // Or 'target_id' if you're using entity reference

        $taxonomy_term->field_main_article_id[LANGUAGE_NONE][0][$column_name] = $node->nid;
        taxonomy_term_save($taxonomy_term);
    }
}


form_alter: Inline entity Form I am using IEF and all is well...until I try ad implement hook_form_alter() and when I access the form via IEF UI (as opposed to directly modifying the entity) none of the changes I make appear to take effect.

I see everything is posted to a ajax/system as well as pulled from when assembling the form...

Is it not possible to hide form elements from the IEF as I would when directly hooking?

Any ideas?

Each line item has a price field which I need to iterate and sum and the apply to the root node. Figured as this module was used in commerce this would be standard practice.

IEF has a hook as outlined in the inline_entity_form.api.php file.

/**
 * Perform alterations before an entity form is included in the IEF widget.
 *
 * @param $entity_form
 *   Nested array of form elements that comprise the entity form.
 * @param $form_state
 *   The form state of the parent form.
 */
function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_line_item') {
    $entity_form['quantity']['#description'] = t('New quantity description.');
  }
}

Check the inline_entity_form.api.php file as there are a few hooks that you may be able to use.


Drupal database not found after running update.php after installing a module I run update.php and then click take me to front page or take me to admin pages the page takes a while to load and eventually gives me the following error:

PDOException: SQLSTATE[HY000] [2002] No route to host in lock_may_be_available() (line 167 of /code/includes/lock.inc).

This seems to happen even if there are no pending updates. There was no changes to settings.php, This also happens if i try and open to many pages to the site at the same time.

the only way to get the site back up and running is to restart the container(Kalabox.)

Any insight on how i can fix this or at least how to trouble shoot it would be great.

"No route to host" looks like something related to DNS. If you're not, try using an IP for your database server in settings.php

If it's localhost, use 127.0.0.1


To know what theme functions are available I wonder if there is any method to obtain all available options for theme() function in Drupal installation? (I mean those one that are declared through HOOK_theme()). Or at least a resource where the most common uses are noted.

P.S. This is not trivial question for me, because almost every module introduces its own hooks for theming and if I don't know about them I can not leverage from theming opportunities. For example if I don't know about theme('table', ....) or theme('fieldset', ....) I have to write my own hooks that, e.g., another developer in his turn will  not be heard of, etc.

Thank you.

The default theme implementations for Drupal core can be found listed here:

http://api.drupal.org/api/drupal/modules%21system%21theme.api.php/group/themeable/7

If you want the theme functions for contrib as well, you could use hook_theme_registry_alter on your install and dump out the theme registry with devel to list all the theme implementations.

e.g

/**
 * Implements hook_theme_registry_alter
 */
function mymodule_theme_registry_alter(&$registry){
  dpm($registry); // requires devel module
}


How can I protect the account of the first user, and not allow administration users to alter it? I want to not allow users with the permission to administer users to alter the account for the first registered user (the one created during the installation of Drupal).
I also want to not allow them to view the user profile for that user.

Is there a module that allows this?

User Protect

From the project page:

  This module allows fine-grained access control of user administrators,
  by providing various editing protection for users. The protections can
  be specific to a user, or applied to all users in a role.

  Note: User Protect has a complicated configuration -- please take the
  time to read the very extensive module help before using it!

  The following protections are supported:

  username
  e-mail address
  password
  status changes
  roles
  deletion
  OpenID identities
  all edits (any accessed via user/X/edit)

  When a protection is enabled for a specified user (or the protection is enabled because
  the user belongs to a role that has the protection), it prevents the
  editing operation in question that anyone might try to perform on the
  user--unless an administrator who is permitted to bypass the
  protection is editing the specified user. The module will protect
  fields by disabling them at user/X/edit.

  User administrators may be configured to bypass specified protections,
  on either a global or per-administrator basis.

  These protections are valid both when trying to edit the user directly
  from their user/X/edit page, or using the mass user editing
  operations.

  The module also provides protection at the paths user/X/edit and
  user/X/delete, should anyone try to visit those paths directly.

  Note: this module is compatible with the RoleAssign module.


Locking nodes or entities to prevent concurrent editing I have not had a need for this, but another (home built PEAR) CMS I support for a client uses locking to prevent two users from being able to edit a piece of content at the same time. It can be irritating but could prevent loss of work.

I suppose if you have multiple site editors it could be invaluable.

Is it necessary? Is the module content lock a viable option?

I believe this is already implemented to some degree. If two users are editing the same piece of content, and one submits changes, the other user will receive this message when trying to do the same:

  The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved.

It happens in the node_validate() function in case you're interested in checking out the code.


Why is it better to use event subscribers rather than hooks In drupal 8, we now have the ability to use event subscribers. What's the reason for this? Is it to work with the new cache API better?

Recently I had a task of needing to extract data from a node when it was viewed, but hook_node_view() is cached (like nearly everything) in Drupal 8. So I ended up using an event subscriber. Why is using event subscribers a better solution? Is it just that it's more object orientated?

You can see this from two perspectives. First of someone who is looking for a way to communicate with Drupal and so is using the hooks and events that exist. The second one is that of a developer who designs these APIs.

Drupal is in the middle of both, on the one side Drupal is a consumer of the Symfony API, almost every piece of code is placed in Symfony events, and on the other side Drupal provides APIs, in form of legacy hooks or custom Symfony events and other methods like plugins.

You probably didn't use one of the Drupal APIs, more likely a Symfony kernel event, KernelEvents::REQUEST. Then you are in the same position as a Drupal developer and this is not a question about hooks or events, because Symfony doesn't provide hooks.

Even if you were using one of the Drupal APIs, you wouldn't have much choice. You would have to select what is provided to you. Only if you design an API in your module to interact with other modules, then you can choose between an event or a hook.


access by term not working I installed drupal 7, and ABT module.

Created taxonomy vocabulary 'Proj' with terms 'proj1' 'proj2'
added term ref 'Proj' field under Article cck
added term ref 'Proj' field under Users (Account settings->manage fields)

Enabled abt's Control "view" access with this field. => Yes, but allow...  on both the term ref fields (Account, article)

Created User1 (proj1 term ref)
Created User2 (proj2 term ref)

Created article PROJ1 article (proj1 term ref)
Created article PROJ1 article (proj2 term ref)

I can see both the articles as admin, but have no access to any of the articles when logged in as User1 or User2

Am I missing any step? please help
Thanks in advance.

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

Create term ref field in User account
And under article cck, add term ref under "add existing field", only then this works!!

Documentation for this module has to be updated, wasted so much of time without proper documentation. Otherwise, great module.


Why we need the key property in the Upsert class if it is never used? I recently tried to use an Upsert query in a table with a composite primary key, but when I go to see the key() method it only allows one parameter and not an array, so we only can only have a singular key:

public function key($field) {
  $this->key = $field;

  return $this;
}

I just tried to use one key and the query works fine! How is posible this? Let see in the core files.

This always will work because if you see the code inside the __toString() function the key property is never used:

public function __toString() {
    // Create a sanitized comment string to prepend to the query.
    $comments = $this->connection->makeComment($this->comments);

    // Default fields are always placed first for consistency.
    $insert_fields = array_merge($this->defaultFields, $this->insertFields);

    $query = $comments . 'INSERT INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';

    $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
    $query .= implode(', ', $values);

    // Updating the unique / primary key is not necessary.
    unset($insert_fields[$this->key]);

    $update = [];
    foreach ($insert_fields as $field) {
      $update[] = "$field = VALUES($field)";
    }

    $query .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);

    return $query;
  }

}

Ok, If the key property is never used I will try to made my upsert without it.

$upsert = $this->database->upsert('forcontu_node_votes')
        ->fields(['nid', 'uid', 'vote'])
        ->values([
          'nid' => $nid,
          'uid' => $uid,
          'vote' => $node_vote,
        ]);
dpm($upsert . '');
// Using dpm() because dpq() doesn't works with upsert https://www.drupal.org/node/2847155
$upsert->execute();

The code will throw an exception because always you need to set the key, if you don't set the key property you will get an exception:

protected function preExecute() {
  // Confirm that the user set the unique/primary key of the table.
  if (!$this->key) {
    throw new NoUniqueFieldException('There is no unique field specified.');
  }
...

If you put comments in the lines

  // if (!$this->key) {
  //  throw new NoUniqueFieldException('There is no unique field specified.');
  //}

the code will works fine, and you will see that if you set or not the key property always the query is the same, in my case:

INSERT INTO {forcontu_node_votes} (nid, uid, vote) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2) ON DUPLICATE KEY UPDATE nid = VALUES(nid), uid = VALUES(uid), vote = VALUES(vote)

So, Why we need the key property in the Upsert class if it is never used?

Note: This is just in the mysql and sqlite clases that the key is not used, but in the postgre clases is used (at this moment I don't have postgre to made some test).

Database Schema:

CREATE TABLE `forcontu_node_votes` (
  `nid` int(11) NOT NULL COMMENT 'Node ID',
  `uid` int(11) NOT NULL COMMENT 'User ID',
  `vote` tinyint(4) NOT NULL DEFAULT '0' COMMENT '1 to 5',
  PRIMARY KEY (`nid`,`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Stores Node votes';

forcontu_blocks.install:

/**
 * Implements hook_schema().
 */
function forcontu_blocks_schema() {
  $schema['forcontu_node_votes'] = [
    'description' => 'Stores Node votes',
    'fields' => [
      'nid' => [
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'Node ID',
      ],
      'uid' => [
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'User ID',
      ],
      'vote' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'size' => 'tiny',
        'description' => '1 to 5',
      ],
    ],
    'primary key' => ['nid', 'uid'],
  ];
  return $schema;
}

You basically said it yourself. The check is there to enforce that Upsert is used in ways that is compatible with all databases, including PostgreSQL, which needs it, as it does not actually support an UPSERT-like operation.

On MySQL, the key doesn't need to be specified as it is only supported on a table with a single unique key anyway:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Query!Upsert.php/class/Upsert/8.2.x

  This class can only be used with a table with a single unique index.
  Often, this will be the primary key. On such a table this class works
  like Insert except the rows will be set to the desired values even if
  the key existed before.


What is standard approach to module development? I'm using module to create content types and views I need.

I prepare the content type in admin, then use export to export the configuration (i.e. views.view.my_view_name.yml, etc).
Then I copy relevant pieces of configuration to the mymodule/config/install directory.
I installed the module and it added the content type.

Now I had to update the content type's field display.

So I changed it in admin and exported.
Copied the updated file to my module.

Now I need to let Drupal know that my module is changed and to "reload" it.

Clearing cache did not help.
Calling /update.php said "nothing to update".
Only thing that actually worked is disable/re-enable the the module. But in that process it breaks all the nodes that used the content type in the module (because for some time the content type was unavailable and therefore it "downgraded" it to normal node).

What is a standard way to develop modules? Removing the module after every change seems ridiculous.

I think this post may be helpful to you:

https://www.mediacurrent.com/blog/registering-migrations-drupal-8

When developing migration configs, you need to update the configs, and it's difficult to get the changes within the install folder to re-register, so there are some scripts you can use, and there are some example drush commands.

Basically you can edit the configs with

$editable = \Drupal::configFactory()->getEditable($config_name);

And you can reinstall configs with

\Drupal::service('config.installer')->installDefaultConfig('module', $module_name);

I'd take a look at the code in /core/lib/Drupal/Core/Config/ConfigInstaller.php in the installDefaultConfig function.  You could probably use part of that code to update just the config you need to update without touching the parts that should stay the same.


How should I perform a redirect in hook_form_alter()? When users log in, I want to redirect them to another page, when they have a certain role. In Drupal 7, I'd use drupal_goto() in hook_user_login() to do the redirect, and hook_module_implements_alter() to make sure that my module is last in the list, so that everything else gets a chance to run.

In Drupal 8, it seems that performing a redirect outside of a controller is not a supported use case.

On that page, gngn has the same problem, and manually generates a RedirectResponse and sends it.

The problem is that, as I see it, send() doesn't terminate the request and the page will have two HTML documents: a 'redirecting to...' page, followed by whatever page would have been there in the first place. Which could be a security issue.

johnvb notes this, and inserts a call to exit() after send().

Presumably something useful is being done in the $kernel->terminate() call in index.php, which is being bypassed by calling exit().

In Drupal 7, drupal_goto() called drupal_exit() to handle this problem.

drupal_goto() was removed says that modules needing to interrupt the request flow should throw an HTTP exception, but there are no 'redirect' exceptions.

As the user login also does a redirect, another approach would be to alter the redirection URL, as suggested on the drupal_goto() change record link above. However, that approach will result in my method being called on every single request, which for what I'm doing seems insanely wasteful.

So, how should I perform a redirect from hook_form_alter() in Drupal 8?

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function [MODULENAME]_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Alter login form and add own custom submit handler.
  $form['#submit'][] = '_[MODULENAME]_user_login_form_submit';

  // Not all forms pay attention to $form['#submit'][]. For these
  // try adding your submit hook to the #submit for the specific
  // button.  e.g.,
  $form['actions']['submit']['#submit'][] = '_[MODULENAME]_user_login_form_submit';
}

/**
 * Custom submit handler for login form.
 */
function _[MODULENAME]_user_login_form_submit($form, FormStateInterface $form_state) {
  // Set redirect to login form.
  $form_state->setRedirect('custom.redirect_callback');
}


In Behat How to Stage Link References in Table Nodes I have a Link field on an article that allows both internal paths and external URLs. How can I stage that type of content in the table node for the article?

(machine name: field_url)

I tried to use:

| field_url:title | field_url:uri |
| Test            | http://a.com  |

But the link Handler throws an error because when you use that format the array keys are 'title' and 'uri' instead of numbers based. (If I change LinkHandler to use the keys it actually works, but obviously breaks other things.)

As for the internal content, I've done entity reference before and they've worked on regular entity reference fields. But when I do something like:

Given "article" content:
| title                  | body       |
| Test Reference Article | Test body. |
And "event" content:
| field_url              |
| Test Reference Article |

The database gets populated with:
field_url_uri = e
field_url_title = T

Has anyone made this work?

This article from nuvole.org helped me resolve the same issue you describe.  From the article:

  A Link field in Drupal offers quite a wide range of options, such as
  an optional link title or internal/external URLs. We can use the
  following notation to work with links in our test scenarios:

When I am viewing a "post" content:
| title       | Post title                                              |
| field_link1 | http://nuvole.org                                       |
| field_link2 | Link 1 - http://nuvole.org                              |
| field_link3 | Link 1 - http://nuvole.org, Link 2 - http://example.com |

  As you can see we use always the same pattern: a
  dash - to separate parts of the same field value and a comma , to
  separate multiple field values.

The one note that I would add to the article is how to handle a link that has a URL, but not a title.  To handle that scenario, I used the following format:

When I am viewing a "post" content:
| link_with_text    | My link text - http://url.com |
| link_without_text | '' - https://google.com    |


Field in View linked to another View I created View "Places" consisting of 3 fields (image,date and title) filtered by content type.

This is to create a page showing thumbnails.

I created another view "Gallery" showing images and I need this View to be linked to the corresponding thumbnail image.

Any idea how i can achieve this?
Thanks to everyone...

Solution 1

You could try making the path for each display some kind of hierarchy and using Menu tab as the menu Page settings in order to display both views next to each other in the primary tabs of a page.

Example paths

mypath/view1 // Display 1
mypath/view2 // Display 2

Solution 2

Add a header or footer to the view in Basic settings and include the link to the other view.

More info on Drupal Menu system.


Preprocess title field in all contexts (sitewide) If you put a backslash in a title of a node I need to rewrite that title and remove the backslash wrapping the text after in  tags. I'm currently doing this using multiple preprocess functions. It seems that I have to create a new preprocess function for every context that a title might appear in:

function project_preprocess_page(&vars){/*rewrite*/}
function project_preprocess_node(&vars){/*rewrite*/}
function project_preprocess_node(&vars){/*rewrite*/}
function project_preprocess_panels_pane(&$vars){/*rewrite*/}

This is working but it's frustrating (and probably inefficient) as there are so many different contexts where titles are displayed.

It seems like there should be a function where I can just override this once and not worry about it anymore. Can anyone suggest a solution?

Thanks

I'm sure hook_node_view can do it for you, but you might need to call drupal_set_title on some situations.


How to display search query in view's results page? I'm using views 3 with drupal 7.

I have a views page listing content of a certain content type 'Clothes'. I have a exposed form(in a block) that filters this list by size(small,medium,large) and color(red,blue).

When I click submit, is it possible to show in the header of my results page like the following?

  Showing results for Small size and Red color:

Yes, ultimately all the filters send the data using HTTP methods GET/POST. If you are not using AJAX with views then HTTP method GET is used to send the data.

To display the information in header add Global:Custom Text field and add below line in it.

Showing results for $_GET[X] size and $_GET[Y] color.

Where : X - name of size field
        Y - name of color field
You will get the names from the url generated after search in address bar.


When should I use DependencySerializationTrait? I have noticed that some classes contain the following line:

use DependencySerializationTrait;

I know this trait is used for serialization, but I don't get when to use it and what kind of classes need to support serialization.

@kiamlaluno described the technical details. This is the background why the DependencySerializationTrait was introduced:

This was the situation before:

     Any class that receives injected dependencies (whether by
  constructor injection or setter injection) typically keeps a reference
  to its dependencies in class members. That's how dependency injection
  works.   Drupal being Drupal, it serializes stuff in several
  places:

        Anything that is in a $form / $form_state : the FormInterface object, but also any object whose methods are used by
  FAPI #callbacks ('#pre_render' = array($some_object,
  'someSubmit')).
        Anything that gets cached, stored in state(), or more generally in the k/v stores...
            When an object is serialized, all the objects it references get serialized as well, and recursively, all the
  dependencies of those objects...   This leads to a
  serialization chain of hell: [#1909418] hit a case where serializing
  the form controller meant serializing the EntityManager -> the
  Container -> (among many other things) the DrupalKernel. This got
  fixed by making sure the kernel was serializable - which is just
  insane :-).

And this was the proposed solution:

  The answer for "DIC-friendly serialization" seems to be:    On
  serialize, do not serialize dependencies.   On unserialize,
  re-pull them from the container. Granted, this breaks mocking, but
  serialization/unserialization is not something you typically do in
  unit tests, so I don't see this as a real problem.

  How to do this might not be too simple though. Two approaches come to
  mind:

     Classes that want to be "DIC-friendly serialized" need to
  implement an unserialize() method that hardcodes the services ids of
  its dependencies. That means doing something similar to the create()
  factory method that is currently used at instantiation time in a
  couple places in core (controllers, some plugins). Hardcoding service
  ids in more and more classes is not a joyful perspective, though.
  Crazy idea:

        Modify the DIC so that each time a service gets instantiated, the service id by which it got instantiated gets placed
  in a public __serviceId (or something) property on the object.
        Classes that want to be "DIC-friendly serialized" do:

            On serialize() : foreach member, if (!empty($this->member->__serviceId)) {just serialize the __serviceId
  string instead of the whole object});
            On unserialize() : $this->member = \Drupal::service($service_id)

Quoted from Injected dependencies and serialization hell


Alternative to FieldCollection and FieldCollection Table i have a fieldcollection field in a entity form type with FieldCollection Table display, and its set to unlimited value. In this field collection there are 5 fields.
After some research I found that after insert 20/30 items, field collection slows down considerably. Infact, in my entityform, after 40 items of fieldcollection, increases the data loading time.

I'm looking for an alternative to fieldcollection with the ability to display the field in table such as field collection table.

can you help me?

Thanks

Oh, good question.

combined with some fancy view work, you could use pretty much any fieldable entity in Drupal to do this.

You could use another content type with entity relationships to link the two. You can render it with an Entity Reference Views Widget and use a views table to format that output.

If you don't want to use a content type, you can also explore custom entities.

Reading:

https://www.sitepoint.com/build-custom-drupal-entities/
https://www.phase2technology.com/blog/developing-a-custom-drupal-entity/
http://www.trellon.com/content/blog/creating-own-entities-entity-api

Now, if you don't want to have to try and do this in code, there is also a great module called ECK (Entity Construction Kit) which allows you to build fieldable entities and use them just like any other all from within the Drupal admin UI.

Hope this helps.


How do I place my script after jQuery? How can I move the following markup after the one loading jQuery and drupalsettings?

<script src="https://abc.ai/js/w?key=abc.jdnwVFfn4YUZA0in"></script>

Actually, the order is the one in the following markup.

<script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"node","currentPathIsAdmin":false,"isFront":true,"currentLanguage":"en"},"pluralDelimiter":"\u0003","ajaxTrustedUrl":{"\/search\/node":true},"user":{"uid":0,"permissionsHash":"a791675a6fdb4f639fabce88c7e91295566b58e25f936b9d181582d9321c503f"}}</script>
<script src="/core/assets/vendor/jquery/jquery.min.js?v=3.2.1"></script>
<script src="/core/misc/drupalSettingsLoader.js?v=8.5.1"></script>
<script src="/modules/abc/js/abc.js?v=1.x"></script>

I used hook_page_bottom() to attach the script in the abc module.

function acobot_page_bottom(array &$attachments) {
  $attachments['#attached']['library'][] = 'acobot/acobot-initialise';
  $attachments['acobot'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#attributes' => array('src' => 'https://acobot.ai/js/w?key=' . $token),
    ],
    'acobot-token',
  ];
}

The content of the abc.libraries.yml file is the following.

abc-initialise:
  version: 1.x
  js:
    js/abc.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

I added weight in the below code(instead of #attached in hook_page_bottom) but it does not change the position .

function acobot_library_info_alter(&$libraries, $extension) {
$libraries['acobot'] = array(
  'version' =>'1.x',
  'js' => array(
     'acobot/acobot.js' => array(
        '#weight' => 100,
     ),
   'dependencies' => array(
     0 => 'core/jquery',
     1 => 'core/drupalSettings'
   )
  ),
);

  return $libraries;
}

The problem is that you're adding it to page bottom region, which is above the JS.

What exactly is $token, is it something personalized or is it a global license key/identifier for the whole site? If the second, then use a library alter hook to load it instead.

See https://cgit.drupalcode.org/jw_player/tree/jw_player.module#n129 for example, that dynamically alters the library definition to either load from a CDN with a dynamic url or a local path that can vary based on input from the libraries module.


How do I update a field to use a different field_type? I have created custom field_type for a field in my content type.  The field 'field_content_category' already exists and is an entity_reference. Changing the yml file and importing doesnt work because there is already data for the field.

My custom field_type is an entity reference and a field to type in an integer.

How do I change the field field_type without creating a new field?

To change the field type you would have to write an update_hook:

Example:

function entity_test_update_8001() {
  // To update the field schema we need to have no field data in the storage,
  // thus we retrieve it, delete it from storage, and write it back to the
  // storage after updating the schema.
  $database = \Drupal::database();

  // Retrieve existing field data.
  $user_ids = $database->select('entity_test', 'et')
    ->fields('et', ['id', 'user_id'])
    ->execute()
    ->fetchAllKeyed();

  // Remove data from the storage.
  $database->update('entity_test')
    ->fields(['user_id' => NULL])
    ->execute();

  // Update definitions and schema.
  $manager = \Drupal::entityDefinitionUpdateManager();
  $storage_definition = $manager->getFieldStorageDefinition('user_id', 'entity_test');
  $storage_definition->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
  $manager->updateFieldStorageDefinition($storage_definition);

  // Restore entity data in the new schema.
  $insert_query = $database->insert('entity_test__user_id')
    ->fields(['bundle', 'deleted', 'entity_id', 'revision_id', 'langcode', 'delta', 'user_id_target_id']);
  foreach ($user_ids as $id => $user_id) {
    $insert_query->values(['entity_test', 0, $id, $id, 'en', 0, $user_id]);
  }
  $insert_query->execute();
}


Only admin can see bulk operations in view I have a view that includes bulk operations that involve flagging (Flag module) or unflagging nodes.  I originally created this in Drupal 6 for another site and have been using it for several years.  I recently re-created this in Drupal 7 whereby four different bulk operations can be carried out in a view on a specific type of node.  This works flawlessly for administrative users.  Authenticated users, however, cannot see the four "operations" buttons in the view I've created.

I've checked permissions everywhere, even "loosening" them to see if they were too tight.  For example, I granted "Edit any node" permission to authenticated users, even though they shouldn't need that for the flag action.  I've checked the view permissions, etc.

The operation calls a simple flag or unflag action and I'm unable to find any other permission(s) that might be impacting this.  I'm hoping someone's going to jog my memory with something simple I've missed.

Edited to add:  I have a similar view on the same site that allows users (through VBO) to send an email to multiple users.  They're able to see the button for this functionality just fine.  Again, leading me to believe this is a permissions issue.

You need to install the sub module in VBO called Actions Permissions.

  ACTIONS PERMISSIONS

  A module called actions_permissions is included in the package. This
  module generates a permission for each action, and VBO honors those
  permissions before showing or executing the corresponding actions.
  This is useful if you want to provide your VBO to several groups of
  users with different privileges: the same view will accommodate those
  different groups, showing to each the actions that they are permitted
  to see.

For your view make sure that you add the relationship to the flag

something like this (adjust as appropriate)

Afterwards navigate to the permissions screen, and enable Execute Flag (or unflag) a node for your roles

For your view of content you need to add the field Bulk Operations: Content (NOT bulk Operations:Flag').

And last but not least, make sure your flag permissions are set for your roles.


how to add a cck field for youtube embed code? I have created a content type. I want to add a cck field to the content type where I can paste the youtube video embed code.

So that when I display the value of that field, a youtube video should display where I should be able to click on the play button and the video should play then.

Any module or any other idea for this problem?

Use Drupal's Embedded Media Field. Here is a quote about it (from the module's project page):

This extensible module will create fields for content types that can be used to display video, image, and audio files from various third party providers. When entering the content, the user will simply paste the URL or embed code from the third party, and the module will automatically determine which content provider is being used. When displaying the content, the proper embedding format will be used.
The module is only an engine, and requires a supported module to function. These include 'Embedded Image Field', 'Embedded Video Field' and 'Embedded Audio Field'. These modules are included in the contrib folder of the module, so they can be easily activated from the module administration page.


When creating an autocomplete form in a custom module how do tell Drupal what modules I need? I want to create an auto-complete form in my custom module that will be loaded in a block. Drupal doesn't seem to be loading the necessary Javascript libraries to work properly. How do I know what needs to be loaded and how/where do I tell Drupal to load these libraries?

hook_block_view:

function my_module_block_view($delta = '') {
    //The $delta parameter tells us which block is being reqested.
    switch ($delta) {
        case 'my_module_my_block':
            $block['subject'] = t('Block Subject');
            $block['content'] = drupal_get_form('my_module_my_form');
            break;
    }

    return $block;
}

Form code:

function my_module_my_form($form, &$form_state) {
    $form = array();

    $form['term'] = array(
        '#type' => 'textfield',
        '#autocomplete_path' => 'my-module-autocomplete'
    );

    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add',
  );

    return $form;
}

The form loads, the field is there, but auto-complete isn't working :(

If I call the my-module-autocomplete path I do get a valid response back when compared with a Content Type edit form. The ajax spinner in the input field never appears so the ajax isn't being called.

See the examples module for a straight forward AJAX Example.


Disable form redirect I want to disable the form redirect.

$form['#redirect'] = FALSE;
$form_state['#redirect'] = FALSE;

Neither of those works.

How can I turn off form redirect? I want to see the output of $form_values.

If you just want see the $form_values array, I suggest you to install Devel and use the function dsm or even you can use the drupal_set_message with print_r.


How to Translate Content type name using i18n module? I am developing a multilingual site that supports English and Norsk bokmal. I have set English as my default language. I wanted to translate the contents and the other things in the site.

My real problem started when I found that I was unable to see the translation of the content type's name. I went to admin/config/regional/translate/translate and translated everything, but still my content type's name is not translated.

I have attached a screenshot of the translation page. Still I don't find a way to translate the content type's name.

First, I must point out that if all you want is a single language non-English website you should not install the Internationalization project, and not enable the Multilingual content module (part of the Internationalization project).

If you have this problem with a single-language non-English web-site, all you need to enable the Locale module (part of core) and enable the Localization update module.  See the first part of this answer to see how to deal with this if you've a problem with content type names not being translated on a single language non-English website.

However, if you're creating a multi-language website where the user interface and the content shall be in multiple languages (due to various detection and selection strategies), then you need to install a project named Internationalization and enable several of its sub-modules, including one named Multilingual content.

However: Do not do this if all you want is to have the the site user interface and its content in a single language that is not English.  The Internationalization project is (IMHO) hard do configure correctly, and still have some serious bugs unfixed. Do not install it unless it is absolutely required.

If you need a multi-language website and you've configured it and you've configured the language settings and already set another default language than English, then the names of content types will not be translated by default, even if the translations for the names of these types are already present in the translated strings listed for the built-in interface.

When you enable the Multilingual content module, a column named Node types will appear in the translate interface overview (if this column do not appear, then the Multilingual content module is not enabled).  For  the names of the content types to appear, you ned to have these translated in the text group Node types as well.  The recipe below tells you how to do this.

I really think this is a bug in the Internationalization module, and as such is off-topic here.  See  Translate interface for nodes, fields, etc. show wrong language in the column for the issue.

However, I was able to get the node types translated at my site by doing the following:

First, I made sure that I installed the Internationalization module and all the required helper modules (such as Multilingual content) before I added any languages.  I also made sure that I used English as the default language all the way during the translation process.

So you do the following with English as the only language enabled (if you've got additional languages enabled, uninstall them, you will also need to disable and uninstall the Internationalization module and all its helper modules to get a clean start):

Download and install the Internationalization project.
Enable the Multilingual content module (part of the Internationalization project).

Then add any additional languages you want, but do not enable them.  This is supposed to add translations for the Built-in interface and Node types. However, to me it looks as if the translations for text group Node types is not automatically imported when you enable a new language after you enable Multilingual content.

You can confirm this by looking under the "Overview" tab of the translation interface:

If the percentage in the "Node types" for your second language is ("Norwegian Bokmål" in the image above) is 0%, the translated strings for the Node types has not been imported into the translation interface.  This means that even after you enable that language, the fallback English strings will be used.

However, it should now be possible to add these translation by hand.  Navigate to the translate tab of the translation interface, and limit search to Node types.

The strikethrough over the string with the two letters in the Languages column means that the translation is missing.  Click "edit" to add the missing translation.

This exact procedure fixed it for me as can be seen from the "Overview" tab below.  The percentage for "Node types" for "Norwegian Bokmål" in now 100%.

After doing all the above, it is OK to set a non-English language as default.


settings.php.lock error I've been working on a Drupal 8 site for a month or so now and development has been progressing nicely until a week ago. It looks like the issues started at just about the same time that the website host applied a server update. The first part of the issue is that I now have a WSOD with the error - The website encountered an unexpected error. Please try again later. I thought that issue might be related to the hosting environment as it's still running php5.6 (now no longer supported by version of Drupal from what I understand).

I thought that if I copied the site files and database to a different environment running php7.2 or 7.3 I might be able to resolve the issue. However since I don't have root access to the dev server I decided to export the database from the dev server as a sql.zip file and then import it into my new database on the new 'test' server and copy the site files across. However while performing the Drupal install I added a prefix for the 'test' database tables. I realised what I had done and went to the settings.php file to change it. When I tried to push the file up via FTP I got a 'failed to write file' error. Instead of trying to sort out the permission via FTP I logged into the Cpanel. I set the permissions of the sites folder to 755 and checked the box to apply the permissions to all sub-folders and files. I checked and all files permissions were updated. I open the settings.php file using the edit option in Cpanel and edited the line with the database prefix (to target the imported tables from the dev site -they have no prefix) to

'prefix' => '',

and clicked 'save changes' and I got the error

"The system failed to create the file “/home/user_account_name/public_html/sites/default/settings.php.lock” (as EUID: 1045, EGID: 1040 1040) because of the following error: Permission denied"

If I change the prefix value and edit anything else like the username I can then save the file without an issue.

Can someone please explain what is happening here. I believe that there is some flag set in the database (or another file) that is preventing me from updating and saving the settings.php and it may also be the reason for my WSOD issue.

Drupal version is 8.6.10 on dev server and 8.7.3 on the test server.

Edit the permissions of the folder it self.
The folder "default" set to 0555, set them to 0755 for editing. Don't forget to restore the default values afterwards!


Where are the main menu links created? I've been doing some w3 validation but I find that my menu's are missing a <ul> for the <li>'s. I have read Where is links__system_main_menu defined? but this doesn't really answer my question. I understand that

  links__system_main_menu is a theme hook pattern of the form [base
  hook]__[context]. When links are themed with
  theme('links__system_main_menu', $vars), theme() will search for and
  use theme_links__system_main_menu() if it has been defined. If not, it
  will use theme_links().

The theme i'm using doesn't do much as far as modify the menu system at first glance. In the theme.php file, it contains:

$variables['main_menu_themed'] = theme(
    'links__system_main_menu',
    array(
      'links' => $variables['main_menu'],
      'attributes' => array(
        'id' => '',
        'class' => array('links', 'clearfix'),
      ),
      'heading' => array(
        'text' => t('Main menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      ),
    )
  );

How can I modify the actual output of the menu?

You can override theme_links__system_main_menu() by declaring a function in your theme's template.php file:

function MYTHEME_links__system_main_menu($vars) {
  $links = $vars['links'];

  $items = array();
  foreach ($links as $link) {
    $items[] = l($link['title'], $link['href']);
  }

  return theme('item_list', array('items' => $items));
}

The above is a very basic example, you'll probably want to take a look at the original code for theme_links() to make that a bit more bulletproof.


Pathauto insert taxonomy term custom url I have change the url of an taxonomy term. Now when i use a field with taxonomy term the url is showing like this:

[node:field-taxonomy:parents:join-path]/[node:field-taxonomy:name]/[node:title]

auto/safety-tools/audi

The taxonomy term has name Safety Tools but i have change the url to just tools.

like auto/tools/audi

How i can load to my node the custom term url path.

I tried [node:field-taxonomy:url],[node:field-taxonomy:url:absolute],[node:field-taxonomy:url:relative] without success

You can use the following pattern:

[node:field-taxonomy:parents:join-path]/tools/[node:title]

(manually set the middle part of the pattern).

Or, if you have several terms (not just Safety Tools), you can use

[node:field-taxonomy:parents:join-path]/[node:field-taxonomy:url:path]/[node:title]

([node:field-taxonomy:url:path] is the path component of the term's URL)


Database object syntax for where conditions giving error I am trying to convert the following SQL query in calls to the database API.

SELECT p.id, p.message,t.posted, p.posted AS reply_date,p.poster_id,t.id,t.subject, t.forum_id FROM punbb.punbb_posts AS p JOIN punbb.punbb_topics AS t ON p.topic_id = t.id WHERE p.id = t.first_post_id;

What I get is the following code.

$query = db_select('punbb_posts', 'p')
  ->fields('p', array('id', 'message', 'posted', 'poster_id'));
$query->join('punbb_topics', 't', 'p.topic_id = t.id');
$query->addField('t', 'posted');
$query->addField('t', 'id');
$query->addField('t', 'subject');
$query->addField('t', 'forum_id');
$query->addField('t', 'first_post_id');
$query->condition('t.first_post_id','p.id');

The code generates the following SQL query.

    SELECT p.id AS id, p.message AS message, p.posted AS posted, p.poster_id AS poster_id, t.posted AS t_posted, t.id AS t_id, t.subject AS subject, t.forum_id AS forum_id, t.first_post_id AS first_post_id
FROM
{punbb_posts} p
INNER JOIN {punbb_topics} t ON p.topic_id = t.id
WHERE  (t.first_post_id = :db_condition_placeholder_0)

Why can't I get "PID"?

You need a where():

$query = db_select('punbb_posts', 'p')
->fields('p', array('id', 'message', 'posted', 'poster_id'));
$query->join('punbb_topics', 't', 'p.topic_id = t.id');
$query->addField('t', 'posted');
$query->addField('t', 'id');
$query->addField('t', 'subject');
$query->addField('t', 'forum_id');
$query->addField('t', 'first_post_id');
$query->where('t.first_post_id = p.id');


How do I theme checkout pages? how do I theme the cart and checkout pages in Drupal commerce?  I have set content, account, billing, and payment parts. Is there any --.tpl.php file to create?

For theming cart page add page--cart.tpl.php in your theme's templates directory.

For theming checkout page add page--checkout.tpl.php in your theme's templates directory. If you want to theme only the checkout review page add page--checkout--review.tpl.php in templates directory.

After adding tpl files do not forget to clear cache.

If you want to know about more hooks do a dpm($variables) inside YOURTHEMENAME_preprocess_page function and look into the theme_hook_suggestions array.

For details read this comment http://drupal.org/node/1142800#comment-5365466


Adding VBO to an entity I have created an entity. I have exposed it to views using hook_views_data().
I can create a view for my data however when I try and add a field for Bulk Operation there is not a field listed for my entity type.

How do I expose my entity to VBO?

In your hook_views_data implementation, you need to specify that the table is about an entity.

You need to define the entity first. I assume you have already defined your new entity using hook_entity_info.

<?php
function hook_entity_info() {
  return array(
    'my_table_item' => array(
      'label' => 'My new entity item',
      'base table' => 'my_table',
      'load hook' => 'my_table_item_load',
      'entity keys' => array(
        'id' => 'mtid',
        'label' => 'My new entity item',
      ),
    ),
  );
}
?>

Then, mention this new entity type in the hook_views_data implementation.

<?php
function hook_views_data() {
  $data = array()
  $data['my_table'] = array(
    'table' => array(
      'base' => array(
        'field' => 'mtid', // Primary field
        'title' => 'My new entity item',
        'help' => 'My Table',
      ),
      'entity type' => 'my_table_item', // <-- Important. Set the entity type here.
      'group' => 'My Table',
    ),
  );
}
?>

VBO will start to show actions that are type of entity in the available actions.
To add new actions, implement hook_action_info.

<?php
function hook_action_info() {
  return array(
    'my_table_do_awesome_things' => array(
      'type' => 'my_table_item', // <-- New entity type here
      'label' => t('Do awesome things'),
      'behavior' => array('changes_property'), //<-- Triggers an entity save.
      'configurable' => FALSE,
      'vbo_configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}
?>

I'm the first author (improved by the community later) of VBO for Drupal 7 drupal.org documentation. Have a look at it as well, for a deeper explanation for hook_action_info and making them configurable at VBO level.


Custom MigrateMap to sync by field or property, e.g. SKU Existing situation: MigrateSQLMap

Normally with migrate API, a migration will use MigrateSQLMap to identify imported rows with existing entities.

This means: A database table named like migrate_map_* will be created for each migration. The * part of the table name is based on the migration machine name. This table associates primary key of the source data (e.g. a primary key column of a csv file) to entity ids.

Whenever a row is to be imported, Migrate API will look into the respective migrate_map_* table, and check if a row with this id was already imported, and if the imported entity still exists. If it does, it will update this existing entity, and update the value last_imported in the migrate map table. If it does not, it will create a new entity, and create a new entry in the migrate_map_* table.

What I want instead: Map to existing entities.

Now what if instead of creating new entities, I would like to update existing entities which were previously created with another mechanism, unknown to Migrate API? E.g. these might have been created manually, or with a home-grown migration script.

In my case, these entities are commerce products, which were created with a custom script which is to be replaced with Migrate API.

The idea is:

Compute an SKU from the imported csv row.
Find out if a product with this SKU already exists.

If yes, update.
If no, create a new product.

If possible, save the import timestamp somewhere.

Solutions I can think of so  far

I can imagine two possible solutions.

A custom migrate map class SkuMigrateMap extends MigrateMap.
Seeing how many abstract methods MigrateMap has, this could be quite a lot of work.
Use MigrateSQLMap, but prefill the table based on existing products.

Question

Is there an existing or recommended solution for this somewhere?

The map class doesn't (and shouldn't) know anything about either your source or your destination - its job is simply tracking the relationships between their keys.

I've done this in the migration's prepareRow(), doing an explicit lookup for a matching destination object, and if found saving that destination ID to the map and returning FALSE to prevent further processing. Look at how migrate_d2d maps user accounts based on email:

// On initial import, if this email address already exists, just map to the
// existing uid and don't allow it to be deleted. When updating, we can
// take the existing uid from the map instead of querying for it. Make sure
// when updating an imported user that we don't apply this logic.
if (empty($row->migrate_map_destid1)) {
  $new_uid = db_select('users', 'u')
             ->fields('u', array('uid'))
             ->condition('mail', $row->mail)
             ->execute()
             ->fetchField();
  // If we haven't mapped the admin account based on email address, map it
  // directly to the destination admin account.
  if (!$new_uid && $row->uid == 1) {
    $new_uid = 1;
  }
}
elseif ($row->migrate_map_needs_update == MigrateMap::STATUS_IGNORED &&
        $row->migrate_map_rollback_action == MigrateMap::ROLLBACK_PRESERVE) {
  $new_uid = $row->migrate_map_destid1;
}

if (!empty($new_uid)) {
  $hash = isset($row->migrate_map_hash) ? $row->migrate_map_hash : NULL;
  $this->map->saveIDMapping($row, array($new_uid), MigrateMap::STATUS_IGNORED,
    MigrateMap::ROLLBACK_PRESERVE, $hash);
  $this->rollbackAction = MigrateMap::ROLLBACK_PRESERVE;
  return FALSE;
}


Grouping nodes by common CCK values in views I can't think of a better title than that, but hopefully it makes sense once I describe it.

I have a node type with 3 CCK fields, we'll call them A,B,C and 1,2,3 and X,Y,Z.

Some nodes will be A,1,X and others will be B,3,Z and etc.

I want to create a view which will pull all of my nodes and list each unique option set as a row so all rows that are A,1,X are in a row with the # of results, and all B,3,Z's are in a row with the # of results.

Is what I want to do possible? If so - how?

Yes it is possible: On your view you have filters, you can filter results by A, then another view with all the results of B; then, if you want these both in a single page I'd suggest a Panels page.


How do I change a field type? I have a content type with a field_maps whose type is Text (plain, long). I needed to change it to Text (plain).

So I've done this SQL statement:

ALTER TABLE node__field_maps MODIFY field_maps_value VARCHAR(200);

It seems that field_type has changed to VARCHAR(200), but there is still one more problem: On the content type and manage fields tabs, the field is still shown as Text (plain, long).

How do I change it to Text (plain)?

I have also get this kind of issue that change field type from one to another with existing data. So as @Eyal mentioned, we can write an update hook to

export data from a field table to a variable
remove fields of all bundles
add new fields of all bundles
restore data to field table

Here is the code example

use \Drupal\field\Entity\FieldStorageConfig;
use \Drupal\field\Entity\FieldConfig;

/**
 * Change node__field_maps from string_long to string type.
 */
function mymodule_update_8XXX() {
  $database = \Drupal::database();
  $table = 'node__field_maps';
  $entity_type = 'node';
  $field_name = 'field_maps';

  $field_storage = FieldStorageConfig::loadByName($entity_type, $field_name);

  if (is_null($field_storage)) {
    return;
  }

  $rows = NULL;

  if ($database->schema()->tableExists($table)) {
    // The table data to restore after the update is completed.
    $rows = $database->select($table, 'n')
      ->fields('n')
      ->execute()
      ->fetchAll();
  }

  $new_fields = array();

  // Use existing field config for new field.
  foreach ($field_storage->getBundles() as $bundle => $label) {
    $field = FieldConfig::loadByName($entity_type, $bundle, $field_name);
    $new_field = $field->toArray();
    $new_field['field_type'] = 'string';
    $new_field['settings'] = array();

    $new_fields[] = $new_field;
  }

  // Deleting field storage which will also delete bundles(fields).
  $new_field_storage = $field_storage->toArray();
  $new_field_storage['type'] = 'string';
  $new_field_storage['settings'] = array(
    'max_length' => 255,
    'is_ascii' => FALSE,
    'case_sensitive' => FALSE,
  );

  $field_storage->delete();

  // Purge field data now to allow new field and field_storage with same name
  // to be created. You may need to increase batch size.
  field_purge_batch(10);

  // Create new field storage.
  $new_field_storage = FieldStorageConfig::create($new_field_storage);
  $new_field_storage->save();

  // Create new fields.
  foreach ($new_fields as $new_field) {
    $new_field = FieldConfig::create($new_field);
    $new_field->save();
  }

  // Restore existing data in the same table.
  if (!is_null($rows)) {
    foreach ($rows as $row) {
      $database->insert($table)
        ->fields((array) $row)
        ->execute();
    }
  }

}

NOTE: Always backup DB and test code before running this code

Other thoughts
In my case, we also have exported configures which means the field type and settings are also included in field_storage_config, field_config, entity_form_display, and entity_view_display config files. So we have to update config settings in those files as well. One easy way could be:

clone your website
delete the field and add a field with the same name again in field UI
export configures to use them in the repo
make sure the config uuid for the field and storage were not changed (change the uuid back if it was) to avoid the import potentially removing data.
import configure after DB update and clear cache again

This is code is inspired by @drugan in the post https://www.drupal.org/node/2816859


Copying a CiviCRM/Drupal install from one server to another (got error) I've tried copying a a CiviCRM/Drupal install from 1 server to another. I copied all the files within the drupal root, and the database, and changed the database details in both Drupal's settings.php file and CiviCRM's civicrm.settings.php file. Drupal now works fine - copying this over appears to have worked, and I've done so succesfully with the same method many times. However, CiviCRM is not fully working. When I visit the main CiviCRM admin page (ie. http://cea-crm.philosofiles.com/civicrm/ on my server) I see CiviCRM's sidebar boxes (indicating it's working to some extent) but, to the right of them, see:

Page not found
The requested page "/civicrm/" could not be found.

When I click on any sidebar box link, such as 'My Contact Dashboard', I likewise see:

Page not found
The requested page "/civicrm/user?reset=1" could not be found.

Presumably I've missed some change I needed to make to reflect my new server setup? I can't see anything in civicrm.settings.php I still need to change, e.g. I've added lines like define( 'CIVICRM_UF_BASEURL'      , 'http://cea-crm.philosofiles.com/' ); and $civicrm_root = '/home/myusername/public_html/d7/sites/cea-crm.philosofiles.com/modules/civicrm';

If you have Drush installed, you can also use the following command to update some of those settings:

drush civicrm-update-cfg

It will try to update the URL and directory settings, which is pretty equivalent to the URL: "http:///index.php?q=civicrm/admin/setting/updateConfigBackend&reset=1".

After that, you can use the API to flush various CiviCRM caches which may be using that data:

drush civicrm-api system.flush


Overriding Drupal core base class I need to override the block configuration form in Drupal 8.

To override the configuration form for a new block we are creating can be done by implementing BlockBase::buildConfigurationForm method.

But I need to alter the configuration form for all the blocks which means overriding the BlockBase class. How can I implement this?

Is there a generic way to override all Drupal Core classes?

No, you can't change the base class. This is a PHP language construct, it's not possible to override it.

I'm not exactly sure what you are trying to do but it is likely that what you are looking for is a plain old hook_form_alter() + third party settings on the block config entity.

The Block class D8 sandbox is a simple module that is doing exactly this and allows to configurabe custom CSS classes for every block.

Note that this is on a different level, you are altering the block config entity and it will only apply to how Drupal core/block.module uses block plugins but not e.g. page_manager. Doing it in a more generic way is simply not possible.


admin/config/people/accounts/fields not displaying I am new to drupal and have inherited a site.
I want to tidying and edit some of the fields n the user profile that already have been added, however
admin/config/people/accounts/fields does not appear as a tab in admin/config/people/accounts
and nothing happens if i try to access admin/config/people/accounts/fields directly.

How can I enable this tab?

The page you are looking for is provided by Field UI core module. Go to /admin/modules and enable it.


How to change title of "Log in" link in account menu for anonymous users? How to change title of "Log in" link in account menu for anonymous users in Drupal 8? Thanks for any suggestions.

As described by @Matt in the answer the menu link is provided by the user module and you can simply decide not to use it and build your own links.

The link in the user module is a dynamic link where a menu link plugin  generates a different title depending on whether the user is authenticated or not.

To change the title you can replace this plugin class:

/**
 * Implements hook_menu_links_discovered_alter().
 */
function mymodule_menu_links_discovered_alter(&$links) {
  $links['user.logout']['class'] = 'Drupal\mymodule\Plugin\Menu\MyLoginLogoutMenuLink';
}

and override the method getTitle() with your own content:

mymodule/src/Plugin/Menu/MyLoginLogoutMenuLink.php:

<?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\user\Plugin\Menu\LoginLogoutMenuLink;

class MyLoginLogoutMenuLink extends LoginLogoutMenuLink {

  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('My Log out');
    }
    else {
      return $this->t('My Log in');
    }
  }

}

A third option would be to change the title in an English to English translation, see How do I translate to English?


How to show users Online and with Photos filter on views want a view that will have this functionality:

https://www.thaifriendly.com/browse.php

There is a radio box to see users that are:

Online
With Photos

I have played with views but can't find a way to make it work, the current_user field works, but it only displays the user that is logged in at the moment, not ALL logged in users

There is not current_user filed in sort either.

Thanks,
Bruno

You can achieve that by using the User Stats module

  Provides commonly requested user statistics for themers, IP address tracking and Views integration.

  Statistics are:

  days registered; join date; days since
  last login; days since last post; post count;
  login count; user online/offline; IP
  address;


Whats causing this garbled text below my pages? Hoping someone might have experienced this and know the culprit code. This keeps appearing below some pages intermittently. Only on logged in members.

You could try searching for part of the string in your codebase.  If you have SSH access then you could run something like:

cd /path/to/document/root
grep -r "W!b\EU6" .

Otherwise if the file is on you local computer then you could use any search tool to look for "W!b\EU6" (those particular characters are from the last line of your screenshot.

Note that it may not be in the codebase.  It could be in the database or could be the output of some function such as an encoding function.  You could check if it's in the database by dumping the database to a .sql file (not compressed) and searching in that.

If you find it and are not sure what to do with the results then paste them here for further advice.


How can I trigger a javascript function when a Drupal ajax call is complete? I need to do some extra things after Drupal ajax is done inserting some stuff into the DOM. With jQuery this was brain-dead simple, but I can't for the life of me figure out how to do it in Drupal 7 :s

Do I add something to my ajaxified link? I read something about attaching a behavior...confusion is setting in...

I ended up adding some additions commands to the page that is being returned by the ajax handler like this:

$commands = array();
$commands[] = ajax_command_invoke(NULL, 'grid_content_loading', array('argument1', 'argument2'));
$commands[] = ajax_command_append('#grid-content-target', $html);
$commands[] = ajax_command_invoke(NULL, 'grid_content_loaded', array('argument1', 'argument2'));
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

And on the client side I created 2 javascript funtions through jQuery:

(function($) {
$.fn.grid_content_loading = function($argument1, $argument2) {
   ...
};

$.fn.grid_content_loaded = function($argument1, $argument2) {
   ...
};
})(jQuery);


Image File Upload via REST case Error 500 response due destination directory not set I'm struggling to upload images to the Drupal 8 site via REST. Finally, I managed to deliver the file to the server, but then the error 500 rased due destination folder not set.
I can't figure where to define this destination directory: in request JSON data or header, or somewhere else in the settings.php or somewhere in REST configuration?
Here my code in Python:
def create_drupal_image(session, oauth, media_name, image_path):
    file_size = os.stat(image_path).st_size
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())

    payload = {
        "filename": [
            {
                "value": media_name + ".jpg"
            }
        ],
        "filemime": [
            {
                "value": "image/jpeg"
            }
        ],
        "filesize": [
            {
                "value": str(file_size)
            }
        ],
        "type": [
            {
                "target_id": "image"
            }
        ],
        "data": [
            {
                "value": "data:image/jpeg;base64," + str(encoded_string)
            }
        ],
        "_links": {
            "type": {
                "href": oauth.base_url + REST_TYPE_FILE_IMAGE
            },
        }
    }
    return create_drupal_entity_impl(session, oauth, ENTITY_FILE_URL, payload)

def create_drupal_entity_impl(session, oauth, url, payload):
    payload_str = json.dumps(payload)
    # print(payload_str)
    endpoint = oauth.base_url + url
    # Set all required headers
    headers = {
        'Content-Type': 'application/hal+json',
        'Accept': 'application/hal+json',
        'Authorization': 'Bearer ' + oauth.access_token
    }
    # Post the new node (a Contact) to the endpoint.
    response = session.post(endpoint, data=payload_str, headers=headers, verify=oauth.verify)
    return handle_create_response(response)

Edited this source core/lib/Drupal/Core/File/FileSystem.php line 488 in order to print the $destination, and it appears to be empty. See '' in the server log below:
AH01071: Got error 'PHP message: Uncaught PHP Exception Drupal\\Core\\File\\Exception
\\DirectoryNotReadyException: "The specified file 'temporary://filemDIAwD' could not be copied
because the destination '' directory is not properly configured. This may be caused by a problem
with file or directory permissions." at /var/www/vhosts/web.site/core/lib/Drupal/Core/File
/FileSystem.php line 488'

Tried to define 'file_private_path' folder in settings.php, added 'tmp' folder under 'sites/default/files' but with no result. What am I missing here?

The missing property was destination "uri"
"uri": [
   {
      "value": "public://" + media_name + ".jpg"
   }
],


adding a phone field in out of stock form of commerce stock notifications drupal commerce Is there a way adding a phone number field (along with the e-mail) in the out-of-stock form that is being used from the commerce stock 7.x-2.2 module and commerce stock notifications 7.x-1.1 module?

I am using drupal commerce kickstart2 and when i have a product that is out of stock the above modules helps no to be able to add them in the shopping cart as long as it gives the option to fill in an e-mail address. I would like to add a phone number field as well under the e-mail address I was wondering if anyone knows how.

Ash joshmiller noted, you can add a field using a form alter and then add another custom submit handler to take the submitted values and do something with that data. You'll have to provide your own DB or come up with some method to store that data on the customer or product.


AJAX callback fails using form_alter on two fields I have content type with two text fields field1, field2
so i'm using hook_form_alter() to alter my form and i'm added for the first field

autocomplete_path path

ajax callback and wrraper

and for the second field i'm added

prefix : with id ind the wrraper of first field

suffix

I want to add a AJAX callback to check the value of a first field and added this value to check a value of second with autocomplete .
The code:
function ajax_callback($form,$form_state) {
        return $form['field_annonceur']['und']['0']['value'];
    }

    function newsletter_form_alter(&$form, &$form_state, $form_id) {
        //dpm($form['field_annonceur']['und']['0']['value']);
        if ($form_id == 'newsletter_node_form') {
            $form['field_annonceur']['und']['0']['value']['#autocomplete_path'] = 'admin/get_path/autocomplete_field1';
            $form['field_annonceur']['und']['0']['value']['#ajax'] = array(
                'callback' => 'ajax_callback',
                'wrapper' => 'autocomplete_id',
            );

            $form['field_campagne']['und']['0']['value']['#disabled'] = TRUE;
            $form['field_campagne']['und']['0']['value']['#prefix'] = '
';
            $form['field_campagne']['und']['0']['value']['#suffix'] = '
';

            if (isset($form_state['values']['field_annonceur']['und']['0']['value'])) {
                ['field_campagne']['und']['0']['value']['#disabled'] = FALSE;
                ['field_campagne']['und']['0']['value']['#autocomplete_path'] = "admin/publicite/autocomplete_field2/{$form_state['values']['field_annonceur']['und']['0']['value']}";
            }
            return $form;
        }
    }

autocomplete_field1($value_field1){};
autocomplete_field2($value_field1,$value_field2){};

but i get the same field  when i select a first field , the second field is hidden !!
before input on field 1

after input on field 1

What am I missing? Thanks in advance!

the solution is to return the target field in the ajax callback
so the code is :

function ajax_callback($form,$form_state) {
        return $form['field_campagne']['und']['0']['value'];
    }


How do I wrap a view row inside a ? I have bad-designed a view, and the result is that I have the following scheme:

Field 1: Category (taxonomy)
Field 2: Node title
Field 3: Image
Field 4: Other data (PHP processed).

The problem is that I need field 1 to appear just once for a group of nodes and not always. As I had to redo all the View, I have made the following process, please tell me if there is a better solution.

Instead of not displaying field 1, grouping by that, etc., as I have some PHP process on it, I do the following:

In views-view-fields.tpl.php I identify the category, and prepend [[BEGIN]]. I identify the last field and append [[END]].

In views-view-unformated.tpl.php I replace [[BEGIN]] and [[END]] with <div> wrappers; depending on the valued inside (preg_match), I make the category title  appear just once at the beginning of the list of products.

Please tell me if that is a valid approach (it works) or it should be more desirable to re-draw the view (hours of changing fields, logic, etc.).

The string replacement outputs an additional <div> which wraps all the complete row of fields. This I had in the view as the field 1 was just another field and did not encapsulate anything. Maybe even if I would set it as grouping field it didn't encapsulate anything. The result I want (and get) is:

<div class="other-class" id="category-119"> divs and HTML stuff from the view  </div>

The only easy and fast way of doing a <div> encapsulation of the row is using those delimiters in the template files.

Add field and Exclude from Display.
Add Global: Text area in the header.
Check Use replacement tokens from the first row
Enter the row pattern
Use css to make it look part of the first row

That will output the first row's field in the header.


Different language on the basis of URL? We all know that its possible in Drupal to set different language on different nodes, but is there any option available from which we can set the language on the basis of URL?

For an instance, we can switch themes in Drupal on the basis of URL:
https://drupal.stackexchange.com/a/816/3808

Check a sample code provided in How to change Drupal's default language programmatically? You can trigger this code yourself based on your requirement.

Another way of doing this can be is 'Use another language than "default" as standard'. And You can find an example of hook_language_negotiation_info() on Drupal 7 default language after translation.


Where to start with creating the theme for selling? I have the task to create the Drupal theme from the existing Wordpress theme that will be sold on ThemeForest.

This is the first time that I'm doing something like this, up until now I was doing the themes for concrete clients according to PSD files, but I think that I need different approach for this.

Until now I usually did the themes as Omega sub-theme, can I create the Omega 4 sub-theme in this case? Can I use base theme at all or I must create theme from scratch?

I noticed that a lot of themes are based on Bootstrap, is that maybe the best way for creating the theme or you suggest some other way (I know this is maybe the question for opinion but I'm looking for the simplest way for creating the theme and Bootstrap is maybe one of the most complicated ways, so because of that I need your opinion and suggestion).

It would be really helpful if you could direct me to some page or tutorial where I can find more information and choose the way in which I will create this theme.

Themeforest audience is mostly end users. So, it does not matter what base theme you use as long as it makes you more productive.

That said, unlike Wordpress where you just upload the theme files zip, you will have to create your own distribution with the latest stable Drupal core, the set of contrib modules you want to theme, the base theme(if you are using one) along with your theme files and assets.

I suggest you start with a base theme of your choice rather than roll out from scratch. Its a huge time saver and most base themes come with sensible defaults, especially Omega 4.


How do I manually set tnid when migrating nodes? I need to manually set tnid during migration.

My code:

  public function complete($entity, $row) {

    // load the newly created node (just in case entity isn't fully populated).
    $node = node_load($entity->nid);
    $node->tnid = '66';
    $node->title = 'CHANGE THIS !';

    // create the field collection item entity
    $item = entity_create('field_collection_item', $values);

    // attach it to the node loaded above
    $item->setHostEntity('node', $node);

    // save the entity
    $item->save();
  }

The node 66 exists and is active, but when I check on translations, the new node isn't associated. Instead the  title is changed with "changed this", then the new node is updated.

With Devel I see that the node has tnid 66.

You want to give the node a language, and set the source node in the translation_source key:

$node->language = 'es';
$node->translation_source = node_load(66);

Reference: https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation_node_prepare/7


Views and Panels: Exclude already displayed items from view I have two views on the frontpage, first one is a gallery and it should show only articles which have "promoted to frontpage" checked. The second view should show all the articles except the ones show in the first view.

I saw this question, but the answer does not help me, because in the second view, i don't want to exclude the "promoted to frontpage" articles, i just want to exclude the first 6 of them, all the other should appear mixed up with the other articles.

I also found this question, but as i use panels, i think it's not working for me.

How can i pass varibales from one view to another, or how to setup conditions to work like that? Or how can i set up more complex filters in a view, like

(promoted_to_frontpage== 1 && offset == 6) || (promoted_to_frontpage == 0)

If your views are not using pager then its easy just add a contextual filter with the following php code

$offset = 5

However, it is very unlikely. The best path is to use hook_views_pre_view($view)

Something like this

function YOUR-MODULE-NAME-HERE_views_pre_view($view, &$items) // note the '&' here!
{
  global $pager_page_array;

  // if this is our view...
  if ($views->name == "my-view-name"
       // ..and we're on its first page...
       && $pager_page_array[0] == 0 ) {
    $items = array_splice($items, 0, 5); // ...then eat up the first 5 nodes
  }
}


Advice for reference the same image for several nodes? I need to show the same image for a several nodes. I have uploaded the image to the server. But, I am not sure how to accomplish or reference this using the image field. Do you have any experience that you can share it? or any other way that I can do this?

In my case the easiest was to do the following steps:

In content/media add the picture.
In your content type create a field type File. Save your content type.
When you add your new content, in your new field, use select media and choose the file that just upload it.

Note: If you delete the new content and there is no other content that reference that picture or file, the file will be deleted and you need to upload it again.

I created my content by using web services. So, I needed to do this programatically. The only I needed was the fid.

In my case I need to use services to create the content type, after testing you need the following and to tell if it should be displayed or not. This is the code in case anyone feels it is useful.

$node->field_file_name_field ['und'][0]['fid']='fid number';
$node->field_file_name_field['und'][0]['display']='1';

If you feel there is a better way or another way to do this. It be great to hear it.


"global" keyword does not work from within drush script I have the following script:

<?php

$GLOBALS['foo1'] = "foobar1";
function g1() {
    echo "g1 " . $GLOBALS['foo1'] . "\n";
}

$foo2 = "foobar2";
function g2() {
    global $foo2;
    echo "g2 " . $foo2 . "\n";
}

g1();
g2();

Running it on the browser gives me:

g1 foobar1
g2 foobar2

Running it via drush scr example.php gives me:

g1 foobar1
g2

Any idea why the global keyword doesn't work when I run the script via drush?

I run this on a D7 site with PHP 5.3.5.

To solve it I had to add global $foo; before declaring $foo.

I suppose it relates to this: http://php.net/manual/en/language.variables.scope.php#98811


How to remove a theme's default menu class from a specific menu? I bought a Drupal 7 premium theme and thus my menus use the theme's default menu class.

How do I remove this class from one of the menus so that it would be a simple HTML list or use the native Drupal menu class?

You can remove all unwanted classes and add your own classes using the code below, Its for a rough idea, use dpm or any debugger to locate exact tool

function THEME_menu_link(array $variables) {
  //unset all the classes
  unset($variables['element']['#attributes']['class']);

  $element = $variables['element'];

  if($variables['element']['#attributes'])

  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}


Why all dates columns in drupal are type=int and not type=date/timestamp/time? I want to make this question short, so as title says "Why all dates in drupal are INT" ?

I've notice that in Schema API there was "datetime" but it was removed in D7.
Also all tables that have time in it (cache_*,semaphore,node etc.) have INT instead of TIMESTAMP.

Before debating "INT vs TIMESTAMP" flame, I would like to remind you that:

DATETIME is obvious what the value represents.
INT is smaller
TIMESTAMP has both advantages.

The thing is that I want to understand what's "philosophy of drupal" for this.

I guess the main reason its that you cannot have two columns with TIMESTAMP and default NOW() value in MySQL according the documentation (see that answer). So seems to be the easier way to workaround it its to use int.


How to Import content without affecting existing contents I have installed Data export and import

.i created nodes dataset file using above module and copied that file and pasted in another drupal site. when i import using that dataset file,it is replacing already existing contents. is it possible to import without affecting existing contents.

Looking at the modules in question it states that the purpose is "...to export data from a site into datasets. These datasets are then imported into another site in such a way that the two sites end up with EXACTLY THE SAME DATA INCLUDING ID NUMBERS."

Looking at the drush commands the module provides there are not arguments to maintain any 'current' data. It will force the state of the dataset.


Autocomplete ahah combo is not working in Drupal 6 I am using Drupal 6.
I have a form which uses autocomplete and ahah in form. It works fine in Firefox but not in Chrome. if its just ahah or autocomplete it works fine but the combo seems to be not working in Chrome. :(
Below is my form

$form['my_fieldset']['my_field'] = array(
      '#type' => 'textfield',
      '#title' => t('Something'),
      '#description' => $client_exists_text,
      '#autocomplete_path' => 'autocomplete/my_field',
      '#ahah' => array(
         'event' => 'change',
         'path' => ahah_helper_path(array('details_fields')),
         'wrapper' => 'details-fields',
         'method' => 'replace',
         'progress' => 'throbber',
      ),
      '#default_value' => ($form_state['values']['my_field']) ? ($form_state['values']['my_field']) : $client_data['my_field'],

Has anyone come accross such issue, please help!
Thanks in advance!

you need delete 'event' => 'change' or change event value


Replace menu's ul li.first a text link with image  link Drupal 7.

For example no matter what menu block would be added to the header region, how can I make it replace first link (which has .first class) with image link?

So Drupal generates links as
Home
 and then apply some function from template.php which would replace it with something like

I found some code which kind of does that, but it needs to enter path to image via Add link under Title field and I don't really need that, the users of the theme won't understand how that works. And it also applies to any links. While I need to switch the very first text link with image link whose path would be given inside template.php

<?php
/**
* Allows for images as menu items.
* Just supply the an image path in the title. The image path will be replaced
* with an img tag. The description is used as alt text and title.
* Implements theme_menu_link().
* Reference: http://chrisshattuck.com/blog/how-use-images-menu-items-drupal-simple-preprocessing-function
*/
function YOUR_THEME_menu_link($variables) {
  $element = &$variables['element'];

  $pattern = '/\S+\.(png|gif|jpg)\b/i';
  if (preg_match($pattern, $element['#title'], $matches) > 0) {
    $element['#title'] = preg_replace($pattern,
      '',
      $element['#title']);
    $element['#localized_options']['html'] = TRUE;
  }

  return theme_menu_link($variables);
}
?>

I can do that with CSS, but I prefer not (client side reasons).

You can override theme_menu_tree.  All it does is output UL tags, so you could squeeze in an LI at the beginning, like this:

    function mycustomtheme_menu_tree($variables) {
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '
' . $home_link . '
';
      return '
' . $home_li . $variables['tree'] . '
';
    }

I've done this exact thing on several sites (but I use nice_menus), here's the code I added to my template.php file in my custom theme:

    function mycustomtheme_nice_menus_tree($variables) {
      $menu_name = $variables['menu_name'];
      $mlid = $variables['mlid'];
      $depth = $variables['depth'];
      $menu = $variables['menu'];
      // Load the full menu array.
      $menu = isset($menu) ? $menu : menu_tree_all_data($menu_name);
      if (isset($menu)) {
        $page_menu = menu_tree_page_data($menu_name);
        $trail = nice_menus_build_page_trail($page_menu);
        unset($page_menu);
      }

      // Allow i18n module to translate strings where available.
      if (module_exists('i18n_menu')) {
        $menu = i18n_menu_localize_tree($menu);
      }

      // Assume depth == 0 by default, overriden if mlid is specified.
      $parent_depth = 0;

      // For custom $menus and menus built all the way from the top-level we
      // don't need to "create" the specific sub-menu and we need to get the title
      // from the $menu_name since there is no "parent item" array.

      // Create the specific menu if we have a mlid.
      if (!empty($mlid)) {
        // Load the parent menu item.
        $item = menu_link_load($mlid);
        // The depth for our parent item, if it exists.
        $parent_depth = ($item['depth']) ? $item['depth'] : 0;

        // Narrow down the full menu to the specific sub-tree we need.
        for ($p = 1; $p < 10; $p++) {
          if ($sub_mlid = $item["p$p"]) {
            $subitem = menu_link_load($sub_mlid);
            // Menu sets these ghetto-ass keys in _menu_tree_check_access().
            $menu = $menu[(50000 + $subitem['weight']) . ' ' . $subitem['title'] . ' ' . $subitem['mlid']]['below'];
          }
        }
      }

      $output['content'] = '';

      if ($menu) {
        // Set the total menu depth counting from this parent if we need it.
        $depth =  ($depth > 0) ? ($parent_depth + $depth) : $depth;
        $output['content'] .= theme('nice_menus_build', array('menu' => $menu, 'depth' => $depth, 'trail' => $trail));
      }

      /* my changes */
      $path = drupal_get_path('theme', 'mycustomtheme') . '/images/home.png';
      $image = theme('image', array('path' => $path, 'alt' => t('Home'), 'title' => t('Home')));
      $home_link = l($image, '', array('html' => TRUE));
      $home_li = '
' . $home_link . '
';

      $output['content'] = $home_li . $output['content'];
      $output['subject'] = '';

      return $output;
    }


Building Custom Drupal Form I am trying to display a custom form with Drupal 7.

Here is what I am trying:

function mymodule_menu() {
  $items = array();

  $items['pay-online'] = array(
    'title' => 'Pay Online',
    'description' => 'Pay Online',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form_generate'),
    'access arguments' => array('access content'),
  );

  return $items;
}

function mymodule_form_generate() {

  $form['first_name'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#attributes' => array('placeholder' => 'First Name'),
  );

// ... etc, more form code

return $form;

What I am getting on the screen is a form, but it is not a 'drupal' form. It's just an array of form fields. No form id, etc.

What do I have to do in Drupal 7 to accomplish this?

You should replace

function mymodule_form_generate() {
  $form = array();

with

function mymodule_form_generate($form, &$form_state) {

I'm not sure if this fixes things for you, but that is the only thing I can see that is out of order.


Get Node ID in hook_field_formatter_view() I'm currently working in a custom video player. For that I've created a content type which uses a field_collection (for the video file and other stuff) and a field_caption for a XML file.

The video file field uses a custom field formatter, which I'm using to theme up the player. I need the field_caption file to be added there so I'm trying to get the node id of the field_section Field Collection in the hook_field_formatter_view() to get that info....with no luck!

If I print $entity->vid from the function parameters I will have NULL, because the field is within a field_section I believe.

Is there a way round this?

Thanks in advance!

As the Field Collection docs says:

  A field collection is internally represented as an entity, which is embedded in the host entity

So what you need to do in your field, is:

Test if it's container is a node. This case works already.
Test if it's a Field Collection entity.
Fallback to situation when you can't obtain parent container or it's an unexpected entity.

Now we'll take care about 2. point. If you can safely assume your field is always in a node, you can use code from answer by Chris Muench:

$model = entity_load_single('field_collection_item', $model_id);
$node = $model->hostEntity();
echo $node->nid;

Note that you are writing formatter, and it means you have no guarantee that host entity will always be a node. If it's not, go to point 3 on my list.


How can I secure a custom module that contains sensitive data? I have made a custom module that contains my backup_migrate module profiles as described in this post.  Inside the array are my keys to log in to Amazon S3, which I certainly want to keep secret.

Putting such data in code inside a module immediately set off an alarm inside my head.  Is this a terrible thing to do from a security standpoint?  If so, why?

As long nobody is able to read this php files, there's no problem. If your host is set-up correctly and you are using the standard .htaccess file which comes with core, you should be fine.

An other question is who has access to your host and your source code. A good practice is to avoid any sensitive data inside git or any other source control system. A way to do this is to have a local.settings.php file a longside your settings.php. You can include it in your settings.php by ading this code at the end of the file:

if (file_exists(dirname(__FILE__) . '/local.settings.php')) {
  include(dirname(__FILE__) . '/local.settings.php');
}

Make sure this local.setings.php file is never visible to unauthorized people.

You can set any system variable in local.settings.php to your needs.


View block listing nodes with lower/higher Nodequeue position I'm trying to build up two blocks for nodes with a Nodequeue position, one above the node listing nodes with lower Nodequeue position and one below the node listing nodes. It should look like a list of linked titles and a full node display in between:

Node A (Linked title only, Nodequeue position: 1)
Node B (Linked    title only, Nodequeue position: 2)
Node C (Current full node display, Nodequeue position: 3)
Node D (Linked title only, Nodequeue position: 4)
Node E (Linked title only, Nodequeue position: 5)

Clicking the title of "Node D" should result in this:

Node A (Linked title only, Nodequeue position: 1)
Node B (Linked title only, Nodequeue position: 2)
Node C (Linked title only, Nodequeue position: 3)
Node D (Current full node display, Nodequeue position: 4)
Node E (Linked title only, Nodequeue position: 5)

I've tried Contextual Filters in Views, but couldn't find a way to limit the list to nodes with lower/higher Nodequeue position.

Any Ideas?

For sorting the nodes according to their position in a nodequeue follow these steps:

Add a relationship "Nodequeue: Queue".
You might want to select "Limit to one or more queues (recommended)" from the options provided and select appropriate nodequeue.
Save.
Click "add" in the sort criteria. Select "Nodequeue: Position"

Select ascending/descending depending on the positions.
Save.

And as for the other requirement that you posted "Current full node display"; I think this could be handled with adding the fields in the view, and controlling their display using JS.


How to relate an image to an article when posting the article in REST API Using the following code we can post a node trough rest API. However, if there is an image attached to this article we need to post the image node first and then include the image fid in the article.I successfully posted the image also but as far as the documentation is very incomplete I am not able to find a way to add the image fid to the second request to attach it to the article.

$serialized_entity = json_encode([
   'title' => [['value' => $node->title]],
   'body' => $node->body_array,
   'type' => [['target_id' => $node->node_type]],
   '_links' => ['type' => [
       'href' => $base_url.'/rest/type/node/'. $node->node_type
    ]],
]);

$response = \Drupal::httpClient()
    ->post($base_url.'/entity/node?_format=hal_json', [
        'body' => $serialized_entity,
        'headers' => [
            'Content-Type' => 'application/hal+json',
            'Authorization' => 'Bearer '. $token->access_token
        ]
    ]);

Is this the right way to attach an image? if yes, what are the request parameters we need to add the image to the node post request?

Any help would be appreciated.
Thanks

See https://www.drupal.org/project/drupal/issues/1927648, this is not supported yet in core.

You can try using https://www.drupal.org/project/better_normalizers to send it base64 encoded instead.


Page region CSS class not applied I am working with Drupal 8.5-x, I am trying to render HTML with bootstrap classes, but I am having trouble. Here is my problem:

I have highlighted (region) and content (region). I am trying to add a
 with highlighted region but to no avail.

I have:

{# Highlighted #}
  {%
    set highlighted_classes = [
      page.sidebar_first and page.sidebar_second ? 'col-sm-6',
      page.sidebar_first and page.sidebar_second is empty ? 'col-sm-9 col-md-8',
      page.sidebar_second and page.sidebar_first is empty ? 'col-sm-12',
      page.sidebar_first is empty and page.sidebar_second is empty ? 'col-sm-12'
    ]
  %}

{# Content #}
  {%
    set content_classes = [
      page.sidebar_first and page.sidebar_second ? 'col-sm-6',
      page.sidebar_first and page.sidebar_second is empty ? 'col-sm-12 col-md-12',
      page.sidebar_second and page.sidebar_first is empty ? 'col-sm-12',
      page.sidebar_first is empty and page.sidebar_second is empty ? 'col-sm-12'
    ]
  %}

when rendered, I get

but I was expecting

I am lost as to where I could have gone wrong.
My info file is as follows:

    regions:
  navigation: 'Navigation'
  navigation_collapsible: 'Navigation (Collapsible)'
  header: 'Top Bar'
  highlighted: 'Highlighted'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Primary'
  sidebar_second: 'Secondary'
  footer_first: 'First Footer'
  footer_second: 'Second Footer'
  footer_third: 'Third Footer'
  footer_fourth: 'Fourth Footer'
  footer_fifth: 'Fifth Footer'
  page_top: 'Page top'
  page_bottom: 'Page bottom'

Any help?

Nevermind I read on attributes: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates

The attribute I was referencing 'highlighted_attributes' was blank. I just added a simpler solution, by referecing to the example of the API:

{% set classes = [ 'red', 'green', 'blue' ] %}

<div{{ attributes.addClass(classes) }}></div>