How do I migrate a multilingual site? I'm currently trying to migrate my Drupal 7 site, which has the Dutch language enabled, to Drupal 8. I have enabled the following modules as instructed in the docs: Configuration Translation, Content Translation, Interface Translation, Language. After running the migration, no nodes have been created on the Drupal 8 site. Moreover, the log contains lots of error messages similar to the ones underneath.

  Migration d7_node_complete:webform did not meet the requirements.
  Missing migrations language. requirements: language.

  Operation on Node complete (Webform) failed

Am I doing something wrong? How can I solve this?

It turned out that some of the migration processes were stuck after the first attempt. Here is how I solved the problem and completed the migration of my multilingual site:

Download and enable the Migrate Tools module and Drush 8
Run drush help to verify that new migration commands such as migrate-status and migrate-import are enabled
Run drush migrate-status and check the migration processes; all statusses should be Idle, but in my case some were stuck on Importing
Use migrate-stop to stop any running processes; according to the documentation, this ''cleanly stops a running operation''
Use migrate-reset-status to set the status of stopped processes back to Idle; according to the documentation, this ''sets a migration status to Idle if it's gotten stuck''
Continue the upgrade via the web browser or Drush


How to load a contributed module load before a custom module? I have a custom module which is having dependency on contributed module.

How can i make sure that contributed module will be loaded before custom module ?

You could update the module weight so that it is lower than that of the contrib module meaning it would get loaded first.


Get display name from hook_preprocess_views_view I want to use hook_preprocess_views_view in order for several views to share the same template, by adding theme_hook_suggestions as described in this article: http://greenash.net.au/thoughts/2014/04/sharing-templates-between-multiple-drupal-views/

function mytheme_preprocess_views_view(&$vars) {

  if (in_array(
    $vars['view']->name, array(
      'whatever'))) {
    $vars['theme_hook_suggestions'][] =
      'whatever';
  }
}

Problem is, I need to specify which display of the particular view it should apply to, rather than the whole view itself. I've tried printing the $vars out which results in a huge recurring array which doesn't seem to include the display name anywhere.

I'm also aware you do this via tagging in the views UI. The same problem occurs though - I can't add a tag to a particular display of a view.

If there is another way I can accomplish this I'm all ears!

You can get the display ID through the current_display property of the View object, e.g.

$view = $vars['view'];
if ($view->name == 'foo' && $view->current_display == 'bar') {
  // ...
}


Form elements as arrays #tree So I'm struggling with the concept of trees in Drupal. I have a form that presents a user with a drop down of number 1 - 27 depending on what they pick the form renders out an equal number of text fields. The goal is to collect all the values put into the text fields into an array even if it's a single element. Right now all that seems to happen is the last field is written as a string to the variable.

What I have:

if (!isset($form_state['values']['number_subscribers'])) {
$form_state['values']['number_subscribers'] = 0;
}

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
$form['subscribers_wrapper_container'][]["#tree"] = TRUE;
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('Subscriber IP Address'),
'#required' => TRUE,
);
}

End goal would be to read $form_state['values']['UCM_SUB'] and have it return an array.

This:

$form['subscribers_wrapper_container'][]["#tree"] = TRUE;
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(...

Can't be what you meant to do. You're creating two new elements there, one with only #tree in it.

Surely you want the tree on the outer element, e.g.

$form['subscribers_wrapper_container']['UCM_SUB']['#tree'] = TRUE;

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
  $form['subscribers_wrapper_container']['UCM_SUB'][] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}


Adding custom html and css to views header and footer Is it possible to add custom HTML and CSS in views header and footer using the administrative UI? I am trying to add a header to my view but that is not giving me any option through which I can add HTML and CSS like the options which are given to us when we add fields in views.
I have tried adding a header using Global Textarea but in this, we can only write HTML not CSS. Kindly tell how can we add HTML and CSS both to the header.

It isn't good practice to intermix HTML and CSS (embed CSS or use inline styles). As a rule CSS is kept separate in files in your theme, and some in modules.

Views allows you to define CSS classes for certain parts of the output, but you still have to keep the CSS rules and declarations in your theme.

If you don't have access to your subtheme for some reason or only want to apply tiny changes you can try CSS Editor. It gives you a place where to enter new CSS rules that will apply throughout your theme.

You still have to edit your Views output to include the custom HTML classes to elements you want to style, you can do that through Global Text area as you already found.

Many themes already assign a lot of classes to various Views parts, so maybe you already have classes relevant to your design and you can use them in custom CSS without adding new classes in HTML.


How to target non admin pages (front end) from a module? From my custom module I'd like to target essentially all front end pages on my site whether it be a node, front page, a views page or taxonomy page. I started out thinking it would be better to use logic that said if not admin or node edit / add but did not seem to have much luck. I came up with this and it seems to work fine but I don't know if accounts for every possible front end type of page that I have mentioned.

function mymodule_page_build(&$vars) {

  // Global node.
  $node = menu_get_object ();

  // Target front end pages
      if ((!empty($node) && arg(2) === null) || (drupal_is_front_page())) {

// do stuff

  }
}

I have a feeling the code does not account for all possible conditions I have mentioned so I am looking for some suggestions. I was thinking to exclude by path would be good except that node edit and node add don't have /admin in the url.

Note: By Target, I simply mean to focus or act upon. Example: If you want to add javascript or css to a specific page or pages from a module, you are "targeting" those pages.

You can use the path_is_admin() function to determine whether or not a path is an admin page, so you can just use the reverse to determine if it's a non-admin page:

if (!path_is_admin(current_path())) {

}


How to theme output from module? I have a simple module that is extracting names from database table. I can display that names in hook_block_view like this:

function example_block_view($delta = '') {

  // $result - an array containing names
  // $names - a string containing names from $result array

  $block = array();

  switch ($delta) {
    case 'xxxxxx':

      $block['title']   = t('Example header');
      $block['content'] = $names;
      break;

  }

  return $block;
}

This will output string with names. But I want to use theme() function for outputting names. So I am continuing by this documentation page: https://www.drupal.org/node/722174

Therefore I edited my code to:

  $block['content'] = array(
    '#theme' => 'example',
    '#header' => 'Example header',
    '#rows' => $result,
  );

But I can't manage out by documentation what should I do next. What is the simplest example of displaying names by custom theme function in my case? Should I do something in template.php of my theme folder, or should I make an hook_theme() in my module? How could I theme the list of names stored in $result array?

You could use hook_theme to register your theme function, but it sounds like you're wanting output an item list which can be done with theme_item_list:

  $names = array('one','two','three');
  $block['content'] = theme('item_list', array(
    'items' => $names,
    'title' => t('My Names'),
  ));

This will fill in your block's content with this:

My Names

one

two

three


Deny access to non-existing sub-paths that bubble up to an existing node I have a drupal site with a page 'About us' (url: example.com/about-us). So when you type the url it correctly opens up the 'About Us' page. But if you append that url with any garbage value or a sensible word (eg:  example.com/about-us/adfasd OR /home) it still opens up the 'About us' page.

Is there a way to restrict this?
That means the user should get an error (something like 'Page not found') if he enters a url for a page which is not valid or if there is not content for that url on the website.

Any kind of help or guidance is greatly appreciated.

check admin/config/system/site-information and configure, in my site it's empty and all wrong urls get a drupal msg that the page couldn't be found.


How to prevent access to a page but allow query I have a page defined by Views module.
(for example: http://namedomainnn.com/cvstaff)

However, I want user only allow to access using query command)
(for example: http://namedomainnn.com/cvstaff?name=user1)

How can I prevent any users to access without query.

Simply check that your URL parameter exists and it's not empty before loading your view:

/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'MY_VIEW_NAME') {
    // If your URL parameter doesn't exist or it's empty, deny access.
    if (!isset($_GET['name']) || empty($_GET['name'])) {
      drupal_access_denied();
      exit();
    }
  }
}

So, accessing:

http://example.com/cvstaff?name=user will work.

http://example.com/cvstaff will show an Access Denied page.


How to make views header sticky while scrolling? I have created report using drupal views and i used views_merge_rows module. Now i wanted to create sticky header of report table. Can any one please help me.

Under the format in views select table.
Got to settings on table there will find the checkbox named Enable Drupal style "sticky" table headers (Javascript) . Enable it
In views preview u can see the sticky headers of the table.


Get all managed file usage by id Is there a way to get all the managed files used by a particular entity, i.e. a node or other module item?

Looking in the file_usage table there is an id column and this is what I want to retrieve fid's by.

Seems like something that there would be a function for, but I haven't found it yet...

I don't think there is such a function. However it's not hard to create your own. Here's an example:

function load_files_by_type($type, $id) {
  // Select all used files by type and id.
  $query = db_select('file_usage', 'fu')
    ->fields('fu', array('fid'))
    ->condition('fu.type', $type)
    ->condition('fu.id', $id);

  // Load all file ids in an array.
  $fids = $query->execute()->fetchCol();

  // Return the file objects.
  return file_load_multiple($fids);
}

You can call it like this: load_files_by_type('node', 64);

Of course you can alter the query to your liking, you could even add a module check.


How to track mailchimp signup form location Mailchimp has an article that explains how to track signup form locations by adding hidden fields to the mailchimp form.

All well and good, but if you put the form in a Drupal block, the location of the form suddenly becomes a variable.

I'm wondering if the token module, and a token in place of a hard-coded hidden field value that tracks location, would be a good approach? The form code for the hidden field currently looks like this:

 <input id="SIGNUP" name="SIGNUP" type="hidden" value="global" />

So, the value "global" is the one that needs to change based the the page that the block is displayed with.

I'm not sure about which token to use, but thinking I'd use something like the page title or page url. In the case of a simple block, do I just need to get and enable the token filter module?

Any thoughts on token as a good option, or other ideas I should consider?

Note - this has nothing to do with the mailchimp module (http://drupal.org/project/mailchimp), which I don't have installed on this site since this site doesn't yet have any notion of user logins.

Links:
token and token_filter.

I'm sure there's a simple answer to the above question, but in the end I took a different approach described here: Create custom signup block with mailchimp module?

Because I'm using hook_form_submit to control processing once the form is submitted, I can add the form location (using request_path()) to the merge variables that are passed back to mailchimp. That way, the form is the same on ever page that it appears, but the location is passed back to mailchimp as part of the sign-up process.


create a menu based on the parent of a drupal book I've been working with the book module bundled with drupal 7 and have a question.
Say i have a book x, and this book contains 4 pages which each have 2 children giving a structure like this:

Book x

Subheading 1

Page 1
Page 2

Subheading 2

Page 1
Page 2

Subheading 3

Page 1
Page 2

Subheading 4

Page 1
Page 2

What I want to do is create a menu that will sit at the bottom of the page which displays links based on these 4 subheadings, i.e. if you were viewing Subheading 1 the menu would display links to the 2 child pages of the subheading. Is this possible?

I figured out my issue, turns out my theme_menu_link function was hiding the book menu block. Once I realised this I placed the block alongside my main menu on the block pages, and used my theme_menu_link to style it.


How can I get links in Views Slideshow to link to different URLs than just one as defined in views? I think I am a little closer to getting my links to work, but I am running into an issue that makes my link point to something like: /content/statshttp://lacrosse.college.edu/content/stats
I am trying to make it so that the maintainer of the website can just enter in the relative URL they want the link to point to.
I have included screen shots of two areas that I think may be causing this.

Thanks!

I found that the answer is that I needed to set the Formatter of the link to be set to the default. You can see in the picture that I was trying different formatting options, but the default is what I needed.


How to use Drupal as static website generator? When I want to convert my Drupal 7 site to html files I have used Static module, which converts Drupal 7 site to html files. However, I will like to know how I can convert a Drupal 8 into static html pages.

Any ideas on how I can make a Drupal 8 website into static html pages ?

I do not think there are any plans for the static project to be ported to Drupal 8.

However, a workaround to turn your Drupal 8 into a static site is by using the wget --mirror command. This will take an exact copy your site.


How to save session data in prod server? I want to save my data in a session: under drupal 8.6

I worked with "Private tempstore" it works locally but not in the server prod only if user is anonymous.

if ($this->currentUser->isAnonymous()) {
  session_start();
}

The same for the native php session.

I ask if it can be stored with php configuration or how?

thank you

Don't use procedural code. Session is now a Symfony object:

class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

Source: https://www.drupal.org/node/2380327

Edit:

What you need to do for debugging depends on your dev environment. If for example you have disabled caching you are not able to debug caching issues. In this case enable caching in dev and see what happens if you add cache metadata to the returned result:

    return [
      '#markup' => $value,
      '#cache' => ['max-age' => 0],
    ];

Cache max-age = 0, because the result in this example changes on each request and is not worth caching.

When this is working the next step is to optimize production performance. Put the code in a #lazy_builder callback or in a block, which is built lazily by default. In both cases this is then auto-placeholdered for certain cache condition like cache max-age = 0, so that the rest of the page can still be cached.


Change the heading User Accounts in user Registration Page I am trying to change the heading in User Registration Page from User Account to Registration.

I tried pre-processing, but in the page variable title is empty and I can only see rendered html.

I also tried using the following code in the settings.php file, but it doesn't seem to work.

$conf['locale_custom_strings_en'][''] = array(
  'USER ACCOUNT' => 'Registration',
  'Add new comment' => 'post new comment',
);

"User account" is the title that an anonymous user see for the "Create new account," "Log in," and "Request new password" pages. Replacing "User account" with "Registration" using $conf['locale_custom_strings_en'] would cause the string to be replaced in every place where "User account" is used, which is not correct.

The solution is to replace the title callback used for user with another title callback. Create a custom module, or add the following code to the custom module you are already using.

function mymodule_menu_alter(&$items) {
  if (isset($items['user'])) {
    $items['user']['title callback'] = 'mymodule_user_title';
  }
}

function mymodule_user_title() {
  if (!user_is_logged_in()) {
    switch (current_path()) {
      case 'user':
      case 'user/login':
        return t('Log in');
      case 'user/register':
        return t('Create new account');
      case 'user/password':
        return t('Request new password');
      default:
        return t('User account');
    }
  }
  else {
    return t('My account');
  }
}

The code I used for mymodule_user_title() is exactly the same code used by Drupal 8 in its user_menu_title().

Other solutions, such as using the String Overrides module don't work too, as they replace the string independently from the context, which is important in this case. Users who are in the page for requesting a new password should not read "Register" as title because they are not registering.


Does Drupal have any security like Dexterity in Plone? Is there anything in Drupal's security like Plone's Dexterity where I can wrap content in my webpage and have it displayed or not displayed based upon security roles?

EDIT:  Thanks.  None of these do what I'm asking, however.  I want to wrap a piece of content on a webpage and based upon the user hide or display it,

<? if user in group or role x (?>
<input type=buttong value="approve employee for vacation time" />
<? else ?>
Supervisor not approved yet
<?)?>

Don't get hung up on vacation.  I'm not looking for a workflow.  It could have said anything.  Show DOB, SSN, etc

I have to query outside databases like Oracle, SQL Server, and so on to get this information.  It will not be resident in the Drupal database, only the security will be.

Drupal has a powerful access control to allow users, site builders and developers grant or deny access to content created in it. The basic of access control is the triplet user-group-permission, where you have users associated to roles associated to permissions.

There's a lot of Drupal contributed modules to extend these features. Content Access is a cool module to restrict content to some roles based on it's own type. Domain Access is another control acccess module, a lil more complicated, which handle the access control to affiliate content to "subsites" (domains, subdomains or non-standard ports). So, if you make a little search in the Modules page of drupal.org for "ACL", "access control" or something like, you'll find a lot of resources to bootstrap your web software development.

Keep drupalizing!


404s on all pages except homepage I have copied a Drupal installation onto my local machine and I am now running into an issue where only the homepage will load and all other links return a 404.

Clean URLS are enabled but even attempting to manually type the URL like:

?q=admin/module

fails...

I have tried the following:

Setting AllowOverride to All
including the mod_rewrite module
including the usr_module
setting the baseURL in settings.php

None have yet appeared to have any effect.

Can anybody suggest anything else to try?

Check that you have the .htaccess file present in your Drupal root folder.


Fivestar votes on drupal fields I'm looking for a drupal module, that allows me to have a fivestar voting for every user (also anonymous) and for every value of a certain field in a node.

What am I trying to do?
I'm trying to have a gallery. Each node with the content-type of "gallery" represents a gallery. In it there is one Image field which allows multiple values. And each image-value should be rateable.

Does anyone know such a module for Drupal 7?

Thanks

You can do this easily with the help of three modules
1) Entity
2) Fivestar
3) Field collection

Step 1. Install above modules.
Step 2. Create content type gallery.
Step 3. Add field collection as a field in the content type.
step 4. Add fields(Image field and fivestar field) to the field collection http://www.example.com/admin/structure/field-collections


Show Targeted Content Based on Content Field and User Roles I'm looking for a way to show specific targeted content based on a content type's field and user role.

For example, if user1 has a "Content Group 1" role, then the view should show content pieces with "field_content_grouping" == "Content Group 1". User2 having a "Content Group 2" role should only be able to see "Content Group 2" and so on. Both roles & field values are exactly the same.

I'm looking for the best way to properly execute this. I've seen people do similar things with pre-render for views or views query alter hooks. My general line of thinking is:

Before rendering views get User roles: Loop and check roles against a specific field "field_content_grouping" - if there is a match, continue else unset node from view.
Return full results (sans content pieces without a matching field &
role).

What's the best way to accomplish something like this? Or am I completely on the wrong track all together? Any and all assistance is greatly appreciated, thanks!

You can make your content field a taxonomy term and you can accomplish this with a simple view without any custom coding.

If we assume

vocabulary Departments
user has field Departments
some users with department selected
token and views_argument_token installed

Add a content view

Add any relevant filters (content types, etc)
Add user relationship
Add contextual filter Has taxonomy term id

Provide default value > token and fill in the current user's selected term id which in this case is [current-user:field_department:target_id]
use Browse available tokens to find the relevant token

Here is a screenshot of a working view


How to add data from one Drupal site to other? Help me solve this scenario,

Assumptions:

Two users user1 and user2 are using their own copy of Drupal site - site1 and site2 on their respective machines.
They use same set of contributed modules (possibly with different configuration of the modules).
Both users add about 300 pages each to the sites.

Now, it is decided that the organization will use the site of user2 and migrate it to the production server. The organization also wants the pages created by user1 to be added to the site created by user2. How can this be done without changing the configuration of the site?

I did use the Backup and Migrate module to migrate the site site2 of user2 to the production server. Now, I am having difficulty in adding the content of site1 created by user1 to the production site; because if I use Backup and Migrate module again it will overwrite the existing pages from the site. It will also change the settings of the modules stored in the database. It is because, the nodes (pages) on site2 and site1 will have nids starting from 1 and auto-incrementing in the nodes table. So, doing a backup and migrate procedure will replace nid=1 from site2 with nid=1 from site1.

Is there a way so that I could append nid from the old database to new?

What other options do I have?

You need to migrate the content of site 1 keeping the config of site 2. My recommendation is to use migrate module coz I prefer it. But you'll have to write code to use migrate module.

There are other modules that may help you like node export, deploy. You can also write custom script but I have had most success with migrate module. You might need to justify the use of migrate in comparison to the content to be migrated, because you'll need to write migration classes but for lets say 300 nodes I'd still use migrate.

I wrote an answer sometime ago which talked about migration of content, users, categories etc. See if it helps you to choose as well - Updating content after major upgrade from 5 to 6 (changes to production site need to be reflected in dev environment)


Odd problems with Drupal 8.7.7 and drupal/jsonapi 2.4.0 I share a release branch with a team of developers and I am the only one having this problem locally (see below).

$ git reset --hard origin/2019-Oct-R2
HEAD is now at 8e5cec59b1 WWW-1599 update spoke service definition and update jsonapi module
$ git status
On branch 2019-Oct-R2
Your branch is up to date with 'origin/2019-Oct-R2'.

nothing to commit, working tree clean

At this point I am on the latest release branch with no tracked or untracked files (same as my colleagues), I then try this:

$ composer update nothing
Gathering patches for root package.
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove drupal/core 8.7.7
    - Conclusion: don't install drupal/core 8.7.7
    - don't install drupal/core 8.7.7|remove drupal/jsonapi 2.4.0
    - don't install drupal/jsonapi 2.4.0|don't install drupal/core 8.7.7
    - don't install drupal/jsonapi 2.4.0|don't install drupal/core 8.7.7
    - Installation request for drupal/core 8.7.7 -> satisfiable by drupal/core[8.7.7].
    - Installation request for drupal/jsonapi (locked at 2.4.0, required as ^2.4) -> satisfiable by drupal/jsonapi[2.4.0].

Can anyone interpret this error message for me?

Composer is showing those error messages because you are updating to Drupal 8.7.7 and the JSON:API module is a requirement the composer.json file contains. (That is why the error message says locked at 2.4.0, required as ^2.4.)

Since the module is now part of Drupal core (as the project page and the release notes for version 8.x-2.4 say), updating to Drupal 8.7.7 would cause the module version to be updated to 8.7.7. (The version of every Drupal-core module is the Drupal version.) That is not allowed from the composer.json file which, with a restriction like ^2.4, just allows versions that aren't higher than 2.

Editing the composer.json file to accept any version of that module would avoid those error messages.
There would still be the problem of having two versions of the module installed in two different directories. I would rather uninstall the module before updating Drupal, but I am not sure how it would possible to preserve the module settings.


How to translate the month name in a date select list field? I have created a date field in user account fields. In manage form display, I have selected Select list as widget.

I want to translate the month names which is displaying a select list.

I checked it here admin/config/regional/translate and in config translation admin/config/regional/config-translation but I don't see any option to translate it.

Is there anything I am missing. Is it possible to translate the month names in the date select list?

Enable the "Language" & "Interface Translation" modules.
Then download the translation .po file on https://localize.drupal.org and import it in /admin/config/regional/translate/import


Which is the difference between the Full content and the Default mode? The FieldUI uses the default as default value for entity form/view displays. But the EntityViewBuilderInterface uses the full as default value.

Also template_preprocess_taxonomy_term() uses the full value to find out if the current page is taxonomy term.

So which one should I look for to know if "default" mode is being used? Should I be checking both values?

I think this applies to D7 too but I'm working with D8 so I'm looking for information within this context.

The argument for EntityViewBuilderInterface is $view_mode.

View displays and view modes are not the same thing.

view_mode can basically be anything you want, you can even make up them on the fly.

What the field formatter/widget system then does is look up if there is a form/view display with for that view mode. If that is the case, that is used.  If not, then it falls back to default.

The view/form modes that you set up in the UI are basically only there to tell field UI that it can create form/view displays for them (the checkboxes at the bottom of the default display page). They are never used at runtime.

So, when you are going to node/1, there is by default no display for full, so it falls back to default. Whereas teaser does have one, so it uses different things. However, you can also enable a form display for full and then it will no longer use default.


How to make diffrent registration form for diffrent role I want to make a registration form that be different for efferent role.
At the first I use the auto assign role for that the user can choose the role.
At now the user can choose him-self's role.
I want if he(or she) choose role "A":
He should answer some field like phone number
and if he(or she!) choose role "B"
He should answer some other field like home address but he cant answer the "phone number" by choosing this role
What should I do?
Is there any module?

Multiple Registration module is the answer. I haven't tried it, but here is what it says

  This module adds ability to create role-specific registration pages.
  Example of situation when this module could help you:

  You need to create two user registration pages. One for general users
  and one, let's say, for hosters. You need to add several specific
  fields for hoster registration page and these fields should not be
  available on general user registration page. Furthermore, if you need
  some hosters fields only on user edit page, without showing these
  fields on registration page, this module could help you too.

Profile2 is another option. It lets you add different fields for different roles which are not part of user entity as opposed to above module.


hook_node_insert, hook_entity_insert, hool_node_presave not triggering I just got a  drupal 7 site with a custom theme handed over to me.

I have to do some stuff when a curtain content type is created by a user, but i am so far unable to get any related hooks working.

So far i tried to add the following to the tempalte.php file

function MYTHEME_node_insert($node) {}

function MYTHEME_entity_insert($entity, $type) {}

function MYTHEME_node_presave($node) {}

Changing MYTHEME to the name of my theme.
I doubbledchecked and the template.php file is used.

Only certain theme-related hooks, and alter hooks, can be implemented by a theme. The hooks you're trying to implement aren't in that list, as they're unrelated to theming.

You'll need to create a custom module and implement he hooks there instead.


Making 'Check out' option appear I am using the Commerce module and Paypal WPS on Drupal 7. When logged in as Admin to my website on a product page I can see the 'Check out' link next to 'View Cart'. However, if I log out and select the same product the 'Check out' option is not there. All I can see is the shopping cart.

What can I do about this?

I have managed to solve this issue by changing the permissions for the Checkout module. I went to People/Permissions/Checkout and enabled 'access checkout' for both anonymous and authenticated users. Previously it was just enabled for Administrator. Hope this helps anyone else with the same issue.


error when updating module I'm trying to update my colorbox module and I keep getting the error:

  Update failed! See the log below for more information. Your site is
  still in maintenance mode.

and below it says:

colorbox

Error installing / updating
File Transfer failed, reason: Cannot remove directory /home/content/02/12910502/html/sites/all/modules/colorbox/..

Next steps
Your modules have been downloaded and updated.
Run database updates

why do I get this error and how can I get this fixed?

EDIT1
I'm using GoDaddy shared hosting. All permissions for files & directories in ftp are set to 755 (owner 12910502) within colorbox/ but I still get this error... - I've never had a problem on other sites I'm working with, weird.
This is drupal core 7.15 - may that be the reason?

EDIT2
How abut if I just replace the directory onthe ftp with the latest version and then run update.php, should this work too?

Sounds like a permission issue.

If you're using ubuntu, make sure the user owner for your modules folder is www-data and 755 permission.

Also, don't forget to run update.php by going to www.yourwebsite.com/update.php after you update drupal core OR any module.


How to reference URL relative to current page in a block I have a custom block where I need to reference a URL relative to the current page (such as node/7/images or node/293/images) that will link to the "Images" view mode I made for the node. I am using a module so that a view mode is accessible via URL (which I have as node/#/images), but I am having trouble getting a working link to /images that would work on any given node.

I have tried to link it to /images and /#/images but have gotten a 404 each time, likely because it is going to example.com/images or example.com/#/images. I have also tried using the Token for current page URL which 404'd as well.

Is there a way, hopefully through the UI, in which I can reference the current node in a way that on any given node the link to the "Images" view mode will link to /node/[current node #]/images?

I have seen ways to implement it using custom modules or code, but I am not very experienced with putting custom code into Drupal and prefer to use the UI is possible.

update

I briefly had a fix, but then I broke it.
I had got it working adding a link that referenced "images/" (without the quotations). While viewing the node, the custom block originally linked to example.com/node/#/images as intended.

However, I then configured the block to be hidden on */images (wasn't necessary to link to the view while viewing it). After I did this, the link broke on the node page, instead now referencing to example.com/node/images, missing the node # in the URL. I have no idea how this got broken as I only worked through the UI

I tried deleting the block then adding it again with no effect

Using "#/images" will direct to /node/123#/images (adding the actual # into the URL) - while this gets the current node id into the URL it doesnt work with the presence of the # symbol

Adding a relative path (without the starting "/") is WRT the current "directory", so when you're on a node page the "directory" is "node" and the NID is the "page". Your "images" is supposed to be another page within the same "directory". That's the simplified explanations about how relative paths work in general.

To solve your problem the easiest way is probably through a Token. Do you have Token Filter or a similar module installed and configured? If your Text format doesn't evaluate tokens you won't get the correct output.

Try some available tokens in your text and see what they output. Maybe there's a [current:path] or similar token, or [current:nid]. When you find one with the output you like you can contruct the link:

Images

or

Images

If you need more control over the Block Visibility you can try Block Exclude Pages.

Another way to create contextually aware links is through Views (Block display). You would have a Node ID as the contextual filter, and override the Link to content field to add "/images" at the end of it.


Is jQuery .once() needed if we filter by context? When implementing a Drupal behavior, a selector can use the 'context' parameter to let the behavior only apply to new elements. On page load the context is the document (I think), on ajax load it is the new ajax content.

Drupal.behaviors.my_behavior = {
  attach: function attach(context, settings) {
    $('.my-selector', context).each(function() {..});

Until now I thought that this alone is sufficient to make sure the behavior runs only once per element.

But in Drupal core and contrib, I see a lot of cases where context is used in combination with .once(), like so:

Drupal.behaviors.my_behavior = {
  attach: function attach(context, settings) {
    $('.my-selector', context).once(function() {..});

Is this ever necessary? Or is 'context' sufficient? And if it is not necessary, why is it used so much in core and contrib?

If it is necessary, does this also apply to click handlers? E.g. would the following cause duplicated click handlers in some cases?

Drupal.behaviors.my_behavior = {
  attach: function attach(context, settings) {
    $('.my-selector', context).click(function() {..});

NOTE: A secondary question would be if 'context' is still necessary if we use 'once()'. My answer to this is: Even if it is not necessary, it is still a good idea because it reduces the search space for jQuery on subsequent calls, thus reducing client-side energy consumption.

NOTE: I encountered this question on D7, but it might equally apply to D8.

The short answer, is 'yes'.
The longer answer is that if all developers properly used the API, you would likely not have to use $.once(). However, you cannot count on developers using the API correctly, so $.once() insulates you against that.

This is because the context passed to Drupal.behaviors is the part of the DOM passed by developers when calling Drupal.attachBehaviors(). However, a lot of the documentation on the web has not specifically stated this, resulting in many developers not passing any value to Drupal.attachBehaviors(). If no value is passed, then the entire DOM becomes the context. This means that your code could be passed through your handler multiple times. This is why $.once() is used.


Output block in particular region from custom module drupal 7 I have a custom module that spits out a form using the drupal form API. What I'd like to do is output a block (a custom menu) in a particular region of the page (using block regions would be the best way I'm guessing.) As of now, the block renders in the top left everytime. How can I output the menu block in a particular region of the page?

function client_menu(){

 $items=array();

 $items['campaign']=array(

   'title'=>'Campaign Manager',
   'description'=>'Area for clients to manage their campaigns',
   'page callback'=>'drupal_get_form',
   'page arguments'=>array('client_campaign'),
   'access arguments'=>array('access client administration'),
   'type'=>MENU_NORMAL_ITEM
 );

 return $items;

}

function client_campaign(){

$block = module_invoke('menu', 'block_view', 'menu-client-admin');
print render($block);

//a bunch of form API stuff...

}

The way you are trying wouldn't work as you are creating a page by
creating a menu item. Rather you should visit your block administration
page at www.example.com/admin/structure/block. Here you will see the list
of all your blocks and available regions in your theme to assign
the blocks.

Here is a screenshot:

In the screenshot where you are seeing the select list with none as selected. This list will let you place your block in the available region.


How do I get machine name by entity type and its ID? How do I get machine name by entity type and its ID?

The code I am using is the following.

$block = \Drupal\block_content\Entity\BlockContent::load(2);
$render = \Drupal::entityTypeManager()->
getViewBuilder('block_content')->view($block);

To get the type and id of a given entity, you can do:

$type = $entity->bundle();
$id = $entity->id();

Some entities, like Node, provide wrapper methods to return the bundle:

$type = $node->getType();

But Block doesn't. So if it is Block that you are after:

$block = \Drupal\block_content\Entity\BlockContent::load(2);
$type = $block->bundle();
$id = $block->id();


Ubercart: maintaining cart content after user login I have a Ubercart site where the user can add items to cart even if it is not logged in: the problem is that when he logs in the cart is emptied and he has to refill it.

Is there a way to save the cart for the anonymous user and, when he logs in, to retrieve the cart content?

The feature looking for is default ubercart behavior. You may have missed with some of your custom code may be with hook_user Check that to see what happens and try disable any custom modules.


Is it good practice for a module to add fields to a certain content type? I have a content type of "album" that is used for displaying reviews of music albums. It has fields like "artist", "genre", "publication_date", etc.

I also have a supporting module that displays relevant albums (that can be purchased elsewhere) for this content type using a 3rd party web service. This module requires a few extra values, like the limit of the relevant albums to be displayed, or a unique id for the artist for the web service.

Is it a good idea to have the module add these extra fields at installation time?

Not only is it a good idea, it is the result of the generally recommended workflow when working with custom content types. If you have other business logic that depends on those fields, I would definitely make them available at install time to make deployment painless.

The Features module can be used to export fields, content types and other configuration into a separate module for you to download, so you do not have to write this yourself. By exporting your configuration to code, it becomes possible to check it into revision control, providing the basis of more complex Drupal modules and distributions.

The KIT specification referred to by Letharion provides a standard for how feature modules (those exported by Features) should be structured for maximum interoperability and portability, but it is the Features module that does the heavy lifting (note, however, that modules created by Features do not name Features as a dependency). Obviously, not every feature you create has to be KIT-compliant, though it does provide a good starting point with a series of sane best practices.

Whether it makes more sense to simply modify the feature module (it is a module like any other, after all!) or make it a submodule of another project depends on the specific use case. If I understand yours correctly, both your supporting module and your content type are used in conjunction to satisfy the same single use case, so I would consider merging them together. Generally, you would make the feature module stand-alone if it could be used independently and satisfies some use case on its own, which does not appear to be the case.

If you have any questions, I would be happy to clarify my answer.


create a downloadable file after submit webform Hello Im not sure if this can be done, but Im trying to make a simple app where you create your own lexical analyzer.

So in the webform I ask the necessary information, then I need the following:

After send the webform generate a script file (from a template I already have done)
I need a way to replace some tokens in the script file with data from the submitted webform
Let the user download the generated script file

Any idea how to achieve this? maybe it is not that complex...

Thank you very much

This module may be used for your idea please use and try this module

Webform2PDF

The Webform2PDF Drupal module is an extension of the Webform module. It can be used to generate PDF document from the results of a form. The generated PDF document can be attached to the form summary e-mail sent by Webform module, or it can be downloaded from the /Results/ page. Different PDF templates can be set for each form. The templates can be formatted with HTML tags, and they can be edited with WYSIWYG Drupal module, making the template creation easy and the templates highly customizable. The output documents will be created by using these templates.


Hide a field on a user profile if the logged in user has a specific role I have many fields added for users. What I want is the following:
If the logged in user has a role W and is viewing a user page that belongs to a user of role X then show field Y. Otherwise, field Y should not be visible.

I have tried using a a module named "Field Formatter Conditions" that supposedly has rules integrations and offers the Event: A field is being rendered and the Action: Hide a field. However, when I select the action to hide the field, There is nothing to be configured and I just get the save button.

Kindly suggest how I can accomplish the target and I prefer if the solution is based on rules.

You need to download and install module Field Permissions as suggested by @Pierre.

Then click on configure link:

Here you will find that Y field on which you want to apply permissions:

Then click on User link and you will be redirected to a form:

Here you can add custom permissions like I did.


Why there is not loadData() method in FileSystem? To use the private:// scheme of Drupal 8 I had to :

Create a folder outside the docroot folder
Implement a  $settings['file_private_path'] = '../private-files'; to designate this folder
Make sure authorization matches the website user to write into it

Then I load the filesystem helper (I could use injection dependency but that is not the point here) :
$this->filesystem = \Drupal::service('file_system');

Prepare the directory in case it does not exists :
$this->filesystem->prepareDirectory('private://any_folder', FileSystemInterface::CREATE_DIRECTORY);

And then I could save a (unmanaged) file:
$this->filesystem->saveData(json_encode(['My Beautiful File Body']), 'private://any_folder/any_file.json', FileSystemInterface::EXISTS_REPLACE);

And this works fine.
But to load the file, I would have expected to have an "opposite" (say, loadData() ) method in $this->filesystem.
And as the file is unmanaged (which is fine) I cannout use File Entity::load() to load it.
So I end up with :
$loadedFile = json_decode(file_get_contents('private://any_folder/any_file.json'), JSON_OBJECT_AS_ARRAY);

Which works fine, but raises questions :

Is this a legitimate way to do it (meaning, using a Drupal helper to save a file, then loading it from a straight PHP function) ?

Why there is no loadData() method in the FileSystem service as I would have expected ?

How does the Drupal scheme 'public:// or private://) is resolved from this PHP function ?

To answer your questions in respective order:

Sure. If there's no built-in API function to make it easier, there's nothing wrong with using file_get_contents since the function can use Drupal's file stream protocols.
The core test,
FileSaveDataTest::testFileSaveData(), is doing this to confirm that saveData() works.
One can only guess about the requirements as the class was composed. saveData() is a wrapper around a file_put_contents() op so that logging can take place when Drupal writes to a temp file. Perhaps there was no need to wrap file_get_contents in the same way?
Drupal has a StreamWrapperManager service class that registered different custom myscheme:// streams with PHP. This manager makes use of core PHP function stream_wrapper_register() to register any injected class that has the tags: { name: stream_wrapper, scheme: myscheme }. For example, look at CoreServiceProvider::register() which registers the private:// scheme when it detects file_private_path settings has been set.


Get fields out of an entity returned by EntityFieldQuery I have a video content type. I run the following query in hook_cron:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'video');
$query->propertyCondition('status', 1);
$results = $query->execute();

This returns number of entity object with property nid, vid and type. I want to use this object to find a value of a particular field of the video (say duration). I don't want to use node_load, because I would have done that in the first place instead of using the query. How can this be done?

It can't - an EntityFieldQuery will only ever load the entity ID, and the bundle keys.

There's no choice but to use node_load_multiple() (or the equivalent if using a different entity type).

$nodes = node_load_multiple(array_keys($results['node']));

Bear in mind that the $conditions parameter of node_load_multiple() is deprecated; in favour of EntityFieldQuery as I understand it.

You could theoretically subclass EntityFieldQuery and override the execute() method to return the fully loaded entities - but you'll also need to extend the class so it always knows what entity type it's querying for; otherwise it won't know which key to use in $results.


Importing pages with different node ids to the live site We have a site in drupal 6.

It's placed in 2 different server with separate databases. One is used for staging and the one is used for live.

We have created a new language section and imported the data with xliff tool to the staging. We have completed the modifications in staging and now we need to push them to live.

But the thing is that the node id's are different in staging and live, and also some pages contains view , block and nodes.

And also I must say that I am a newbie in drupal.

I would appreciate if someone could show me a way to import this new language pages to the live site without using xliff.

Thanks in advance

I've had this problem myself in the past, and importing nodes into a livesite can be quite a head ache at times.

Luckily there's a great module available for D6 called Node Export. It allows you to import / export nodes using a host of different formats such as JSON, CSV, XML etc.

I've used it before exporting a large dataset and I was impressed with how easy it was to implement.

Hope this helps.


Core listed as outdated, but composer is not updating it I'm facing a strange issue with drupal-composer.
It has been installed via the usual command line:

$ composer create-project drupal-composer/drupal-project:8.x-dev ./ --stability dev --no-interaction

Now I want to update drupal/core, and here's what I've got:

$ composer show -l
[...]
drupal/core  8.3.1  8.3.3  Drupal is an open source content management platform powering millions of websites and applications.

$ composer update drupal/core --with-dependencies
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

I've maintained Drupal instances with Composer for monthes, and never faced this kind of issue (other instances have successfully been updated to 8.3.2 or 8.3.3).
I've tried to clear Drupal and Composer caches, and desperately ran /update.php before another try, without luck.

Any thoughts?

Eventually, I fixed this issue running a global:

composer update

Still don't understand what was blocking me from updating drupal/core.


form_submit() and form_validate() doesn't work for tableselect I'm trying to create sort of slider that slides the user selected blocks. to do so I need to list all of the blocks and let the user to select them, I used tableselect. this is my MODULE.module

function deckslider_permission() {
return array(
        'administer deckslider' => array(
                'title' => t('Administer deckslider module'),
                'description' => t('Perform administration tasks for Trails module.'),
        ),
);
}

function deckslider_menu() {
$items['admin/config/deckslider'] = array(
        'title' => 'Deck Slider',
        'description' => 'deckslider configuration',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('deckslider_admin_settings'),
        'access arguments' => array('administer deckslider'),
        'file' => 'deckslider.admin.inc',
        'file path' => drupal_get_path('module', 'deckslider'),
);
return $items;
}

function select_blocks_submit(&$form, &$form_state, $form_id) {
dsm("Hello");
print "Hello";
}

function deckslider_form_select_blocks_alter(){
    $form['#submit'][]='my_submit';
}

function my_submit(){
    dsm("Hello");
    print "d";
}

and it is deckslider.admin.inc:

function deckslider_admin_settings() {
    global $theme;
    $blocks = _block_rehash($theme);
    $header = array(
        'title' => t('Block'),
    );

    $options = array();
    for ($i = 0 ; $i < count($blocks) ; $i++){
        $options[] = array('title' => t($blocks[$i]['info']));
    }

    $form['select_blocks'] = array(
        '#type' => "tableselect",
        '#header' => $header,
        '#options' => $options,
        '#multiple' => TRUE,
    );
    return system_settings_form($form);
}

The problem is the form has a default save configuration button and I can't trigger any function for its submission. this is the output

You either need to change the name of the submit handler so it matches Drupal's naming convention of FORM_FUNCTION_submit, e.g.

function deckslider_admin_settings_submit(&$form, &$form_state, $form_id) {
  dsm("Hello");
}

Or add the handler manually in your form function:

function deckslider_admin_settings($form, &$form_state) {
    global $theme;
    $blocks = _block_rehash($theme);
    $header = array(
        'title' => t('Block'),
    );

    $options = array();
    for ($i = 0 ; $i < count($blocks) ; $i++){
        $options[] = array('title' => t($blocks[$i]['info']));
    }

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

    $form['#submit'][] = 'select_blocks_submit';

    return system_settings_form($form);
}


How do I add an extra css class to my Views rows? I have created a view and it gives me lots of css classes for the rows of my unformatted list:

...but not enough...I need a class for the content type or field name also, something like:

I can see in the style options for the page: 'Row class The class to provide on each row. You may use field tokens...'.

Is this what I need? Do I have a 'field token' for content types? Thanks

Add the field "Content: Type"
Check "output machine name"
Check "exclude from display" for the type field
For the row class, enter [type]


Migration tries to create existing entity I have a D8 migration where I pull remote resources and for each one I create new entity object, apply the resource onto the entity via custom methods on that entity and return the data for this resource as $entity->toArray(). This is how my iterator is getting build. So basically it is an array of entity definitions.

On the target entity I have a field called 'name' which is a unique fields so no two entities with the same 'name' can exist. In the migration I have this field as id key. But for some reason when I run the migration it tries to create a new entity and so the UniqueField constraint will prevent the entity to be saved(I am doing validation in entity's preSave() method) and my migration will fail.

And I cannot figure out why it won't match the existing entity if the 'name' field has a value(I have checked this on multiple places in the code).

The only thing I can come up with it so try to load an existing entity in the prepareRow() myself but that seems as very strange approach and I could basically just completely scratch the migration and write a simple batch.

This is my iterator:

  /**
   * {@inheritdoc}
   */
  protected function initializeIterator() {
    $items = $this->getResourceEntity()->getResourcePlugin()->loadAll();
    $storage = $this->entityManager->getStorage($this->getDerivativeId());

    $items = array_map(function($resource) use ($storage) {
      $entity = $storage->create();
      $entity->resourceMap($resource);
      return $entity->toArray();
    }, $items);

    return new \ArrayIterator($items);
  }

After debugging \Drupal\migrate\Plugin\migrate\id_map\Sql::sourceIdFields and \Drupal\migrate\Plugin\migrate\id_map\Sql::destinationIdFields it looks like it tries to map 'name' => 'id' fields for some reason instead of 'name' => 'name'.

I guess that is because the destination plugin(content entity) returns the entity id field which in this case is id in \Drupal\migrate\Plugin\migrate\destination\EntityContentBase::getIds.

I guess I am missing some crucial information here on how the migrations work.

So yeah, I had to use 'id' in getIds(), and in the iterator I had to try to figure out entity id of an existing entity.

It's rather premature to create an entity at the source plugin, when the destination plugin will create the entity for you... It's much simpler for the iterator to simply produce an array of fields representing the raw data, have the process pipeline map those source fields to the Drupal destination entity's field names, and have the destination plugin 'entity:my_entity' create and save the entity to Drupal.


how to hide the tags and category in the front page My site is http://nbmdemo.16mb.com/

How do I hide tags:featured

Also in http://nbmdemo.16mb.com/?q=node/1

Same thing with: Category: Demo Articles

You can hide it by going to admin/structure/types/manage/YOUR-CONTENT-TYPE/display and just drag the field(s) info the Disabled section.


Upload Image in system_theme_settings form using Zen on Domain Access System I want to upload the image as the background in the settings page of the zen theme.

In zen , It's easy to add an extra field in the theme-settings.php and it's worked at the single site system.

However,I want to add this feature to the domain access Website.

And I got some error message.

I just write the code as belowed:

$form['background_file'] = array(
    '#type'     => 'managed_file',
    '#title'    => t('Background'),
    '#required' => True,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('background_file'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
  );

picture above appeared correct.

But when i push the upload button.

I got the error message belowed

Notice: Undefined index: system_theme_settings in drupal_retrieve_form() (line 806 of /Library/WebServer/Documents/official/includes/form.inc).
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'system_theme_settings' not found or invalid function name in drupal_retrieve_form() (line 841 of /Library/WebServer/Documents/official/includes/form.inc).
Notice: Undefined index: var in variable_realm_form_system_theme_settings_alter() (line 618 of /Library/WebServer/Documents/official/sites/all/modules/variable/variable_realm/variable_realm.module).
Notice: Undefined index: background_file in file_ajax_upload() (line 271 of /Library/WebServer/Documents/official/modules/file/file.module).
Notice: Undefined index: #suffix in file_ajax_upload() (line 280 of /Library/WebServer/Documents/official/modules/file/file.module).

and i really don't know how to fix that.

I just referenced the content below and i can't find the answer.

https://stackoverflow.com/questions/7739345/drupal-7-retain-file-upload
https://stackoverflow.com/questions/11515221/is-there-a-proper-drupal-7-form-api-managed-file-tutorial
http://www.rahulsingla.com/blog/2011/06/drupal-7-handling-file-uploads-and-moving-files-to-the-public-file-system
Is there a way to add managed_file field to theme-settings.php?

Does someone fixed this situation before?

thanks a lot.

The form needs to be able to find system_theme_settings() when getting rebuilt via ajax.

form_load_include($form_state, 'inc', 'system', 'system.admin'); inside of theme-settings.php hook_form_system_theme_settings_alter() should do the trick.


End points for services module not working I have setup an endpoint following this guide. I am getting mixed results, as endpoint/node.xml successfully returns a list of content nodes.

When I try and load an individual node as xml, I just get a blank xml document example below, clicking /endpoint/node/1000.xml results in:

<?xml version="1.0" encoding="utf-8"?>
<result></result>

Also if I try and load it as a ...node/1000.json it just returns false.

Error log is really vague, content is open to non-authenticated users so permissions shouldn't be an issue.

Any help would be fantastic.

Found a work around for this issue, rather than use the node id I am using the UUID. This is now successfully loading the content.

The UUID id is pulled out of the main list of nodes at /endpoint/node.xml, giving a working url of:

/endpoint/node/e2349095-de4f-4827-919f-3ec28cf392a8


Add styles to panes in Panels module I'm using Panels in page manager to create unique pages with different blocks and panes. I'd like to be able to add settings to each individual pane such as adding a class or style.
For example when I edit a block or pane, I receive this window

I'd like to be able to add settings here but I'm not sure where to start.
In Drupal 7 adding styles to individual panes was clear and I'm not sure it even has that functionality in 8 yet.

I managed to create what I was after by using the Plugin Api
I created module with the file structure

mymodule
   -src
      -Plugin
          -Block
           Block.php

In block PHP I used the following

<?php

/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Block\Basic.
 */

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 *
 * @Block(
 *   id = "basic_text",
 *   admin_label = @Translation("Basic MyModule Block (basic_text)")
 * )
 */

class Basic extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function defaultConfiguration() {
        return array(
            'mymodule_string' => $this->t('Enter text here'),
            );
    }

    /**
     * {@inheritdoc}
     */
    public function blockForm($form, FormStateInterface $form_state){
        $form['mymodule_string_text'] = array(
          '#type' => 'textarea',
          '#title' => $this->t('Block contents'),
          '#description' => $this->t('This text will appear in the block.'),
          '#default_value' => $this->configuration['mymodule_string'],
        );
        $form['mymodule_style_selected'] = array(
            '#type' => 'select',
            '#title' => t('Style'),
            '#options' => array(
                0 => t('default'),
                1 => t('black'),
                2 => t('white'),
            ),
            '#default_value' => $this->configuration['mymodule_style'],
        );
        return $form;
    }
    /**
     * {@inheritdoc}
     */
    public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['mymodule_string']
         = $form_state->getValue('mymodule_string_text');
    }
    /**
     * {@inheritdoc}
     */
    public function build(){
        return array(
            '#type' => 'markup',
            '#markup' => $this->configuration['mymodule_string'],
        );
    }
}

I haven't implemented the logic handling the style options but I can now place a pane using the IPE and configure the style pane by pane.


Autocomplete field consisting of multiple fields I am trying something that have been probably discussed already, but I can't seem to find it.  I have a node reference field that I would like to use the "Autocomplete field" function with. However, I would like to show an extra (custom) field, not only the Title of the node. Preferably in a comma separated list, like:

TITLE Node 1, custom field
TITLE Node 2, custom field

etc.

I'm sure this can be done. But I can't seem to find how (and yes.. I'm a beginner I'm affraid).

Thanks a million!

Instead of using Node Reference (References), I suggest you to use Entity Reference module. It has an option to build the autocomplete options with a view so that you can add other fields.


Yearly Archive with month in drupal7 I  want to add news in my website . i want left sidebar and header as in image.

I dont know which module should i use for this.

Months are showing in tabs . I am using Bootstrap3 theme here

There is an archive view that comes bundled with Views (Check out admin/build/views page, views name Default Node view: archive (default)), just clone and modify it as per your need and it should work.

Also check this links containing discussion about the same requirement:

How to create monthly archive block
How to create a monthly archive block for a Drupal blog with Views
Views Archive Drill Down (Year//Month/Day) Block


Display events on Calendar by time I am trying to display the events on a calendar, and have setup the calendar module with the date/ time. I am able to get the events to display on the calendar but they all are showing up as all day events. I have adjusted the formatting of the date/ time every way I can think of.

Adam

Fixed. Had a configuration issues with Dates


Insert value to field programmatically and remove cache from field I have content type feature and i have field hit_count in this c.type, also i have db table - hit_count - example:

nid   hit_count

1     434
2     233
3     512

I want to output hit_count inside my field - hit_count on current node(also should appear on node edit). So for example if node id is 1, field hit_count = 434, and if admin want to edit this field i want to update field value to my table hit_count with current nid and field value hit_count.

To save value into my database table i will use hook_node_update and just get fields nid and hit_count values and update my table.

But i don't know what hook should i use or how to insert this value from database to my field. There are lots of nodes with content type feature.

UPDATE

  My first thought is - why do you use a separate db table for this rather than simply using an integer field in the content type?

Hit count module was created long time ago, client wanted to disable/enable statistics for every content type, so default statistics module does not fit our needs. And now client want to manage this hit counts for certain nodes etc...

Also i managed to insert value to edit form on hook_exit updated custom hit count module.

function hit_count_exit($destination = NULL) {
    if ($node = menu_get_object()) {
        $selected_types = array_filter(variable_get('hit_count_content_types', array()));
        if (!empty($selected_types)) {
            if (in_array($node->type, $selected_types)) {
                db_update('node_hit_counter')
                        ->expression('totalcount', 'totalcount + 1')
                        ->condition('nid', $node->nid)
                        ->execute();
                if($node->type == 'feature') {
                    $val = db_query("SELECT * FROM {node_hit_counter} WHERE nid='$node->nid'")->fetchAll();
                      db_merge('field_data_field_hit_count_node')
                        ->key(array('entity_id' => $node->nid))
                        ->fields(array(
                                'entity_type' => 'node',
                                'bundle' => 'feature',
                                'deleted' => 0,
                                'entity_id' => $node->nid,
                                'revision_id' => $node->nid,
                                'language' => 'und',
                                'delta' => 0,
                                'field_hit_count_node_value' => $val[0]->totalcount,
                        ))
                        ->execute();
                }

            }
        }
    }
}

But right now i see next problem. I need to get rid of Drupal field cache, cuz i see cached value every time i reload page, and if i clear all caches i get current value of hit_count.

I also think you could use an integer field on the node for this - but keeping that aside, the  problem you are facing (the inserted value not being refreshed by the cache) is caused by the fact that you are trying to write in the database table field_data_field_hit_count_node directly. This is definitely discouraged, and you should be using the proper API instead.

Instead of db_merge('field_data_field_hit_count_node')->...->execute() you would want to do something like:

$node->field_hit_count_node[LANGUAGE_NONE][0]['value'] = $val[0]->totalcount;
$node->save();

Doing it this way ensures that the saving is done by Drupal, the caches are cleared as required, hooks as called as necessary, etc.

In addition if you don't mind using the entity module, then you can do this with Entity Metadata Wrappers in a simpler way:

$nw = entity_metadata_wrapper('node', $node);
$nw->field_hit_count_node = $val[0]->totalcount;
$nw->save();


How to display second level menu on another node page I created a menu by Menu block module. I added a link 'to /news' in the first level. The second level are news categories (taxonomy items). I want to display the categories (2 level) on node page. How to do that?

Try the Taxonomy Menu Module. It creates you a menu item for each term which you then can place in your menu.


Drupal View Filter Criteria "Contains Taxonomy" I need to filter based on taxonomy term in my view, I have set up this filter however I would like to return nodes that 'contain', not "Is one of". See screenshot below:

Is there a module or a way I can achieve this? If I put 'vod' instead of 'vodafone' it does not return anthing:

The end goal is to filter nodes from the URL e.g. localhost/numbers?field_company=vod will return nodes for vodafone and vodafoneblahblah.

Add a Relationship of type "Terms in node"
Add a filter "Taxonomy term: Name"

Now you can set "Contains" has an option for your filter


render($content) puts comment form above markup - why? In my node--blog.tpl.php file, I have the following code:

<?php if ($teaser):?>
    <!-- Do some stuff -->
<?php else:?>
    <!-- A little HTML -->
    <?php print render($content);?>
<?php endif;?>

When I load up a blog page, the comments form is actually above the content.  This isn't some CSS quirk - it's above the content in the HTML structure.

How have I managed that, then?  Can anyone suggest a way to ensure the comments form appears in its rightful place, below the content?

There is a show weights link in Drupal 7.14. If you go to Comment Fields in your content type /admin/structure/types/manage/.

I set the weight, and comments still show above the body.


How to hide node edit / delete link in a view conditionally? I have a view that lists a content type in a table. There are edit/delete links so the users can edit the content. I want to display these links conditionally.

These are just orders sent in by customers and I only want to let them edit or delete them until the "status" field is set to "processed". Once their order has been processed, they shouldn't be able to modify nor delete it.
I can show them a message via a custom module, but it would be nice to remove the edit/delete buttons for these nodes.

Although an old issue, the way to do this in D7 commerce is with

hook_commerce_entity_access

/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order') {
    // Prevent edit and delete of 'processed' status orders
    if ($entity->status == 'processed' && ($op == 'edit' || $op == 'delete')) {
      return FALSE;
    }
  }
}


Why Conditional Fields Validating the Hidden Fields? I have preset sizes like small, medium and large and an option to provide custom size. If some one selects custom option from a select list the measurements fields appears through conditional fields and if some one select small medium or large the measurements fields hides.

The problem is when I am submitting a form by selecting Small, Medium or Large option from select list it gives error that measurements fields are required.

I have tried to add additional condition to make the fields optional if the select list has the values small, medium or large but still getting the same error.

Check that your measurements field isn't set as required in the field settings in content types. You could also provide a default of 0 I guess.


What's wrong with my taxonomy links or my taxonomy view and contextual filter? I have a D7 view displaying all items tagged "food" at

mysite.com/industry/term/food

But my taxonomy terms for "industries" link to e.g. mysite.com/industry/food
(i.e. without /term/)

I thought I could update the view to make the page path: /industry/%
instead of: industry/term/%
but that breaks the view

so I thought I might be able to update my Taxonomy url aliasing pattern to be:

[term:vocabulary]/term/[term:name]

instead of [term:vocabulary]/[term:name]
but that doesn't work either :( or at least, it doesn't update all pre-written aliases...

I read this:
http://www.webbykat.com/2012/04/overriding-default-taxonomy-page-view-drupal-7
which pointed to a solution from 2009 here
https://www.drupal.org/node/394062#comment-1953504
but if I use Name or ID (rather than "name converted to ID") in my contextual filter it breaks the view

What am i doing wrong - I'm sure it's something simple and I'm just being blind!?

You mentioned that changing the alias doesn't update all pre-written aliases. Could you pick one term, edit it, and hit "Automatic alias" under URL aliases so that it updates, then post whether that resolved the issue for that individual term?

If so, all you need is to bulk update aliases for that vocabulary, which can be done with a VBO - I'll detail how if that's the issue.


Drupal service session handling In my angular app, I am trying to use headless Drupal using service module. I can't able to find a proper documentation to handle session authentication for each subsequent calls. My each request ends in "csrf validation failed" message.

Can anyone suggest a good tutorial or steps to handle session authentication?

For any POST, PATCH or DELETE request, you always need to pass along the X-CSRF-Token.

After logging in via REST, the new X-CSRF-Token should be provided in that data result, then you can just set that aside (in a global variable, in local storage, etc) and then pass it along with each request.

I personally use (and created) this module to make things easier: https://www.drupal.org/project/angular_drupal


Features local permission issue Warning: mkdir(): Permission denied in features_export_build_form_submit() When I am trying to generate a new feature on local, it runs in permissions issue beginning with

  Warning: mkdir(): Permission denied in
  features_export_build_form_submit()

There is no www-data user on local. My environment is Mac OSX Mountain Lion.

This is an extension of this question
Folder permissions, owner/groups

Which deals with a similar issue on the server level. I am looking for the response for my local.

Current permissions for sites/all/modules/features are

  drwxr-xr-x  22 myusername  wheel   748 Aug  7 16:41 features

wheel is the group and root is its user.

Thus what user should own this directory to not run in to the mkdir permissions denied issue on Drupal frontend?

Thanks.

The point is that your folder needs to runs under the _www group (www-data is the group and user for linux machine). You can do it within a terminal or with the finder too.
So find the webserver root folder (~/Sites/MYDRUPALSITES, for example) and pull up the Finder Get Info window.

Then on the bottom left corner, click the group icon (The picture with 2 people) and then hold Option then click the “+” button. This will allow you to select system users and groups. Find the World Wide Web group, select that and change the group priviledge to “Read & Write” and then use the cog-wheel to “Apply to enclosed items…”

Or just run the following chgrp (change group) command via Terminal : easiest way (y) !

cd ~/Sites

sudo chgrp -R _www MYDRUPALSITES/

That's the most revelant answer I can answer with your question. But it can also be the owner or a bad installation permissions set. Simple google : permission issue mamp/xammp. Or you could also run

sudo chmod 777 -R MYDRUPALSITES/

But I clearly do not recommend it on a online production (in local it's "acceptable").


What is the best way to theme page--front with twitter bootstrap? I am trying to create a user dashboard by design a flat menu for page--front.tpl.php, and the twitter 3.0 bootstrap. My current site is using Omega's OHM responsive theme as default, so my question is, how do I apply twitter bootstrap to just a SINGLE tpl file?

There's a part 2 if its related, copying page.tpl.php and calling it page--front.tpl.php isn't being recognized (I do this within ohms templates/system dir, and cleared cache). I've read through Drupal.se, and googled it and tried the variety of things - but I guess I don't understand how drupal recognizes page--front. Do I assign a piece of content as home page then it gets applied? If so, that's the page I need specifically themed with bootstrap only.

You might want to switch the theme entirely. You could simply use something like: https://www.drupal.org/project/themekey

Regarding the regcognition of page--front.tpl.php,
rename your existing page.tlp.php to page--default.tpl.php


Drupal 7 Execute a mysql sql query in Views using Views PHP I'm trying to do a custom sql query in Views for Drupal 7 and I have the following code in my views php, but I'm not sure if I'm doing this correctly.

<?php $xx = db_query('SELECT * FROM acl_node INNER JOIN acl_user ON acl_node.acl_id=acl_user.acl_id INNER JOIN users ON acl_user.uid=users.uid WHERE nid=201');

print_r($xx);
?>

After running that I get a big array, but none of the data in it. I tested the sql query and it is indeed working via my sql builder tool.

You must avoid using php in UI.

As a solution
  - Either you can override the views template.
  - Or you can try implmenting hook_views_pre_render.(Reference https://knackforge.com/blog/sivaji/how-alter-views-field-output-programmatically)

Now, about fetching the results from query result object.

Other than iterating through the result set, there are other ways to fetch results.


The username has not been activated or is blocked. using custom login form In my module tpl file I'm calling

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

Then in my .module file I have this function:

function mymodule_login_form($form, &$form_state){
  $form = drupal_get_form('user_login');
  return $form;
}

So the user_login form gets called and shows up but when I try to use it ( submit it ) I'm always getting the error message: 'The username has not been activated or is blocked.'

When I change the tpl file to:
<?php print drupal_render(drupal_get_form('user_login')); ?> it works and giving the correct error messages or logs the user in.

The problem with this is that I'm using it in a popup screen and want to display the error messages in the popup screen using ajax. So I need to alter the user_login form. I know how to do that but I'm not getting past the error message 'The username has not been activated or is blocked.'

If your requirement is displaying user login form in AJAX POPUP then you can consider Ajax Login/Register module.

This module provides a block with 2 links (Login, Register) for the
anonymous user.
When the user clicks on Login or register the
requested form appears in a nice ajax popup.


How to create dynamic query for inner join on same table? I want a dynamic query to do inner join on same table.

My query is:

SELECT t1.table1 FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id AND t1.name = t2.name"

I want to join table1 and table2 based on id and name present in table2.

What is the equivalent dynamic query in Drupal for this?
How this can be achieved?

$query = db_select('table1','t1');
$query->join('table2','t2','t1.id1=t2.id2');
$query->fields('t1', array('some fields'))
      ->fields('t2', array('some fields'));
$result = $query->execute()->fetchAll();

Then you can do print_r stuff into $result like

echo "<pre>";print_r($result);echo "</pre>";

If you have devel module installed and enabled, then you can also use:-

dsm($result);

This will give the whole result in form of array.
If you need in form of object, then you need to modify few lines of code like this:-

$data = $result->execute();
while($result = $data->fetchObject()){
  //Do your related stuff
}

I think it will help a lot. Thanks.


How does one 'override' string used in a core file? I'm trying to change the text "Already a member?" located in commons_core.blocks.inc to a different value. I would preferrably like to override this value and not directly edit a file in /profiles/drupal_commons/.

Can anyone recommend a good solution?

For overriding a few text strings the easiest way is probably to use the String Overrides module:

  Provides a quick and easy way to replace any text on the site.

UPDATE

The line that sets this particular string is:

$block['content'] = t('Already a member? !login', array('!login' => l(t('Login'), 'user')));

Once it's built up, the string will actually look something like this:

'Already a member? Login'

That's why you're having difficulty targeting it with the string overrides module at the moment. If you're not developing a multilingual site you might just get away with inspecting the  tag in the block, and using that HTML in string overrides. I'm pretty sure it'll work.


Node template only on specific page (Drupal 7) I've been reading through a ton of Drupal 7 theming docs but can't seem to find my answer.

Here's what I'm trying to do. I have two content types article and feature.

Nodes of both content types are displayed on my /blog page via the Views module. All working great so far.

When the node of type article is listed, it uses the node--article.tpl.php template, and when a node of type feature is listed on the blog listing page, is uses node--feature.tpl.php.

This is all as expected, BUT for feature types, I want to display the node--article.tpl.php template only on the /blog page, and use node--feature.tpl.php (the default) for that type otherwise.

In other words, I'd like to keep the templates separate, but use the same template for both article and feature types on the blog listing page (node--article.tpl.php).

Is there way to create a node-page-specific template file (use this template for this node ONLY if on this page)?

add template.php:

function THEMENAME_preprocess_node(&$vars) {
  if (request_path() == 'specific/page') {
    $vars['theme_hook_suggestions'][] = 'node__specific';
  }
}

and create file node--specific.tpl.php in theme dir


Reading nested field collections I have a field collection called field_sections that has inside it it 2 fields:

field_section_title (just plain text field)
field_menu_item(field collection with 4 fields)

field_menu_item has 4 fields

 - field_item_title
 - field_menu_image
 - field_item_price
 - field_item_description

  I would like to build an array sections, and those sections are
  objects that contain menu_items, which are objects that contain
  menu_items.

I have tried something so far, but unfortunately I can only get the sections and not the nested menu_items and their values. For some reason in their place, only a number is contained instead of the actual field value.

How can I build those arrays?

ps:my apologies for the basic question, but I'm just now getting my hands dirty with PHP and this further complicates things for me.

This is what I did so far:

//prepare array
$sections;
$sectionsCounter = 0;

$node = node_load(8);
//Load sections field collection
$items = field_get_items('node', $node, 'field_section');
foreach ($items as $item) {

   $sectionItems;
   $sectionItemsCounter = 0;
   $fc = field_collection_field_get_entity($item);
   $sectionTitle = $fc->field_section_title["und"][0]["value"];
   //push item into array now
   $sections[$sectionsCounter]["sectionTitle"] = $sectionTitle;
   $sectionsCounter++;

}

I have only managed to get the title of each section so far and push it into an array as an object with property title

UPDATE:

Well ,it seems I somehow got it to work, but I'm worried this is not the best solution. Can someone please have a look and tell me if I'm doing this the correct way?

//Load sections field collection
  $sections;
  $sectionsCounter = 0;

  $node = node_load(8);
  $items = field_get_items('node', $node, 'field_section');
  foreach ($items as $item) {

     $sectionItems;
     $fc = field_collection_field_get_entity($item);
     $sectionTitle = $fc->field_section_title["und"][0]["value"];
     $sections[$sectionsCounter]["sectionTitle"] = $sectionTitle;
     $itemsField = $fc->field_menu_item["und"][0]["value"];

     $innerCounter = 0;
     for ($i=0; $i <sizeof($fc->field_menu_item["und"]); $i++) {

        $arr = $fc->field_menu_item["und"][$i]["value"];
        $innerArray = entity_load('field_collection_item', array($arr));
          foreach ($innerArray as $item) {
            $sections[$sectionsCounter]["sectionItem"+$i] = $item;
          }
        $innerCounter++;
     }

     $sectionsCounter++;
  }

I've managed to create 2 objects that each contain:

A section title
An object that holds all the fields that the 'inner' field collection of the section contains

You could make use of

entity_load('field_collection_item', array($item_id))

This how-do-i-load-a-field-collection-from-a-node post provides multiple solutions for your problem!!


How to override jquery update preprocess page The objective is to exclude certain javascript files from some sections of the website.

I exclude javascript and css files in this way in the template.php file of the theme:

function phptemplate_preprocess_page(&$vars) {
  $scripts = drupal_add_js();
  //PRINT THIS ARRAY AND UNSET THE UNWANTED ARRAY
  // unset($scripts['module']['sites/default/files/js/jquery-min.js']);
  unset($scripts['module']['YOUR_PATH_TO_JS']);
  $vars['scripts'] = drupal_get_js('header', $scripts);
}

However it seems that jquery_update preprocess is executed after template.php, so it overrides my changes:

function jquery_update_preprocess_page(&$variables) {
      ...
      $variables['scripts'] = drupal_get_js('header', $scripts);
}

The code is located in jquery_update.module

How would be the best approach to resolve this?

I would prefer not to hack or disable the jquery_update.module code if possible.

Any alternative ways to exclude javascript files that doesn't involve touching the template.php file would also fix my problem I think.

JSAlter module for D6 should solve your problem..

Project page says

  This module will not be ported to Drupal 7, because Drupal 7 core
  natively includes a hook_js_alter(). Note that the signature and when
  the hook is invoked is slightly different in Drupal 7 core than it is
  in this module.

  This module adds a hook_js_alter() hook that other modules can use to
  modify the javascript that gets output to the page. The module
  provides no end-user functionality, but other modules can use this
  module as a dependency. Check out the JS Registry, JS Debug Helper,
  and jQuery Form Update modules for examples.


How do I install the kurti devi 10 font for CKEditor? I want to use the kurti devi 10 font in my new project. How do I install it for CKEditor?

Check out @font-your-face module. It lets you to add fonts with UI, and it even have some kind of wysiwyg integration.


Using attach_library in a modal For ref, I'm working on https://www.drupal.org/project/focal_point/issues/3162218
I have a twig file that handles the contents of a modal window and I want to load a particular CSS file whenever this twig file is loaded. I've added the following to the top of the .twig:
{{ attach_library('focal_point/drupal.focal_point_preview') }}
...and in my libraries.yml I have:
drupal.focal_point_preview:
  version: VERSION
  js:
      js/focal_point_preview.js: {}
  css:
    theme:
      css/focal_point_preview.css: {}

If I put the attach_library() call in another (inappropriate) template the js/css is present on the page before the modal is loaded and therefore it works properly, but this is not the correct place for these libraries to be added since they are only needed when the modal is opened.
At some point in the past this worked but as of now it definitely doesn't. Thoughts?

render() only works because of EarlyRenderingControllerWrapperSubscriber, which should have been removed by now:
 * In other words: this just exists to ease the transition to Drupal 8: it
 * allows controllers that return render arrays (the majority) and
 * \Drupal\Core\Ajax\AjaxResponse\AjaxResponse objects (a sizable minority that
 * often involve a fair amount of rendering) to still do early rendering. But
 * controllers that return any other kind of response are already expected to
 * do the right thing, so if early rendering is detected in such a case, an
 * exception is thrown.
 *
 * @see \Drupal\Core\Render\RendererInterface
 * @see \Drupal\Core\Render\Renderer
 *
 * @todo Remove in Drupal 9.0.0, by disallowing early rendering.

So don't use any render method. Ajax renders HTML content automatically and so makes sure to catch all metadata which bubbles up.
BTW in a module handling AJAX responses you don't need to bubble up attachments through Twig:
{{ attach_library('focal_point/drupal.focal_point_preview') }}

You can add them directly to the Ajax response:
$response->addAttachments(['library' => ['focal_point/drupal.focal_point_preview']]);


User's field autocomplete/autosuggest widget I have a user field where multiple users can be added. Currently, I am using the auto-complete widget.

Is there a module that allows you to customize what can be additionally shown on autocomplete? I would imagine that you could add an 'autocomplete' view similar to full-page or teaser.
Something like Facebook's search. Providing more info like picture or residence of the user.

In your field setting, you can choose a view for node or user references:

To create this kind of view-reference, you have to previously create a view with a reference page like this :

Note that every field you'll choose for the view, will appear in the autocomplete input

Hope this can help


How to load webform results using EntityFieldQuery I have a webform and I need to read its results/submissions using EntityFieldQuery.

I need to load all the results of a specific webform having a field value. ( load all the submissions of webform node where age = 25 )

Can EntityFieldQuery do that ?

Thanks in advance.

Webform results aren't entities, so you can't use an EntityFieldQuery.

You'll need standard db queries to get that data.


Attach js file to every page w/term reference widget in Drupal 8 I have begun trying to port a small, simple module that I maintain to Drupal 8.

It was originally written (not by me) in Drupal 6 and used hook_init() in combination with drupal_add_js() to attach its scripts to every page.

Both hook_init() and drupal_add_js() have been deprecated in Drupal 8. I only really need to attach scripts to pages that have a taxonomy term reference widget (and in fact much of my logic has already been moved into a hook_field_widget_taxonomy_autocomplete_form_alter().) Scripts are now added via #attached which I understand, but since I don't have the $form array or object in hook_field_widget_taxonomy_autocomplete_form_alter() I'm not sure where to add the #attached element.

I'm also not clear if #attached is used instead of or in addition to a *.libraries.yml file. Does every single module with its own script.js need to declare a *.libraries.yml file?

How do I attach my custom js file to every page with a taxonomy term reference widget in Drupal 8?

'#attached' works for any element. You should have an element in scope in that alter hook. Also you should have a mymodule.libraries.yml to declare your script.


Send mail once content approval of custom content types I am creating one Like job posting custom content type.The permission for only posting the job for recruiter.After Post the job I need the approval for publishing permission from admin. My thought when recruiter post the job i want to send the mail like recruiter post the new job for admin and once admin approved the content. How can i do this

It's kind of hard to understand what you want but I think you should use the "Rules" module, which allows you to "to define conditionally executed actions based on occurring events":
https://drupal.org/project/rules


How to show a custom form in a block? I have a custom form which currently shows on a page. The form is submitted via ajax and the view embedded is also updated via ajax. I do not want to show the form on a page. Instead I want to show it in a block. I should be able to put the block anywhere on the website.

This is my form

/**
 * Provide a form.
 */
function MYMODULE_form($form, &$form_state) {

  $form['wrapper'] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'mywrapper',
    ],
  ];

  $form['wrapper']['node_form'] = [
    '#type'  => 'fieldset',
    '#title' => t('Add article'),
  ];

  $form['wrapper']['node_form']['node_title'] = [
    '#type'     => 'textfield',
    '#title'    => t('Article title'),
    '#required' => TRUE,
  ];

  $form['wrapper']['submit'] = [
    '#type'   => 'submit',
    '#value'  => t('Save'),
    '#submit' => ['MYMODULE_form_submit'],
    '#ajax'   => [
      'callback' => 'MYMODULE_MYCALLBACK',
      'wrapper'  => 'mywrapper',
    ],
  ];

  $form['wrapper']['view_display'] = [
    // view machine name && display/block name
    '#markup' => views_embed_view('nodes', 'block'),
  ];

  return $form;
}

/**
 * Do some validation.
 */
function MYMODULE_form_validate($form, &$form_state) {
  // Better do some validation.
  // Here or via #element_validate.
  // @see https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#element_validate
}

/**
 * Form submit. Node creation.
 */
function MYMODULE_form_submit($form, &$form_state) {

  global $user;
  $node = new stdClass();

  $node->type     = 'article';
  $node->title    = $form_state['values']['node_title'];
  $node->language = LANGUAGE_NONE;
  $node->uid      = $user->uid;

  node_object_prepare($node);
  node_save($node);

  // Empty out title field on rebuild.
  $form_state['input']['node_title'] = '';

  // Rebuild form.
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback to return the whole wrapper.
 */
function MYMODULE_MYCALLBACK($form, &$form_state) {

  return $form['wrapper'];
}

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['example/form'] = [
    'title'            => 'Example Form',
    'description'      => 'A form to mess around with.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['MYMODULE_form'],
    'access arguments' => ['create article content'],
  ];

  return $items;
}

Create a block with hook_block_info and embed your custom form within a block using hook_block_view. Assuming module's name to be example, this module creates a "My block" with the form.

FYI, in the below code drupal_render(drupal_get_form('MYMODULE_form')); is the one rendering your form in the block where MYMODULE_form is the form ID.

 <?php
    /**
     * Implements hook_block_info().
     */
    function example_block_info() {
      $blocks = array();

      $blocks['MYBLOCK'] = array(
        'info' => t('My block'),
        'cache' => DRUPAL_NO_CACHE,
      );
      return $blocks;
    }

    /**
     * Implements hook_block_view().
     */
    function example_block_view($delta = '') {
      $block = array();

      switch ($delta) {
        case 'MYBLOCK':
          $block['subject'] = t('My block title');
          $block['content'] = drupal_render(drupal_get_form('MYMODULE_form'));
      }
      return $block;
    }


Print the query results inside the submit function I have a query wherein it fetches data from the database, a simple SELECT query which is processed when a certain submit button is clicked. What I want to achieve is to get the results of that query so that I can populate it on my form. So far my code looks like this,

function my_module_my_form_submit_go($form, &$form_state){
    $values_array = array(
        'week'            => $form_state['values']['week'],
        'employee_name'   => $form_state['values']['emp_name'],
    );

    $result = db_query("SELECT * FROM {time} WHERE week='".$values_array['week']."' AND employee_name='".$values_array['employee_name']."' ");
}

and my form looks like this,

// this is where I want to populate the data which came from the database
$form['week'] = array(
    '#type'     => 'textfield',
    '#title'    => 'Week',
    '#value'    => $result['week'],
);

$form['emp_name'] = array(
    '#type'     => 'textfield',
    '#title'    => 'Name',
    '#value'    => $result['employee_name'],
);

$form['go_btn'] = array(
    '#type'           => 'submit',
    '#title'          => t('Go'),
    '#value'          => 'Go',
    '#id'             => 'go_btn',
    '#submit'         => array('my_module_my_form_submit_go'),
);

I am pretty sure that the query has results because I ran it on the database. What I want is to echo/print the results in the form because later on they will be also used in another form submission. How would I do such thing after the submit button is clicked. I have only managed to display a text using drupal_set_message but any data which came from the database, I can't display any. Please help. Thanks.

The issue is due to the form submission and rendering process within Drupal.  Long story short, Drupal submits the form then re-renders the form page, which goes through a 'submission' process.  So, all the drupal_set_message calls are getting cleared during this process.

What you want to use is an AJAX callback on the submit button, populating a section of the form with the data retrieved.  And lucky for you the process is much simpler in Drupal 7.

To use the data again in a later form, look at multistep forms.