Allow users to register using username in drupal commons throw Integrity constraint violation error I'm using drupal commons and I want to allow user to pick his username on registration.

Currently drupal commons does not allow user to choose his own username but generates one automatically.

What I have done so far through hook_user_register_form_alter :

I changed the #type of name (username machine name) from hidden to textfield. This display the field.

$form['account']['name']['#type'] = 'textfield';

I removed the default value

$form['account']['name']['#value'] = NULL;

Now when I try to add a new user, I get the following error message:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name': INSERT INTO {users} (uid, name, pass, mail, signature, signature_format, created, status, timezone, language, picture, init, data, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13); Array ( [:db_insert_placeholder_0] => 824 [:db_insert_placeholder_1] => [:db_insert_placeholder_2] => $S$DgHF.OcL6K0hxQ0A4v.O67r4FUp4kpfeuywOrGHvb4zmoEzjpQrW [:db_insert_placeholder_3] => test@test.com [:db_insert_placeholder_4] => [:db_insert_placeholder_5] => filtered_html [:db_insert_placeholder_6] => 1463562222 [:db_insert_placeholder_7] => 1 [:db_insert_placeholder_8] => Europe/Brussels [:db_insert_placeholder_9] => en [:db_insert_placeholder_10] => 0 [:db_insert_placeholder_11] => test@test.com [:db_insert_placeholder_12] => a:2:{s:7:"contact";i:0;s:20:"l10n_client_disabled";b:0;} [:db_insert_placeholder_13] => 267c9864-8fe0-4cc5-81ef-22bd53befcf8 ) in drupal_write_record() (line 7333 of /home/me/websites/customprojects/mysite.local/docroot/includes/common.inc). Backtrace:
PDOStatement->execute(Array) database.inc:2171
DatabaseStatementBase->execute(Array, Array) database.inc:683
DatabaseConnection->query('INSERT INTO {users} (uid, name, pass, mail, signature, signature_format, created, status, timezone, language, picture, init, data, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13)', Array, Array) query.inc:36
InsertQuery_mysql->execute() common.inc:7333
drupal_write_record('users', Object) user.module:582
user_save(Object, Array) user.module:3912
user_register_submit(Array, Array) form.inc:1519
form_execute_handlers('submit', Array, Array) form.inc:903
drupal_process_form('user_register_form', Array, Array) form.inc:385
drupal_build_form('user_register_form', Array) form.inc:130
drupal_get_form('user_register_form')
call_user_func_array('drupal_get_form', Array) menu.inc:527
menu_execute_active_handler() index.php:21

I understand that it is a duplicate problem on the username field but checking in the database there is no username matches the one I have chosen.
So don't understand the error.

Also, I'm wondering if the fact of having username can have a side effect ?

I removed the default value

Sort of but not really - what you've actually done is set a static value of NULL for that field, which will be carried through to the submission regardless of any user input.

Your best bet to avoid these sort of problems would be to implement the field again from scratch:

$form['account']['name'] = array(
  '#type' => 'textfield',
  '#title' => t('Username'),
  // ...
);

Note that this won't remove any extra validation that Commons might add, so YMMV and there may be some additional steps to complete your feature.

Just for future reference, to set an initial value for an element that doesn't nuke user input, use #default_value in place of #value.


render form item of type text_format in twig file I have created a form element, basically I want text formats to change texts as accordingly.

$form['thankyou'] = [
        '#type' => 'text_format',
        '#title' => $this->t('Thank you'),
        '#format'=> 'full_html',
        '#default_value' => $config->get('thankyou'),
      ];

Now, I have created a function, where I'm getting this form element value.

$config = \Drupal::configFactory()->getEditable('myconfig');
 $thankyou_paid = $config->get('thankyou');

If I directly debug $thankyou_paid, I get all my data formatted. (in bold)

But If I render it through hook_theme,

return array(
      '#theme' => 'mytwig',
      '#type' => 'markup',
      '#thankyou' => $thankyou_paid,
      '#cache' => ['max-age' => 0,],
    );

It gives me <b>ugwdegfgiurgiuterug</b>. Means, data gets rendered without formatting.

How to get this text (ugwdegfgiurgiuterug) as ugwdegfgiurgiuterug.

It's unsafe to use the raw filter, better use the render element

  raw

  This filter should be avoided whenever possible, particularly if you're outputting data that could be user-entered. See this page
  for more information on auto-escape in Drupal 8.

processed_text:

return [
  '#theme' => 'mytwig',
  '#thankyou' => [
    '#type' => 'processed_text',
    '#text' => $thankyou_paid,
    '#format' => 'full_html',
  ],
];

To configure the text format visit /admin/config/content/formats and read the warnings

  Improper text format configuration is a security risk.

In this case it might be better to use Restricted HTML or Basic HTML.


Some HTML tags are not displaying in body(ckeditor) of content type I am trying to put HTML file content into a body part of a content type.

Procedure: When user uploads a zip file I will extract and replace <img src="path" with different path and put that replaced content into body of the content type. This will be done in hook_node_presave().

Code:

               if(trim($unzipped_filename) == 'index.html') {
                    $renamed_filename = $unzipped_path . '/testing.html';
                    //rename the index.html
                    $renaming_index = rename($unzipped_files[0],$renamed_filename);

                    //open file and get data
                    $htmldata = file_get_contents($renamed_filename);
                    //Match all img src tags from html file
                    preg_match_all('/<img\s.*?\bsrc="(.*?)".*?>/si', $htmldata, $matches);
                    $i = '';
                    $replacewith = array();
                    for ($i = 0; $i < count($matches[1]); $i++) {
                     //Store replacing strings in an array
                      $replacewith[] = base_path() . $unzipped_path . $matches[1][$i];
                    }
                    //Replace all img src tags from html file
                    $replacedhtml = str_replace($matches[1], $replacewith, $htmldata);

                    file_put_contents($unzipped_path . 'renamed.html', $replacedhtml);
                    $node->body['und'][0]['value'] = $replacedhtml;

                  }

In the above code $node->body['und'][0]['value'] = $replacedhtml; like this I am placing replaced content of HTMl into body part.

Problem: In database I can see all the Tags: etc. But in content its not displaying these tags. Because of this, its not taking JS and css files to load the content. Below html content is not displaying in body.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TEXT Example</title>
<link href="css/Academy-style.css" rel="stylesheet" type="text/css"/>

<script src="js/jquery.min.js"></script>
 <script src="js/css3-animate-it.js"></script>

So where I am going wrong please suggest.

Have a look at your configured input format settings. It is likely the input format or a specific filter are stripping HTML tags out.


How to add a line break between each components in Email template in Webforms I have the Webform 7.x-4.13 version module enabled.

I have a Webform node with more than 30 form components. In Email Settings, I have created a custom email template where I used the token: [submission:values].

Then I test the webform submitting a message. The problem is that [submission:values] print out the components values in a very plain way, no break line between the title and the value for each component. How can we add a line break between each components in an email.

I tried using "Send e-mail as HTML" option as well.

Can we do this using CSS/theme? If yes, Please tell me the procedure.

Thank you in advance.

You can add every form component individuell with a syntax like [submission:values:field_key:label]
[submission:values:field_key:nolabel]
Please check the Tokens in your email settings or the following link https://www.drupal.org/node/2490648

You can also modify the webform-submission.tpl.php file and adjust it for your email.


How to change the title of the button in the user profile form in Drupal 7? How do I change the name of the button in the user_profile_form in Drupal 7?
I alter the user profile using hook_form_alter().

function userform_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form' ) {
    // I define a submit button like:
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Continue'),
    );

    //Then I can change it with this code:
    // Change 'Continue' to 'Sign in'.
    $form['submit']['#value'] = t('Sign in');
  }
}

It works for all elements (buttons) I define myself, but it doesn't work for the default button in the user profile form.
This the rendered HTML for the "Save" button:

<input id="edit-submit" class="form-submit" type="submit" value="Save" name="op">


Git workflow from dev to live when central repo is in local network I use @dev - @stage - @live workflow, managed with drush rsync and drush aliases to update code, syncing db down from @live to @dev / @stage to have recent state.

Recently, I am trying to implement very simple git workflow into it, to secure revisioning of my code. I am not git power user, so I can bear only simple workflow for a good clean simple start (as a single dev I can be spared of situations where many devs are merging/resolving etc.)

There is my local machine (@dev), and staging machine (@stage) that are in my local environment (parties that need to review/QA changes have intranet access to staging machine);  @live machine is remote one, and code is drush rsynced to it.

Now, My Local @dev and @stage are not exposed to internet, (can push, but one cannot connect to them from outside)

I have choosen to create "central repo" on @stage machine. I followed strategy simmilar to this: http://toroid.org/ams/git-website-howto . There is bare repo and webroot. Then I cloned from that "central repo" to my @dev machine. When I commit and push to origin from @dev, there is post-receive hook that populates webroot of @stage server with new code state. It is then reviewed, QA-ed.

Now, I am thinking about strategies to propagate those changes on live. I was thinking to modifiy post-receive in such manner, that if "dev" branch is pushed from my local @dev to central repo, code is only propagated in webroot of @stage server. But if I push "master" branch, code would be propagated in webroot of @stage server, and drush rsync would be triggered to do syncing from @stage to @live. Remote @live site, in that case, does not need to have git installed.

I guess it could be done this way (I am testing this workflow already), but I am also considering would it be any gain if git repo would live on @live site too; and if answer is yes, how could I implement that safely (@live is already populated with stable state, but has no git(could have if needed)).

I cannot go to remote @live server and clone from central repo (that is on my @stage machine) because @stage is not exposed to internet (it could be in future, as new devs will probably join to work on project, and will need to clone from that, but for now, it needs to stay local). I am searching for way to push from central repo to @live on when master is updated. Maybe same post-receive that updates @stage after master is being pushed from @dev, can trigger pushing to @live (instad rsyncing to @live?). But how I could initialize repo on @live, bearing in mind central repo is not accessible over net ?

As a side question, is git friendly when I decide to change the whole proccess (for example, move my "central repo" on BitBucket or anoter remote site, more devs join in...?

I also noticed that git cloning does not keep any of interesting user:group privileges, and pushing code could propagate that "lost" file permissions, is this of some concern (I am not version controlling files and such, that is in .gitignore) ? Yet agian I could always run some commands to regain those privileges as in http://drupal.org/node/244924 but I am not sure if this is best practice.

I hope that some of this make sense and that someone with good nerves could give me advice or two. I know this is somewhat simmilar with (dis)advantages of staging dev->production using 'drush rsync' vs 'git'? but it differs in some details very important to me.

Your question is a bit long, and too subjective. There are many ways to do things, and the answers to your questions are subjective. For better answers, post shorter questions that ask about a single factual item. It's hard to answer "what is the best workflow"-style questions on StackExchange; those are better handled on a discussion board.

Trying to pick out your specific questions: it is not necessary to use git to push to live, especially if you always keep a copy of the deployed code on your staging server.  It might be helpful to record the hash tag that you pushed to live somewhere when your script runs.  The main advantage to using git on the live site is that you don't need to do this, as you can use 'git log' to find out what is there.  If you do use git on the live site, be sure that the .git files are not accessible to the webserver.  I prefer to use this setup:

/path/www/mysite.com/.git
/path/www/mysite.com/htdocs/sites/all/default/settings.php

Regarding permissions, see also http://drupal.org/node/990812.  Hopefully I'll have this fixed up and committed soon. It has been languishing for a while; it works, but needs some cleanup in the flags, et.al.


How can I include radiobuttons to a view's results? I want to include two radio buttons to EVERY view's results, so a user can select one of them. This is actually a view with users results. Next to each result the following radio buttons will appear: "Active", "Suspend this member" and "Delete this member". How can I make these radio buttons appear on each view result?
Thanks

Is it very important to you to have radio buttons exactly like you describe? If not, I can recommend the Views Bulk Operations (VBO) module. VBO is a popular module which allows you to select views rows and perform a certain action on those rows. Each row gets a checkbox and you select the action to be performed with those rows using a select box. Here is a screenshot to illustrate that:

I think VBO is by far the most mature option available to solve your problem. If you insist on having the radio buttons in your view and you don't mind writing code yourself, have a look at Views Form Field (interesting, but no releases yet), or Create the "View as form" style (work-in-progress in the Views issue queue).


Crypt::hmacBase64() versus CsrfTokenGenerator::get() and CsrfTokenGenerator::validate() In a module I am writing, I need to add a hidden field in the registration form, similarly to what the Honeypot module does.

$form['honeypot_time'] = [
  '#type' => 'hidden',
  '#title' => t('Timestamp'),
  '#default_value' => mymodule_get_signed_timestamp(time()),
  '#element_validate' => ['mymodule_signed_timestamp_validate'],
  '#cache' => [
    'max-age' => 0,
  ],
];

mymodule_get_signed_timestamp() concatenates the timestamp with a value used to avoid the timestamp is arbitrary changed. It could be computed in one of two ways:

Using Crypt::hmacBase64()
Using the csrf_token service, which by default provides CsrfTokenGenerator::get() and CsrfTokenGenerator::validate()

The choose is then between one of the following snippets.

use \Drupal\Component\Utility;

$token = Crypt::hmacBase64($value, \Drupal::service('private_key')->get());

use \Drupal\Core\Access;

$token = \Drupal::csrfToken()->get($value);

The difference is apparently just that the csrf_token service's methods use, as part of the key passed to Crypt::hmacBase64(), also the session's data and the hash salt set in the settings.php file.

Considering that, in most of the cases, I would be altering a form submitted from anonymous users who tries to register an account (but I cannot exclude I could be adding that form element to forms submitted from registered users), should I use the first method or the second one?

I made a quick test using the following code.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Site\Settings;
use Drupal\Core\Access\CsrfToken;
use Drupal\Component\Utility\Crypt;

$autoloader = require_once 'autoload.php';

/**
 * Global flag to identify update.php and authorize.php runs.
 *
 * Identifies update.php and authorize.php runs, avoiding unwanted operations
 * such as css/js preprocessing and translation, and solves some theming issues.
 * The flag is checked in other places in Drupal code (not just authorize.php).
 */
const MAINTENANCE_MODE = 'update';

try {
  $request = Request::createFromGlobals();
  $kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
  $kernel->prepareLegacyRequest($request);
}
catch (HttpExceptionInterface $e) {
  $response = new Response('', $e->getStatusCode());
  $response->prepare($request)->send();
  exit;
}

\Drupal::moduleHandler()->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()->load('system');
\Drupal::moduleHandler()->load('user');

drupal_maintenance_theme();

$csrf_token = \Drupal::csrfToken();

$content[] = [
  '#markup' => t('First method: %token.
', ['%token' => Crypt::hmacBase64(123456, \Drupal::service('private_key')->get())]),
  '#cache' => ['max-age' => 0],
];
$content[] = [
  '#markup' => t('Second method: %token.
', ['%token' => $csrf_token->get(123456)]),
  '#cache' => ['max-age' => 0],
];

$renderer = \Drupal::service('bare_html_page_renderer');
$response = $renderer->renderBarePage($content, 'Test results', 'maintenance_page', array(
  '#show_messages' => FALSE,
));

$response->setStatusCode(400);
$response->send();

I then opened three different Firefox windows pointing them at the test script I wrote. This is what I got:

First window

  First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
  Second method: OndzLnnASZLsuzABJltD_HwK8dr48fEW_hdWG9Lu02I.

Second window

  First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
  Second method: J6oHkKdXeL9RUKHX4B1Sn418Yh8XD0tJbRrs459BI7A.

Third window

  First method: r3xavuZbwgsk1RJTPm-zOs3kUSeSY4-BDnj-UCwgyr0.
  Second method: TYvxZiF7xS6hD2nn8pfHu0GR9OPw0X8xT1HfVDNWkXc.

With the second method, different users are going to get different values, even in the case the input value is the same.
I would say that using the csrf_token service is preferable, in my case.


html entities privatemsg token I am using the privatemsg module to send messages and mails with questions about plants. The subject is automatically filled in with the token of a node title, which is always a plantname. They always have 2 single quotes in their names and that is turned into ' when it comes in the subject field of the private message.

What can I do about that?

You may implement this: hook_privatemsg_message_presave_alter in you custom module and change the message's subject as you like.

Here is a code sample:

/**
 * Implements hook_privatemsg_message_presave_alter().
 */
function your_module_privatemsg_message_presave_alter(&$message) {
  // dsm($message); print out the $message contents
  $message->subject = "$message->subject"; // use single or double quotes
}

Tip: strip quotes from a string


How to display a block view on demand triggered by clicking content of another view? A Link from a field value (view 1)  to another view (view 2) with contextual filtering works as well, if the second view is a page view.
But what about, if the second view should be a block view, only displaying after clicking on the link in view 1?

A link just takes you to a different page. Since blocks are associated to pages, you just need to link to a page to which the block is associated.

Linking to the same page that should then show the block is not possible, since blocks appear right when the page is shown. There isn't a way to delay the block appearing on pages.


Strange behavior of block display mode of views when the pager displays a specified number of items I've encountered a problem that I've never seen that before (not even in my searches on google). for the sake of simplicity I explain it in an abstract model.
I have 4 content types with a title; they are named ct1, ct2, ct3, and ct4. Every content type has 4 nodes.

I made a view_N view for ctN, whose display mode is block. I allocated a block on the page p, and view_N must display the last 4 titles of ctN. I used the following settings.

Use pager: Display a specified number of items | 4 item
Offset : 0

Only view_1 displayed 4 items; the other views were empty. I changed "4 items" to 8, and view_1 and view_2 displayed output.

Finally, I found two solutions:

view_2's offset must be set to 4, view_3's offset must be set to 8, and view_4's offset must be set to 12.
I must set the number of items to display to 16

This is very strange because views and blocks must be totally independent but from what I saw these results are totally depend on each other. I think it is going to be very difficult to handle such independence when there are many blocks and views on the page and each one may have different number of outputs (or all the items).

Is there any general solution for it?

If that makes any difference, I am using Drupal 7.

Try using unique pager IDs for each block display here:


How to limit a custom views filter to a certain display type? I'm creating a views filter, and I would like to limit it by display type.  How do I do that?

I'm creating a custom filter for the entity_browser view display (entity_browser/src/Plugin/views/display/EntityBrowser.php).

Since it's only relevant for this display, I would like it only appear in the list of filters when on that display.  How do I do that?

This works, you can use a form alter hook to check the display plugin, and then remove options from the AddHandler form.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function entity_browser_form_views_ui_add_handler_form_alter(&$form, FormStateInterface $form_state) {

  // Hide 'entity_browser_bundle' filter plugin for displays other than
  // entity_browser.
  $display_id = $form_state->get('display_id');
  $display_plugin = $form_state
    ->get('view')
    ->get('storage')
    ->get('display')[$display_id]['display_plugin'];

  if ($display_plugin != 'entity_browser') {
    foreach ($form['options']['name']['#options'] as $key => $value) {
      if (strpos($key, 'entity_browser_bundle') !== FALSE) {
        unset($form['options']['name']['#options'][$key]);
      }
    }
  }
}


Creating a form with GET bypases the validation and submit I am creating a simple form, when sumits, shows result from an external API.
But URL remain the same, so you cant get a url if your search result and send it to someone.

But when I use get

$form['method'] = 'get';

It shows a construted url..

mysite.com/search?cat=2$coutry=3

But it donot fetch the result, cause it is bypassing the submit and validation functions.
Any help?

Have the page or form check for the presence of your variables, using drupal_get_query_parameters(), and if present, perform validation checks and get results from the external API, and display.

For example,

$params = drupal_get_query_parameters();
if ( isset($params['cat']) ) {
  //validate $params['cat']
    if ( myValidationCheck($params['cat']) ) {
      $results = myExternalAPIGetResults($params['cat']);
      $form['results'] = myResultsDisplay($results);
    }
  }


theming nodes as forms - any advantage using drupal_render? I need to theme a node content type as a form. For example, the node has fields:

field_body = a question, e.g. "What is your favourite color?"
field_answers = field collection ------------------> these will become radio buttons
    field_content = an answer, e.g. "Blue"
    field_internal = internal value for the radio button
    field_points = how many points for this answer ---------> this will become an html attribute
    field_additional = "some additional info about this answer ---------> this will become an html attribute

and so on, each question has 3 answers to choose. This is a questionnaire, the editor adds questionnaires dynamically. I don't want Webform module in this case.

So far I've written a mymodule_theme() function (in a custom module) for the whole node with answers, and themed it as a form using raw html output, something like this:

$output = '<form>';
... loop
$output .= '<input type="radio" name="myquestion" value="' . $field_internal_value . '"> . $field_content_value .'<br>'
...

But Drupal has form API. I could as well build a $form render array in mymodule_theme(), instead of raw html and then use:

$output = drupal_render($form)

The question:

in the above example, is there any real advantage of building a form array and rendering it using drupal_render, instead of building the output from raw html as shown? For example, advantage with using ajax later, or submitting, or validating "the Drupal way" etc. (I think not because form API applies only to static forms which are defined in a module, but I'm not sure).

Using the Form API instead of doing things in the theme layer (rendering the node as a form) will give you all the advantages that the Form API has to offer (e.g. custom validation, submit handlers, form alters, etc.)

I would do things differently by creating a menu item with drupal_get_form as the page callback and the node as the parameter.

/**
 * Implements hook_menu().
 */
function example_menu() {
  $items = array();

  $items['custom/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('example_custom_form', 1),
  );

  return $items;
}

/**
 * Form constructor that takes a node as a parameter and creates a form based
 * on its values.
 */
function example_custom_form($form, &$form_state, $node) {
  $form['#node'] = $node;

  // Start generating the form...

  return $form;
}

Although subjective, this feels a little less hacky and might be easier to maintain in the future.


Removing file from form breaks site I created a module that hooks into the admin menu and allows you to upload a specific file for the site to use.

It allows you to upload a file, and change a file, but as soon as you remove a file and click submit I get the error:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry '' for key 'uri': INSERT INTO {file_managed}
  (filesize, status, timestamp) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2); Array (
  [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => 1
  [:db_insert_placeholder_2] => 1412011464 ) in drupal_write_record()
  (line 7202 of /var/www/html/includes/common.inc).

I think Im missing a step when it comes to managing files in a form. Here is the relevant module code:

function read_more_news_admin_form($form, &$form_state) {

    $form = array();

    // File selection form element
    $form['csv_file'] = array(
        '#name' => 'file',
        '#type' => 'managed_file',
        '#title' => t('Choose a CSV File'),
        '#description' => t('Upload your Daily Nav CSV here'),
        '#upload_location' => 'public://',
        '#default_value' => variable_get('csv_fid', ''),
        '#upload_validators' => array(
            'file_validate_extensions'=> array('csv'),
        ),
    );

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

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

    // Saving the file, setting it to a permanent state, setting a FID variable
    $file = file_load($form_state['values']['csv_file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file->fid);

}

The value of $form_state['values']['csv_file'] is empty (0) when you remove the file. You need to do a sanity check on $file after file_load not only for that reason but also as a good coding practice.

function custom_admin_form_submit(&$form, &$form_state) {
  // Saving the file, setting it to a permanent state, setting a FID variable
  $file = file_load($form_state['values']['csv_file']);
  if ($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    variable_set('csv_fid', $file->fid);
  }
  else {
    variable_set('csv_fid', '');
  }
}


How can create a template for user login form? how can I create twig template for user login form page: /user/login
Is there any Twig Template naming suggestion for that?
thank's for any help.

Use page--user--login.html.twig for targeting user/login  page.

You can also enable Twig debugging to see naming suggestions for different page components.

  The markup of each Twig template is surrounded by HTML comments that
  contain theming information, such as template file name suggestions.


Role based exposed filter is not showing anonymous and authenticated roles there. Can anyone tell me any method to add that roles? I've created one drupal7 view which will filter all contents based on roles not current user role. For that I've created one relationship 'author' then in view filter criteria I've given exposed author roles. But by default Anonymous and Authenticated roles are not showing there. Do we have any method to add Anonymous and Authenticated role to that filter?

That's because they are not really real roles, more just a group of users.

What I mean by this is that the relationship between users and roles is stored in the table users_roles. There is one field for uid (the users ID), and one field for rid (the role ID).

So, the admin user has a uid of 1 and also has the administrator role with an rid of 3, so there is an entry in the users_roles table like: 1 | 3.

Any other roles created and assigned will also have rows inserted into this table.

However when the admin user logs into the site there is not a row inserted into users_roles table for the "authenticated user" role. And likewise when they log out a row is not inserted for the "anonymous user" role.

The actual query used by views would be something like this:

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, node.uid, ur.rid
FROM node node
LEFT JOIN users users_node ON node.uid = users_node.uid
INNER JOIN users_roles ur ON users_node.uid = ur.uid
WHERE node.`status` = '1' AND node.type IN  ('article') AND ur.rid = '3'
ORDER BY node_created DESC

Here it is joining onto the users_roles table, but we know that the roles "anonymous user" and "authenticated user" don't have entries in the users_role table so it won't work.

So whilst it is possible to add these 2 roles into the select, the query that runs won't ever return anything.


Confused about choosing between line items and product attributes I am making a website that will have image canvas size as the products. As you know the Canvas Sizes will change and also their price will also change. Let me tell you the actual steps.

The customer selects the Canvas Layout. These are the Products for me.
The customer selects the sizes for the selected canvas layouts.
The customer chooses the Wrap type for the Canvas.
The customer chooses the color of the wrap.
The customer chooses the Frame type of the Canvas.
The customer chooses the color of the Frame.
The customer adds the selected item to cart and go to checkout.

Please note that, once the customer starts customizing the product, the price of the product changes with each customization.

So my confusion is that, what will be the best suited practice to achieve this one. I am using Drupal Commerce. Should I go for the Product attributes or line items?
Is there any way I can achieve this one by custom Module to add line items dynamically? So then I can create the prices upon each customization. I am attaching one wireframe about my idea.

If you made it all attributes (fields) on the products, created a product with each possible variation and referenced them all in a single node, it would work with the commerce add to cart form out of the box.

Commerce would create a select list for each attribute, which might not be exactly what you want, but that should be possible to handle with some form alter.


Best way to go about my news menu item Drupal newb here.

I'm trying to rebuild an existing site into the drupal architecture.
For the sake of context, it is a site for a non-profit organisation that wants to make insights in a certain field of scientific research accessible to the general public.
Because the organisation is not large I would like to keep the current structure of the site. Now, my first problem is with creation of a menu item for news item. Clicking on that item is supposed to display news items. That's all I want for now.

What I've been trying to figure out reading pfds, surfing the web, watching videos about menu creation and taxonomy et.. for a little more than a DAY now, what is the best way plant this in Drupal (7.7 by the way)?

1.
 - Create content type called "news item"
 - Create a node using the basic page content type and give as title "News" enter "Latest    news" in the body field
 - Go to admin>structure > Menu and create a menu item and assign
   as path www.domain/news/news item
 - Each time a news item would be created, the author could then choose "News" as parent menu item.

This approach is obviously ignoring taxonomy. But how does one apply taxonomy to this anyway? As I understand, you can't create a vocabulary and then assign a menu item to that vocabulary name itself, simply because there doesn't seem to be a node that represents a vocabulary name. Correct me if I'm wrong(I kind of hope I'm wrong here).

Of course, You could create a vocabulary called "News" but and then one level below          "News" would have to be something like types of news as terms and then use those terms as nodes that I can assign menu items to. The problem is the types of news would be already too granular for the site that I want to rebuild with Drupal. I just want to have a content type newsitems to be children of of a menu item in my main menu called "news".

2. Just create a "content" taxonomy and have terms like News, and About, media, bios as terms (and thus menu items) and branch off from there.

This approach also seems besides the point of what taxonomy is trying to accomplish. The uberparent of any vocabulary is "content" for each and every site on the web anyway and doesn't describe anything at all, so what would be the use making a vocabulary out of it then? But then again, does it have to describe anything just as long is works and would it be a relatively decent "creative" solution?

Ok, I kind of found my way through it eventually. Still pretty amazing the amount of possibilities. Makes me dizzy.


Is making field.tpl.php print the URL of the node the displayed field is attached to possible? Currently I have this setup with Views but I would like to take views out of the picture to optimize the site and fix a couple of problems that occure as a result of using Views.

What I am trying to achieve is if my nodes have content in a Body of Text called excerpt that it will show a button that links to the node's url and append the text "/excerpt" at the end of the node's url which will then display a different page with the content of excerpt on it.

I'm using Drupal 7 and am modifying a Zen subtheme.

The solution is<?php print drupal_get_path_alias("node/".$element['#object']->nid); ?>

This will print the URL Alias of the node that the respective field is attached to.

I found that I could get the NID of the node the element was attached to by doing<?php print_r($element['#object']);?>to find all of the available options for<?php $element['#object']?>when I found I could get the NID from that field I then put it inside of<?php drupal_get_path_alias() ?>and have it return the desired text.

It took a day to find it but it works. Hopefully someone else can benefit from this as well.


Views data export remove tags from xml output I want to remove <no-name> tag generated by views data export on xml output
Any ideas please?

I have already tried to override template output for the field but no results :(

I have found the problem, i was overriding the template but with a the wrong code, i was using the alternative style template with these variables:

<?php print $header ?>
<?php print $body ?>
<?php print $footer ?>

Instead these should be used :

// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>

<?php
/**
 * @file views-view-table.tpl.php
 * Template to display a view as a table.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $rows: An array of row items. Each row is an array of content
 *   keyed by field ID.
 * - $header: an array of headers(labels) for fields.
 * - $themed_rows: a array of rows with themed fields.
 * @ingroup views_templates
 */
?>
<?php foreach ($themed_rows as $count => $row): ?>
  <<?php print $item_node; ?>>
<?php foreach ($row as $field => $content): ?>
    <<?php print $xml_tag[$field]; ?>><?php print $content; ?></<?php print $xml_tag[$field]; ?>>
<?php endforeach; ?>
  </<?php print $item_node; ?>>
<?php endforeach; ?>

</<?php print $root_node; ?>>

I'm posting so maybe it will be helpful for someone else.


add unpublished content to pane As the maintainers of panels are not really reacting, my questions here:

I am creating panel-nodes which should be filled with existing content.  I need to have a preview functionality, so the user can add the panel-node and the unpublished content, review it, and finally publish everything.

as admin (user/1) I can do so without any problems, but other authed user with the permission to add all content-types etc. cannot.
they can open the dialog add content to pane > exisiting node. they can choose the unpublished node in the autocomplete field.  but after submitting the form (Finish) they get the message "Invalid node". this happens only with the unpublished nodes.

Is that a bug or am I missing something?

update: http://drupal.org/node/1294792

I've never used panels, but it can be a permission problem. As far as I know, to view and publish unpublished content you need to have set the "administer nodes" permission. To let some roles manage certain unpublished content types without granting them more than they needed, once (in D6) I successfully used the view_unpublished and Publish content modules.

Hope it helps.


Example of entity-within-entity subform processing Suppose that, in Drupal 7, EntityA includes one or more instances of EntityB.

Is there an example of building the create/edit form for EntityA that includes one or more edit forms for EntityB, and that can ajax in a new create form for a new EntityB?

It's not really that hard. You would want to create form elements that use the #tree attribute, to make sure the data for instances of EntityB will be well structured.

In order to make add another functionality you need to:

Keep track of the count in the $form_state.

if (empty($form_state['count'])) {
  $form_state['count'] = 2;
}

Add a button somewhere to add another.

$form['entity_b']['add_another'] = array(
  '#type' => 'submit',
  '#value' => t('Add another'),
  '#limit_validation_errors' => array(),
  '#submit' => array('add_another_submit_handler'),
);

function add_another_submit_handler(&$form, &$form_state) {
  // Add one to our counter and rebuild the form
  $form_state['count'] += 1;
  $form_state['rebuild'] = TRUE;
}

The above will work with no JavaScript. If you want to Ajax-enable it, you need to do some work on the wrapper.

Add a CSS ID that is used from the Ajax callback.

$form['entity_b'] = array(
  '#tree' => TRUE,
  '#attributes' => array('id' => array('add-another')),
  // ...
);

Add the #ajax element.

 // ...
 '#ajax' =>  array(
  'callback' => 'add_another_ajax',
  'wrapper' => 'add-another',
  'effect' => 'fade',
 ),
 // ...

Add the Ajax callback function.

function add_another_ajax($form, &$form_state) {
  return $form['entity_b'];
}


How to display badges with username? How can i display the badges with username like stackexchange? I am using D6 and user badge and userpoints modules.

Two modules you can try both of which integrate with user badges but will need a little more customization to get it right. Try the user_picture_block module:

  Create just one block with the logged on user's picture, if he/she has one. In addition, User titles, points and badges are also displayed, if there are any.

Also, there is the author_pane module which also has built-in integration with user_badges:


Why am I forced to log in? I'm a long-time Drupal 7developer, and tried a Drupal 8 install yesterday for evaluation. I installed a bunch of contrib modules. All seems ok, but when I go to the home page, I'm presented with a login screen. I want anonymous users to be able to see the site, how can I allow this? I don't see any settings to force login, and am not using the shield module.

D8 default front page is a view page admin/structure/views/view/frontpage/edit/page_1. Views in 7 and 8/9 is quite similar from a end user perspective meaning you should feel right at home. D7 and 8 default front page is /node as you see and normal access permission.


Views returns 'All taxonomy terms' in alphabetically order; can I change to Parent > child I'm outputtin taxonomy terms using Views; The field i'm calling up is 'Content: All taxonomy terms' and returning all the vocabulary 'address' .  Views then puts these into alphabetical order ie.

England, London, Victoria

I'd like it to return from Parent downwards.  Anyone know how to do this ?

Many thanks,

I believe you're looking for something like the Hierarchical Term Formatter module:

  This module provides hierarchical term formatters for taxonomy reference fields. In other words, it can display a taxonomy term reference on, say, a node as Parent > Child, rather than just Child.


How to turn off Captcha for search? I've installed the Captcha module and I need to remove it from the search button and form (just an unnecessary nuisance there). Captcha configuration allows me to turn it off for specific values of a "Form_ID". I tried that with "search", but I guess the form ID is more complicated than that. What Form_ID(s) do I need to use to get Captcha to stop showing up in search?

Thank you.

For a block, the form_id should be:

  search_block_form

and for a page:

  search_form

To easily find this information, install the Devel module:

  A suite of modules containing fun for module developers and themers

and use something like this in your theme's template.php file:

function myTheme_form_alter(&$form, &$form_state, $form_id)
{
    dpm($form);

}

This will show a hierarchical display of all forms on the page - you can then scroll quickly through the info to find what you need. Very handy for searching arrays.


Module to do an action based on content type user sees I would like to achieve, for my custom module, this behavior:

It triggers only when user sees the node of some content type
It does a calculation based on field present in that content type
(it checks the values of taxonomy term assigned to that node)
It prepares a variable based on calculation (it might be a complex query)
article.tpl.php is injected with the content of that variable

Assuming you're using Drupal 7 you can do all of this in hook_node_view(), e.g.

function MYMODULE_node_view($node, $view_mode, $langcode) {
  // Check the node type and that the user is viewing a full node page
  if ($node->type == 'article' && $view_mode == 'full') {
    // Get some field values from the node
    $field_items = field_get_items('node', $node, 'field_name');

    // Get the first field value.
    $first_field_item = array_shift($field_items);

    // The index will depend on the type of field; for taxonomy term refs it's 'tid'
    $value = $first_field_item['tid'];

    // Perform some complex operation on the value.
    $new_value = MYMODULE_complex_op($value);

    // Add the new value to the node content, to be found in the $content array
    // in node--article.tpl.php
    $node->content['my_new_value'] = array(
      '#markup' => $new_value
    );
  }
}

In your template file you'll be able to call print render($content['my_new_value']); to output the variable to the page.

Obviously that'll need some adjusting for your own needs but hopefully it'll help.


Form not showing in administration menu in Drupal6 I'm trying to create a simple form with a textfield in the administration panel but I get the message "You do not have any administrative items"

Here is the code inside my ptm_autocomplete.module:

function ptm_autocomplete_menu() {
  $items['admin/prestum/autocomplete'] = array(
    'title' => 'Autocomplete',
    'description' => 'Autocomplete',
    'page_callback' => 'drupal_get_form',
    'page arguments' => array('ptm_autocomplete_form', array(), array()),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

function ptm_autocomplete_form(&$form_state, $unused, $form_values) {
  $form = array();

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Color'),
    '#description' => t('Color'),
  );

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

  return $form;
}

Any ideas what might be wrong?

You have an an underscore (_) in page_callback. Remove that, clear the caches, and you should be good to go.

function ptm_autocomplete_menu() {
  $items['admin/prestum/autocomplete'] = array(
    'title' => 'Autocomplete',
    'description' => 'Autocomplete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ptm_autocomplete_form', array(), array()),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

Also if this is Drupal 7 your form function should have $form as the first param:

function ptm_autocomplete_form($form, &$form_state, $unused, $form_values) { ...

But not for Drupal 6.


How can I repeat a group of fields in a content type? I'd like to create a content type named image gallery then add two fields as caption as text and image as image. Then make these two bundled and repeatable indefinitely when entering content for this content type.

Is it something possible to achieve without using third party modules or creating multiple content types?
If so, how?
If not, what would you suggest to use to do this?

I've tried to use Paragraph module and working fine but it seems it doesn't provide the image dimensions unless you loop the whole bit and get the dimensions for each item.

PS: Sorry about the tag by the way but it seems tags for content type and structure doesn't exist.

You should look into the new media entity suite of modules for Drupal 8. You can create media bundles and add fields to them (like title, caption, link, copyright). You can then create a simple Paragraph that holds a media reference field, and set it to unlimited - the theming is up to you to get the display to grid out like a gallery. I'm not sure why you need the image dimensions though. But with media entity, media renders out like normal entities meaning they gain access to display modes and various twig template possibilities.

https://www.drupal.org/project/media_entity
https://www.drupal.org/project/media_entity_image

Here is a walkthrough that covers in depth the technique I'm describing and how to set up a media based workflow:

https://www.annertech.com/blog/reusable-media-drupal-8-tutorial

Using Paragraphs is basically the only way to get 'bundled fields' without resorting to using Entity Construction Kit and entity reference fields - but by the time you engineer all that, you'll have spent three times as long and your field data won't live on the media object itself ( which is another drawback to Field Collection), and for that you will definitely want the Media Entity approach. Please don't make them multiple content types either. Media is media.


Javascript related problems when using old versions of IE and a proxy server I have a site that is fairly javascript heavy.

It uses the edit module with some custom javascript overrides, some other plugins like fancy scrollbars, flexslider, image cropping, etc. as well as a bunch of custom js that does alot of ajax loading of content.

The homepage is basically a solr+facetapi search page that returns a huge grid of images, which are effectively cropped & positioned with js after they load (using imagesLoaded to wait before processing).

In all modern browsers everything works fine.
In IE when not using a proxy, everything works fine.
In IE <= 10 strange things happen.

Normally what happens is the page starts loading and the images start appearing individually as they have loaded.

With IE + proxy the page starts loading and then seems to stop, while all the js & images are loading in the background, then after about 30 seconds (much, much longer than the page would take to fully load normally) all of the images appear at once.

Also, normally as images load in the are visibility: hidden, cropped & positioned and then are visibility: visible, but in this case not all of the images end up with visibility: visible, but the images have loaded in, you can see them with developer tools tweaking of css.

Enabling or disabling of js/css aggregation doesn't make a difference, nor does cache clearing.
After a little debugging I noticed that the imagesLoaded plugin was not firing at all until the end and then was firing for all images at once, instead of normally it firing as each image loads, but there didn't seem to be any reason for this.

Setting the proxy server to "cache deny all" seemed to help the problem but it wasn't as good as it is normally in non-IE browsers (IE11 seems fine too).

Has anyone seen behaviour like this before or does anyone have any ideas of things to investigate?

TL;DR:
I have a site where everything loads normally except for users running IE <= 10 and a proxy, in which case the page loads extremely slowly and javascript doesn't run as expected.

Has anyone seen anything similar or have any ideas on what it might be.

This was seemingly a server specific issue regarding a server I am not the maintainer of so I never got to the bottom of the exact cause (which is annoying because I like to know), however I eventually got around it by using the jQuery Lazy Load plugin to load the images.


Should modules be in source code management? I am new to Drupal and I am using Drupal 7.61.

Should the Drupal modules folder be git ignored or included in the source code management for best practices and continuous integration sake?

As Jaypan and leymannx say in the comments above, if you use Composer to manage dependencies, you can just include composer.json and composer.lock in your version control repository. Then you can use Composer to rebuild your project when you deploy. This has the advantage of keeping all third party code out of your repo.

https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

The documentation linked above shows how to use Composer to install Drupal core, contrib modules, and even patches and libraries.

This approach is the emerging standard. But it has its pros and cons. Here are some Drupal and Composer "gotchas" to look out for:

https://www.jeffgeerling.com/blog/2017/composer-and-drupal-are-still-strange-bedfellows

If you don't use Composer, it's probably a good idea to keep core, contrib, patches and libraries in version control.


How to make one node relate to another node? Ok, I'm going to toss out an example of what I'm trying to do with US states and counties, but I'm not looking for a module to handle them... It's just an example.

Assume I have two content types, the US State and US County content types.  So now I have some nodes of US State (alabama, alaska, etc) that have some fields, like maybe population size, square feet of territory, etc.  Now I have counties, so I've got some N counties that belong to alabama, some for alaska, etc., each as its own node.

How can I make a US County node know what US State node it belongs to?  How can I make US State nodes know what US County nodes belong to them?  For like querying in a view or whatever, basically the functionality of foreign keys in a SQL table.  This seems like it would be very simple and obvious to do, but I must be missing it.

Remember, this is just example data types, I'm not really working with US States and US Counties, so I don't want some specific module for them, just the idea of how to setup content types and the like to have foreign keys.

And if anyone knows, how efficient is this?  If I'm dealing with millions or maybe billions of nodes with some hierarchy of relations, how well can drupal query this stuff with joining linked data from multiple content types based on these "foreign keys"?  Is it 10x slower than mysql tables with foreign keys, faster than that?

edit: Using Drupal 7.  Maybe this will make things clearer: I've tried making a taxonomy vocabulary or whatever, but I don't see how to specify relations between nodes. I can say a US County is under US State, but how can I say "Baldwin County" is in "Alabama"? Where do I put that data in?

I'd look into Node References or Taxonomy depending on what version of drupal you are using and whether or not you are trying to create a hierarchy structure in your site.


Display single field from argument taxonomy term in Views header area I have a view with a taxonomy term ID in the URL which is used to filter the displayed entities in the view.

I want to display the description from the taxonomy term.

I've tried this a million different ways.

I've even gone as far as defining a view mode for the vocabulary which only includes the field - that doesn't work because it insists on displaying the title linked to the term page (which I definitely don't want). I even tried the layout builder but that displayed the title as well.

This is not the same as modifying the page title - which I am doing successfully.

Any ideas what I can do?

I've included my original response below but it turns out I'm an idiot: All you have to do is create the taxonomy-term as a relationship and then you can just pick out the field you want. D'oh!

~~~ my original answer

Yeah, so this is a problem that is currently unsolvable without code as of Drupal 8.6.0. Unless you deploy Display Suite, which is using a sledgehammer to crack a nut.

There's a lot of discussion on drupal.org about the lack of control on title fields in respect to nodes but the issue goes deeper. It applies to Taxonomy as well: You cannot stop the title field from appearing in any view mode because that's the way the template works.

The only solution is to create a new template that doesn't display the title (in my case taxonomy-term--book-series.twig.html) plus the supporting hook_theme() and hook_preprocess_taxonomy_term__book_series() all of which is a PITA.

Even then it's not great because there are no (default) theme suggestions for taxonomy terms that include view modes. It would have been much nicer if I could have designed a view mode called "description" and then had a theme suggestion of taxonomy-term--description.twig.html because that would then work in all cases. Instead I have to create the same template and support code but for a different vocabulary.

All-in-all, not the best experience.


What Plugin goes "type" of a FieldStorageConfig type? I have a module creating a field type. It works.  I can create and add the field through the admin UI.  However, I am trying to update a content type with hook_update_N and change a field from entity reference to my field type. I am creating the FieldConfig and FieldStorageConfig like this

$field_storage = FieldStorageConfig::create([
       'field_name' => 'content_category',
       'entity_type' => 'node',
       'type' => 'my_field_type',
    ]);

$field = FieldConfig::create([
      'field_storage' => $field_storage,
      'field_name' => 'content_category',
      'bundle' => 'story',
      'label' => $label,
      'settings' => array('display_summary' => TRUE),
      'entity_type' => 'node',
    ]);
    $field->save();

This results in an error that says

The "my_field_type" plugin does not exist

but i can  create a field of type "my_field_type" and when I export configurations for my field created through the UI  the type says "my_field_type"

So What plugin is it looking for in the "type" field of a fieldConfigStorage?  In my Plugin folder of my module the Formatter.php  Field.php and Widget.php  which of these is the correct one?

My Bug was actually in

entitity_get_form_display()->setComponent('field', array(
type=>my_field_type))

it should have been

entitity_get_form_display()->setComponent('field', array(
type=>my_field_type_widget))


Menu block goes crazy after 4th level When I click on a 4th level link of a Menu block, the 3rd level disappear.
This is the menu:

Services

Accommodation

Building A

Apartment 1

Apartment 2

I have 3 blocks to show this menu:

1st level block (Starting level 1st, max depth 1): is ok
2nd level block (Starting level 2nd, max depth 1): is ok
3rd level+ block (Starting level 3rd, max depth 9): it's not ok

When I click on a third level link (Building A) the 3rd block shows:

Accommodation

Building A

Apartment 1

Apartment 2

but when I click on any 4th level links (i.e. Apartment 1), the 2nd level link disappears and it shows:

Building A

Apartment 1

Apartment 2

I need to see the third level links even if I click on the 4th+ levels. What I need is this:

Accommodation

Building A

Apartment 1

Apartment 2

Thank you.

Solved.
In the menu block configuration, Advanced Options, I checked Make the starting level follow the active menu item.


How to create dynamic contents with view I have to create some different pages in Drupal 7.
I need a different header and a custom text for the pages appearing in the same block, so I thought that it would be useful to create a view.
I did not develop that website, is it  the right way to do that?

I will explain it better.
I have to do 4 landing pages with the same structure.
I created a webform block for the right block. It will be the same on the four pages. Now I want to create two more blocks, one for the header and the other one for the text. I'd like to change the block content in the different pages.
How can I do it?

There are multiple ways to implement this. Either by creating a new content type landing pages and set a specific template file only for this content type (I think this is the most strait forward option), or you can create a view with multiple pages (if you want to work with views) and again create a specific template for the view. Also I think that you could use the panels module and create your landing page with custom layout.


How to use rendered file entity in view header as background image for view I would like to set a background image on a div in my views-view.tpl.php using the image from a rendered entity field in the View Header.

Something like:

      <?php print render($title_prefix); ?>
      <?php if ($title): ?>

<?php print t($title)?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

      <?php if ($header): ?>
        <?php print $header; ?>
      <?php endif; ?>

How do I print just the url of the entity from the header? It would be great if I could pull the image URL and add an inline style on the group-header div. Any ideas on how to accomplish this?

Similar to this question: Use image from view as background image of div in page.tpl.php

Is there something the Background Images Formatter module can do for you?

The module allows you to set a background to any CSS selector(s) you can think of. Combine it with a selector built with NID-token (NID field in Views, excluded from display, and its token used in the selector you assign the background-image to), and it will probably save you some templating headaches.


How to migrate from test environment to production environment? The migration is from the local environment to the production environment. The production environment has run some time and created a lot of articles.

In order to add new things to my site, I added a custom theme and installed CCK, Views and other modules in my local test environment. Now that the local test environment is finished, how do I migrate it to the production environment, without destroying the content of its database?

This is a non-trivial problem that almost everyone has a different answer for: there isn't a canonical Drupal way to handle staging to production pushes. Dries Buytaert, the guy who runs the Drupal show, made it one of the key initiatives of Drupal 8. Of course, Drupal 7 was just released, so it'll be a while before that bears any fruit.

The problem can be broken out into two separate issues:

Staging configuration (variables, content types, fields, views, etc.)
Staging content (nodes, users, etc.)

The former can be mostly handled by the Features module, which will take your site configuration and turn it into a module you can add to your Drupal installation: this way, you can add it to your version control system and not having to worry about it being blown away when you migrate your content.

The latter is really tricky, because on an active site, it's likely the content will change on production even after you've made the initial sync to your development environment. This prevents wholesale replacement of content during staging like you can do with configuration.

Additionally, Drupal doesn't use universally unique identifiers (UUIDs) for content: every time a node or a user is added, the ID increases by one. So what might be node 45 on your development site might be node 90 on your production site.

Unfortunately, I don't have a great solution for this: staging content is a real weakness of Drupal. What I personally do is add content on the production site only. If a client wants to see how the content looks prior to it going live, I'll set up a clone of the production site that's only accessible to the client. Then, once approved, the same changes are then made directly to production.

There's another alternative that gets tossed around: the Deploy module. It's supposed to leverage Services to make staging content relatively painless. But I can't vouch for its effectiveness and it doesn't have a Drupal 7 version.


Trouble updating Modules in Drupal 7 with FTP I'm developing in localhost. When I try to update modules, it requires FTP access. I've tried several ways by installing vsftpd and adding my user account to ftp group, chowing the files, etc. But, I'm ending up with following message:

File Transfer failed, reason: Unable to remove to file /media/location-of-drupal/module/blahblah

Now, I've decided not to use FTP. Can I just manually download latest copies and unzip > paste the modules? Will that work? And is it applicable to updating Drupal core?

Thanks :)

EDIT: I've managed to fix FTP, and is now updating modules by FTP. But still, I'd like to know the answer, i.e. does copy-paste works perfectly? I posted my answer here: http://bdhacker.wordpress.com/2011/11/26/update-drupal-modules-using-ftp-in-localhost/

I had the same effect.

The instructions at http://bdhacker.wordpress.com/2011/11/26/update-drupal-modules-using-ftp-in-localhost/ have all the necessary details. Especially the vsftp config (/etc/vsftpd.conf) is important. Make sure the following options are set:

listen=YES
local_enable=YES
write_enable=YES
local_umask=022

Don't forget to restart vsftpd after config changes.


Create dummy instances of custom entity with dummy field data? My module defines a custom entity type and bundle and adds fields to the bundle programatically. Now, I need to create a bunch of dummy data to test the interface. I'm working with various combinations of entity_get_controller()->create(), entity_metadata_wrapper()->save(), field_attach_submit(), etc. and I have been able to fill the entity base table with new rows. The problem is that the generated entities aren't loaded with:

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'my_entity_type');

I'm not surprised that the query doesn't return my new entities because I haven't found a place to specify bundle for the dummy entities and I haven't figured out how to generate default or random field data. How do I specify the bundle for my new entities and how can I generate valid random field data for date, taxonomy_term_reference and integer fields?

My created entities were not listed by the EntityFieldQuery above because of this issue: Make EntityFieldQuery::fieldOrderBy include NULL field values

My new entities did not include a date field that was used to sort the table. So, the table didn't include the null-field entries.

I didn't figure out how to specify the bundle for my new entities but there is only one bundle defined, so it is the default. I'm still interested in a function that would be able to create random field data valid for each type of field. Heading over to look at Devel module for that function.


How to get term name using PHP code in views? Drupal 6! how can i get term name of current term using PHP code? I am using it in views. Thank you.

I dont know why, but the below code doesant work:

$term = taxonomy_get_term($tid);
$name = $term->name;

If you want to get the term name of current node in views you can make use of Content: All taxonomy terms field. There is no need for diving into PHP code.


Controlling blocks displayed in domain access for each sub-domain I'm a noob in Drupal and have been exploring the Domain Access module ( http://drupal.org/project/domain ) in my local environment and till now has been doing pretty well. But when it comes to configuring block content i'm a bit baffled.
Problem goes like this:
domain is localhost.com
Sub domains are:

one.localhost.com
two.localhost.com
three.localhost.com

When i enable a block in one of the sub-domains two.localhost, say enabling Search in Right Sidebar and saving the changes they are applied not only to two.localhost but to all the others too.

Note that I'm working in drupal 6.22 with Garland theme in all the sub domains.
Is there anything I'm missing from the functionalities provided by the module like Domain Theme? or does it have to be coded by me to make blocks also in domain specific manner...any suggestions/helps would be much appreciated.

Thanks and cheers!

You've a module that gonna help you. Domain Blocks. And here you've many other that add some features to Domain Access module.


FieldCondition in an EntityQuery for media is causing a website error This entityQuery in a theme preprocess function in Drupal 8 is working great:

$query = \Drupal::entityQuery('media')
    ->condition('status', 1)
$result = $query->execute();

But as soon as I add this fieldCondition for a boolean field, I get a website error:

$query = \Drupal::entityQuery('media')
    ->condition('status', 1)
    ->fieldCondition('field_flagged', 'value', '1', '=');
$result = $query->execute();

What is wrong in the above code?

There's no fieldCondition method, condition works for all fields:

$query = \Drupal::entityQuery('media')
  ->condition('status', 1)
  ->condition('field_flagged', 1);
$result = $query->execute();


Why is hook_form_alter() not setting default values in _after_build function on /node/add/myct? I've got a validation form (id="mymodule-myct-verify-form") that retrieves data from temp_node to populate it's hidden fields. On submit, the form sends its data to /node/add/myct. (currently via $form['#method' = 'get';, which I'm planning on changing to 'post') What I want to do is this: in mymodule_hook_form_alter, get the data from $_REQUEST (later $_POST) and use that to set the default values of my CCK fields. Currently, jQuery is the approach I'm going for, being unable to get mymodule_form_alter() and mymodule_after_build_convert() to work. Here's what I've got:

 function mymodule_form_alter(&$form, &$form_state, $form_id) {
     if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'].'' == "myct") {
        // if converting, set default values through an after_build function
        if (isset($_REQUEST['conv']) && (strip_tags($_REQUEST['conv']) == 'app') &&
            isset($_REQUEST['taid']) && (intval($_REQUEST['taid']) > 0)
            && ($form['type']['#value'] . '_node_form' == $form_id &&
            (strpos($form['#action'], '/node/add/myct') !== FALSE))
        ) { // on the /node/add/myct/?conv=app&taid=1 page, this is true
            $form['#after_build'][] = 'mymodule_after_build_convert';
        }
  }
}

function mymodule_after_build_convert ($form, &$form_state) {
    //TODO: Set default values for CCK fields
    /*dsm($form);
    dsm($form_state);
    dsm($_REQUEST);*/
    // set receiving date and time
    dsm($form['#field_info']['field_status_10']); // date popup
    $form['#field_info']['field_status_10']['widget']['default_value'] = time();     //date("j F, Y - H:i");
    dsm($form['#field_info']['field_status_10']);
    // set deal type (select list)
    $form['#field_info']['field_deal_type']['widget']['default_value'][0]['value'] = intval($_REQUEST['ta_type']);

    return $form;
}

Why is my date_popup field empty instead of containing today's date? Why does the select list not change?

After doing some research, it turns out that taking a JavaScript/jQuery approach is the wrong way to do this. Rather, the code should use hook_form_alter() to retrieve POSTed data ($form['#method'] = 'post';) and set the default values of the node form (including CCK fields) via a function specified with $form['#after_build'].

So, if you want to dig in here and start monkeying with the "real" properties, you need to come in after the point that the CCK form elements are processed. Luckily, the form API has a phase designed for exactly this purpose: #after_build.

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, $form_state, $form_id) {
  // Check for a particular content type's node form.
  if ($form_id == 'example_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'example_after_build';
  }
}

/**
 * Modifies CCK form elements on the example node form.
 */
function example_after_build($form, &$form_state) {
  // Your code here.
  return $form;
}


How to edit views twig template to process node information I have created a views slider block in which have the following fields; image, title, text, and position. What I would like to do is look at the value of the position element and then add an css class to the title and text field to either display on the left or right side of the image.

In Drupal 7 I could do this very easily, but I can't figure out for the life of me how to do this in Drupal 8. I am overriding the views-view-fields.html.twig file.

Normally in Drupal 7 I would get the node ID, load it and then check the position value. In Drupal 8 using views-view-fields.html.twig file all I get is the rendered value (which contains html markup that I don't want).

Trying the preprocess route for the views-view-fields template file, I have the same problem in that value is already marked-up and no way to get the node that it came from.

If anyone has any suggestions how to go about accomplishing this, that would be fantastic.

In Drupal 8 using views-view-fields.html.twig file:

{{ row._entity.field_example.value }}

Trying the preprocess route for the views-view-fields template file:

$node = $vars['row']->_entity;
$field_value = $node->field_example->value;


How to send variable to the javascript in Drupal? What is the easiest way to send a value from PHP to Javascript in Drupal form?

The standard way to do this in Drupal is with drupal_add_js(), using the "setting" type, e.g.:

drupal_add_js(array('variableName' => 'value'), 'setting');

That will make the variable available on the JS side at Drupal.settings.variableName.


How to add breadcrumb? How can I add breadcrumb to a page in my attendance module.

I have used the following hook, but it changed the breadcrumb for all pages in other modules also.

function attendance_init() {
// set the breadcrumb
$breadcrumb = array();
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l('People', 'group/node/'. arg(2) .'/people');
$breadcrumb[] = l('Attendance', 'group/node/'. arg(2) .'/people/attendance');
drupal_set_breadcrumb($breadcrumb);

}

Could you get what you want from the Custom Breadcrumbs module?

  Allows administrators to set up parametrized breadcrumb trails for any
  node type. This allows CCK-style node types to have "Home > User Blog
  >2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases.
  Breadcrumb visibility can be customized via a php snippet.


How to get list of sites with module enabled using drush? How can I find out, using drush, which sites from my Drupal multisite installation have a particular module/theme enabled?

The drush command for this is:

drush @sites pml --type=theme --status=enabled --yes | grep bootstrap

That's for the bootstrap theme, for a module it would be something like this

drush @sites pml --status=enabled --yes | grep pathauto


How to export drupal commerce products? I need to export products generated by Commerce module.
What can I do to accomplish this?

I would use views module with a plugin that fits your export format expectations such as views datasource or views_data_export for CSV, XML, etc


Crossdomain.xml on a multisite setup I can't figure out where I need to place the crossdomain.xml (to let Flash communicate).

If I place it on the root of my Drupal installation, the cross-domain-policy is not working because the symlink redirects the user-agent to the multisite folder.

If I place the crossdomain.xml in the multisite folder, it doesn't work either.

What should I try?

I would make up a module with a hook_menu in it with a path of "crossdomain.xml".  In the menu callback, figure out your domain and serve up the proper file with the proper MIME type.  Install the module in "sites/all" and enable for each site that needs it.

I also suspect you could handle it in .htaccess with something like

RewriteCond %{HTTP_HOST} ^www\.host1\.com [NC]
RewriteRule crossdomain.xml crossdomain.host1.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host2\.com [NC]
RewriteRule crossdomain.xml crossdomain.host2.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host3\.com [NC]
RewriteRule crossdomain.xml crossdomain.host3.xml [L]


Trying to fix errores with the admin_menu module I have a Drupal 8 installation that went bad after installing admin_menu module.
and now the website is down with this error.

  stderr: PHP Fatal error:  Call to undefined function user_access() in /var/www/clients/client1/web7/web/modules/admin_menu/admin_menu.module on line 149

I've tried to delete the admin_menu module with Drush, given website is completely out of order and it gives me this error.

  PHP Fatal error:  Call to undefined function variable_del() in /var/www/clients/client1/web7/web/modules/admin_menu/admin_menu.install on line 22
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Call to undefined function variable_del() in /var/www/clients/client1/web7/web/modules/admin_menu/admin_menu.install, line 22

So I've looked into admin_menu.install and I have commented out its code.

function admin_menu_uninstall() {
  // Delete variables.
/*  variable_del('admin_menu_components');
  variable_del('admin_menu_margin_top');
  variable_del('admin_menu_position_fixed');
  variable_del('admin_menu_tweak_modules');
  variable_del('admin_menu_tweak_tabs');
  variable_del('admin_menu_show_all');
  variable_del('admin_menu_display');
  variable_del('admin_menu_cache_server');
  variable_del('admin_menu_cache_client');
  // Unused variables still should be deleted.
  variable_del('admin_menu_devel_modules');
  variable_del('admin_menu_devel_modules_enabled');
  variable_del('admin_menu_devel_modules_skip');
*/
}

It appears it was also done in a patch here.

Since it worked, I put the module back on and tried to overcome the issue and deleted content of admin_menu_page_bottom() function at line 150 in admin_menu.module and this brought the website back online.

Is it okay to remove this function content? and why is this module still not functional? have anyone else managed to get this working on Drupal?
Is it okay to do this in Drupal 8 to unsintall admin_menu removal with above procedure and is there anything that I am missing?

Admin menu hasn't had any development effort for comfortably more than 2 years now. It doesn't have a Drupal 8 release to speak of; the chances of getting the module working without major surgery to the code are pretty slim.

If you can get the module successfully uninstalled by commenting out some code, then definitely do it (then probably delete the module folder so you don't accidentally enable it again).

The Admin Toolbar module is its successor. It integrates with the core toolbar, and has a sub-module which provides the tools menu that you'll be familiar with from Drupal 7 (with clear cache links etc).


Join user to custom table I have a custom table (myusersession) which contains the uid field that is a reference to user entities.

How can I add user entity fields (exactly 'name') to my view?

I tried many variations of join, in hook_views_data(), but none of them works.

  $data['myusersession']['table']['join'] = array(
    'users_field_data' => array(
      'field' => 'uid',
      'left_field' => 'uid',
    ),
  );

  $data['myusersession']['uid'] = array(
    'title' => t('UID'),
    'help' => t(''),
    'field' => array(
      'id' => 'numeric',
    ),
    'filter' => array(
      'id' => 'numeric',
    ),
    'argument' => array(
      'id' => 'numeric',
    ),
    'relationship' => array(
      'title' => t('User'),
      'help' => t(''),
      'base' => 'users',
      'base field' => 'uid',
      'id' => 'standard',
    ),
  );

I also tested variations of the table name, such as users_field_data, users, and user.

As I understand the following code should be work, but it doesn't in my case.

    'relationship' => array(
      'title' => $this->t('User'),
      'label' => $this->t('User'),
      'base' => 'users',
      'base field' => 'uid',
      'relationship field' => 'uid',
    ),

With ['table']['join'], the table appears as column on the view with User as base, but but if the view base is myusersession, User doesn't appear.

Found that there is additional step: you have to add/enable that relationship at View GUI->Advanced->Relationship


Add menu itens in Commerce Kickstart administrative toolbar I have worked with default Commerce Kickstart 2 toolbar menu, and I really liked. But now I installed a new module, Commerce Feeds, and I can not access it because there aren't menu entries in toolbar. Is there a way to add menu entries like the one I need in Commerce Kickstart 2 toolbar menu, or I have to back to Drupal 7 administrative toolbar?

You're able to modify the Commerce Kickstart 2 admin menu from this path: /admin/structure/menu/manage/management

It's a normal menu created during installation called "Management".


What is the "default revision"? I'm using the Workflow module in Drupal 8 and I saw this checkbox on the "add a state" screen (/admin/config/workflow/workflows/manage/help/add_state):

  Default revision When content reaches this state it should be made the default revision; this is implied for published states.

What exactly is meant here by "default revision"?  Why is it implied for published states?

So that means it will become the active revision shown to users. So if a revision is published its got to become the default revision as it will be shown as the page content for normal users

When you select "Archived" for a piece of content you'd want that to become the default revision too so that when users look at the page they'd see access denied. But you wouldn't have the published option ticked for "Archived"

And draft you wouldnt want to become the default revision because it's not supposed to be shown to users in that state


Profile2, url rewrite How do I create a path like this www.example.com/PROFILE_NAME/FULL_NAME

FULL_NAME is a Profile2 field.

With pathauto you cannot modify profile2 entity.

There's a "quick dirty workaround" to making profile2 entities work with tokens/pathauto properly if you're interested.

It doesn't work for bulk generation, but does for individual saves of an entity.

It seems there is an ongoing effort to get this solved (http://drupal.org/node/1330546), but nothing's been added in a couple of months. It might be worth checking the issue queue/recent release notes to see if you can find out where they are with this.


Get current path in hook_file_download I have implemented hook_file_download function in my module. When I call function current_path in the body of this hook, it returns path of the file, not path of current URL in browser. The similar result I got when I try method request_path or variable $_SERVER['REQUEST_URI'].

My hook_file_download is called after I am programatically displaying image with function

<?php
function some_page_callback() {
// $args = ...some args
$output = theme('image_style', $args);
return $output;
}
?>

How to get  path registered in hook_menu for "some_page_callback" in hook_file_download method?

That's the correct behaviour.

If current_path() wasn't the URL of the file, then the file must never have been requested, and that hook would never have fired.

When you request a private file the current URL must be the file's URL, by definition. It sounds like you're looking to track the page that originally contained a link to your file. That's going to be almost impossible to do reliably.


Why is my migrate source plugin (d7_file) not found for my migration? I'm trying to write a migration for files from an old D7 site to a new D8 site, roughly following the instructions at https://www.previousnext.com.au/blog/migrating-drupal-7-file-entities-drupal-8-media-entities.

I have a myproject_migration module which includes the migration in its install folder.

myproject_migration.info.yml:

name: MyProject Migration
description: Migrations for existing MyProject content.
package: myproject
type: module
core: '8.x'
dependencies:
  - file
  - migrate
  - migrate_plus
  - migrate_source_csv
  - migrate_tools

config/install/migrate_plus.migration.furniture_files.yml:

id: files
label: Files from the old D7 site.
migration_group: myproject
dependencies:
  enforced:
    module:
      - myproject_migration
      - file
source:
  plugin: d7_file
  scheme: public
  constants:
    source_base_path: /
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  #uid: uid
destination:
  plugin: 'entity:file'

I enable the module; run drush migrate-status and get:

exception 'Drupal\Component\Plugin\Exception\PluginNotFoundException'
...with message 'The "d7_file" plugin does not exist.'
...in /var/www/myproject/docroot/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52
Stack trace:
#0 /var/www/myproject/docroot/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryCachedTrait.php(25):
Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition(Array, 'd7_file', true)
#1 /var/www/myproject/docroot/core/modules/migrate/src/Plugin/MigratePluginManager.php(53):
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('d7_file')
#2 /var/www/myproject/docroot/core/modules/migrate/src/Plugin/Migration.php(335):
Drupal\migrate\Plugin\MigratePluginManager->createInstance('d7_file', Array, Object(Drupal\migrate\Plugin\Migration))
#3 /var/www/myproject/docroot/modules/contrib/migrate_tools/migrate_tools.drush.inc(471): Drupal\migrate\Plugin\Migration->getSourcePlugin()
...

I've been importing updates to this config with drush config-import --partial -y --source=modules/custom/myproject_migration/config/install/.

I can see the plugin in core\modules\file\src\Plugin\migrate\source\d7\File.php, with the id "d7_file". Running through the checklist at https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins - it implements MigrateSourceInterface; it's annotated with @MigrateSource; it's in in the namespace subdir Plugin\migrate\source under the "file" namespace. So it's definitely there, and everything looks right, it's just not found.

Make sure the migrate_drupal module is enabled. (I can't be sure that's the reason, but it's the first one I stumbled over when I reproduced this locally.)

The reason this isn't easy to see:

Migrate plugins have multiple providers (which must all be enabled to use the plugin), and the relevant plugin managers actually use their own discovery which automatically infers providers from the parent class namespace. So the d7_file plugin has the providers "file" and "migrate_drupal" as it is provided by the file module but extends a class from the migrate_drupal module.

In effect, migrate's multi-provider thing adds "invisible" dependencies which silently remove the plugin when the required modules aren't installed.


Getting the profile2 user fields? i am writing a simple multistep form using ctools on drupal 7. Everything seems to work but i have a one last problem before i finish the task. How can i access the custom user fields (or fieldset i am not sure about the terminology). I've tried to do that by using the function below but it doesn't works and the property is always empty;

function helper_get_default_value_from_profile($fieldset, $key){

  $uid      = helper_is_user_logged_in();
  $account  = user_load($uid);
  $profile  = profile2_load_by_user($account, "cv");

  if(!property_exists($profile, $fieldset))
    return 0;

  if(empty($profile->$fieldset))
    return 0;

  $fieldset_ref = $profile->$fieldset;
  $id           = $fieldset_ref["und"][0]["value"];
  $fieldset_data = field_collection_field_get_entity($id);

  if(!property_exists($fieldset_data, $key))
    return 0;

  if(empty($fieldset_data->$key))
    return 0;

  $user_prop = $fieldset_data->$key;
  return $user_prop["und"][0]["value"];
}

It seems like you want to retrieve the value of a single field from a field collection. And that the field collection you want to retrieve a field from is a field of a 'cv' profile2.

The returned value of profile2_load_by_user($account, "cv"); is a Profile entity object. When $fieldset is the (machine) name of a field collection field, then you can retrieve its value using $items = field_get_items('profile2', $profile, $fieldset) (see field_get_items()). This will return an array of field collection values (or FALSE if there is no value for the field). The values are arrays containing a value entry which is the entity id of a field collection entity. You can load the field collection entity for an ID using field_collection_field_get_entity(). Finally, using $key as field name, you can retrieve the values of one of this field collection entity's fields using field_get_items() again.

$items = field_get_items('profile2', $profile, $fieldset);
if ($items) {
  $item = reset($items);
  if (!empty($item['value'])) {
    $field_collection = field_collection_field_get_entity($item);
    if ($field_collection) {
      $items = field_get_items('field_collection', $field_collection, $key);
      if ($items) {
        $item = reset($items);
        return !empty($item['value']) ? $item['value'] : 0;
      }
    }
  }
}
return 0;


Term reference with filter I wonder if it is possible to add a term reference field with just a subset of the available taxonomy terms. Let me explain. I have a taxonomy vocabulary with a structure like this:

- term 1
  - term 1.1
  - term 1.2
  - term 1.3
- term 2
  - term 2.1
  - term 2.2

Then I will create a specific content type and for that content type I will add a term reference field. Instead of referencing the whole vocabulary, I need to add only the options for, say, branch 2. I need to show options term 2.1 and term 2.2. In Drupal 6, the Node Reference field allows me to pull the options from a View. But this is a term reference field (it pulls the options from a given vocabulary) in Drupal 7.

I just want to avoid creating several different vocabularies, one for each content type, since their subject is more or less the same. In the future, I could take advantage of the fact that I have shared this resource instead of having a series of scattered vocabulary sets.

I think you want the References module. At the moment it dosn't have the views limitation on valid values committed but there is an issue with a working patch which should allow you to do what you want.


What is a "link template" in a token? When configuring a webform submission URL by using tokens, I noticed this entry that specifies a link template:

[webform_submission:url:?]

  The URL of the webform submission. Replace the '?' with the link
  template. Defaults to 'canonical' which displays the submission's
  data.

What is a link template? Can I customize or define my own? How would I know what other tokens can be used in place of 'canonical'?

Link templates are defined in the entity class. For webform_submission:

 *   links = {
 *     "canonical" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}",
 *     "access-denied" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/access-denied",
 *     "table" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/table",
 *     "text" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/text",
 *     "yaml" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/yaml",
 *     "edit-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/edit",
 *     "notes-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/notes",
 *     "resend-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/resend",
 *     "duplicate-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/duplicate",
 *     "delete-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/delete",
 *     "collection" = "/admin/structure/webform/submissions/manage/list"
 *   },

Source: https://git.drupalcode.org/project/webform/blob/8.x-5.x/src/Entity/WebformSubmission.php


Rate Module - Ability to "Rate" people Using the Rate Module , I'm interested to know if it is possible to "Rate" people.

For example, rate a tradesman; rate a private tutors teaching service; rate any service provider.

I'm already using the Rate module for node rating, but cannot seem to find at this moment the ability for the above, unless it's custom hack or something.

Has anyone used the Rate module for similar, or would anyone like to share a general overview of what's needed to accomplish such a task?

Drupal is very capable in this arena.

A few modules that come to mind are:

Voting API
Fivestar
Rate

With more detail I think you would get a better answer, but at a glance I believe you could accomplish this quite easily with readily available modules.

The tricky part I believe will be figuring out how to structure your site.

Will People/Service providers be stored as nodes or user accounts?

Will users need to register to rate? Can anonymous users rate? Both?

Can service providers register their own business/service or will you be adding a pre-selected list?

If you create a custom content type called "Service Provider" for example, you could apply the Rate module to this content type and have something up and running quite quickly.


File directories question I've started learning Drupal 8 and I have question about file directories.

Previously on D7 I've set directories like this:

files - /sites/all/files

modules - /sites/all/modules

themes - /sites/all/themes

Usually I don't make multisites, so can I set directories like this for D8?

files - /files

modules - /modules

themes - /themes

In Drupal 8, /modules and /themes are already in the root for you. Within them, you can also do /contrib and /custom for further organization.

I have never put files in the root, but I suppose you could as long as you ignore it with git.

See this answer for more detail: https://drupal.stackexchange.com/a/84851/57


Couple of important issues before I migrate into Drupal Currently my website is in .NET and I would like to migrate to Drupal in order to manage the content better.
My site currently supports 22 languages having different domain names for each language. The site has the same theme for all of the domains.
Generally, the site (including all of its domains/languages) is divided into 3 subfolders/sections which are responsible for different content and slight changes in the theme. for example:
The URL http://www.example.fr (which is responsible for the French language) is divided into 3 content sections:

http://www.example.fr/sec1/
http://www.example.fr/sec2/
http://www.example.fr/sec3/

and so is the other domains/languages. As a matter of fact, each section contains a slightly different version of the whole site.
I have installed fresh D7 and also I have installed i18n (and its dependencies),pathauto, panels and context modules but I have yet succeeded to answer the following questions:

How can I create a node and assign it to one of the above sections ?
Once I have managed to assign a node to a section, how can I make it have a URL prefixed by the appropriate section prefix like sec1,sec2 etc. ?
How can I have my theme changed according to the section the user is in?

I have heard that Drupal has a very supportive community so I am really looking forward to someone who will be able to help me in these matters as soon as possible.
So thank you all.

Taxonomies and pathauto/token will solve your first two questions. Use a taxonomy to categorise your nodes, then use a token such as [term] or [termpath] to add it to the start of the automatically generated URL paths.

The sections module will solve your last question. You can assign different themes based on paths, or for individual nodes, and some other ways too. Unfortunately, it looks like it doesn't currently have a released D7 port. There may be one in the works, or you may need to try to port it (likely not hard from my understanding of how it works). Possibly related project is taxonomy_theme, which seems to have a -dev D7 release. I haven't used this module in either D6 or D7 personally though; I know sections works fabulously though in D6 despite not having an update in 2 years now.


How to display IMCE file browser in overlay or popup window? When users access the IMCE file browser from their user profile it gets integrated in the websites main content. I want it to be displayed in the administrative overlay or even as a popup. Does anyone know how to do that?

I have checked the configuration settings, but it doesn't seem to be that easy, or I overlooked something. I also checked the module ThemeKey, but I think that would be a little overkill.

Any help would be appreciated!

Using the Media module instead of IMCE provides a powerful popup media asset browser that integrates with WYSIWYG.


How do I rename uploaded files? How do I rename the uploaded files for my module?

You might find some information about how to code changing file names in the File (Field) Paths module.


My uninstall module tab is almost empty hello to the drupal pro,

I have over 50 disable modules listed on my module list page but only one appear under the uninstall tab. (Toolbar module)

I discovered that when i wanted to uninstall a module for the first time

Any idea why?

PS: i'm running my drupal site on the localhost using WAMP server

Modules only appear listed on the uninstall tab if they have been enabled and then disabled at some point in the past, AND if they actually installed something in the database that can be uninstalled (i.e. custom tables, variables, etc.) OR they implement hook_uninstall, even if they don't install anything in the database.


last entry in home page I created a content type and created various entries. Each entry has the following fields:
name, photo, date.

How can I put a box on the home page with fields covering only the last entry?
(I would also like a page with squares side by side, sorted by date.)

You need to use CSS last-child selector to theme last entry as a box ! You need to write css in you active theme style.css.

  I would also like a page with squares side by side, sorted by date.

For above you need to use views module and display nodes in grid format sorted by sort filter date.