Unlimited Custom Form Fields - Without Ajax I have a simple form where users can set the number of fields they need. Users may need 100+ fields so I am not using ajax "add more" options.

With the below code, everything works (Even though you have to save the form twice, once to add the fields, twice to save the data), but I get an Undefined offset notice Notice: Undefined offset: n anytime I increase the field count and save the form.

As I'm not sure a better way to ask this question...

1) I know the code below is not perfect UX (having to save a form twice), does Drupal offer any API advantages to my approach I am not aware of?

2) Is there a way to handle/suppress these notices?

public function buildForm(array $form, FormStateInterface $form_state) {

  $config = $this->config('MYMODULE.settings');

  $form['#tree'] = TRUE;

  $form['fieldset'] = [
    '#type' => 'fieldset',
  ];

  $form['fieldset']['field_number'] = [
    '#type' => 'textfield',
    '#default_value' => $config->get('field_number') ?: 1,
  ];

  for ($i = 0; $i < $config->get('field_number'); $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      '#default_value' => $config->get('field')[$i] ?: '',
    ];

  }

  return parent::buildForm($form, $form_state);
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();

  $this->configFactory->getEditable('MYMODULE.settings')
    ->set('field_number', $values['fieldset']['field_number'])
    ->set('field', $values['fieldset']['field'])
    ->save();

  parent::submitForm($form, $form_state);

}

My issue was from improper checking of array key values. Below is the approach for non-ajax form adjustment (which is very similar to ajax).

MYMODULE/src/Form.php:

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

  // get form config.
  $config = $this->config('MYMODULE.settings');

  // Set our count. Used in for loop below.
  if (!empty($form_state->getValue(['fieldset', 'field_count']))) {
    // get $form_state count value.
    $defaultCount = $form_state->getValue(['fieldset', 'field_count']);
  }
  else {
    // Get config count value.
    $defaultCount = $config->get('field_count');
  }

  $form['#tree'] = TRUE;

  // Fieldset item.
  $form['fieldset'] = [
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  // Field count item.
  $form['fieldset']['field_count'] = [
    '#type' => 'number',
    '#title' => 'Number',
    '#required' => TRUE,
    '#default_value' => $config->get('field_count') ?: 1,
  ];

  // Rebuild submit item.
  $form['fieldset']['rebuild'] = [
    '#type' => 'submit',
    '#value' => 'Apply number',
    // Make our call to the rebuild function.
    '#submit' => ['::rebuildFormSubmit'],
  ];

  // Loop through our count and create form items.
  for ($i = 0; $i < $defaultCount; $i++) {

    $form['fieldset']['field'][$i] = [
      '#type' => 'textfield',
      // This is important. Must check isset() to avoid Undefined index notices.
      '#default_value' => isset($config->get('field')[$i]) ? $config->get('field')[$i] : '',
    ];

  }

  return parent::buildForm($form, $form_state);

}

/**
 * {@inheritdoc}
 */
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

Related question: Get an Un-submitted/Active Form Field Value in $form_state?.


One Time Bulk Node Creation I have Drupal 8 site I need to migrate a bunch of data into from a different CMS.  What I'd like to do is write a basic SQL query and iterate through the results, creating a new node for each returned row.

Since it's a one time thing - do I need to write a full module for this - or can I just hook into drupal some other way (like through the main index.php file) and do the node::create([]) $node->save() stuff from within there?

Never done something like this before - and looking for the easiest way.  Any help/guidance is appreciated!

Your options are:

Feeds module - You can check the doc here.
Export the content from source into csv or json. On the target (D8) either you can use Migrate module to handle the migration but requires custom coding.
Create a json endpoint that will expose the content and in your target (D8) server consume that endpoint. You can then get the content by using Guzzle.

Example...

$request = Drupal::httpClient()->get($url);

See this page for more info.

P.S: I have no experience building with D8 yet but my suggestions above I guess is still applicable.


Integrity constraint violation: 1048 > Column 'entity_id' cannot be null Whenever I try and create a new node (of type article, page, blog, etc), for some reason I get thrown the following error upon hitting the save button.

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
  Column 'entity_id' cannot be null: INSERT INTO {pathauto_state}
  (entity_type, entity_id, pathauto) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2); Array (
  [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] =>
  [:db_insert_placeholder_2] => 1 ) in pathauto_entity_state_save()
  (line 492 of /sites/all/modules/pathauto/pathauto.module).

I've tried going into the database and setting these columns to allow NULL, but this doesn't seem to fix the issue. I've also tried uninstalling and reinstalling the pathauto module, but no luck.

This error was occurring previously with a couple of other modules, and I seem to have fixed them. I'm just not sure why this error is occurring at all (e.g. I can edit and save existing nodes, but creating new ones all of a sudden is a problem?)

UPDATE: Another issue I seem to get:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
  Column 'id' cannot be null: INSERT INTO {file_usage} (fid, module,
  type, id, count) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4); Array (
  [:db_insert_placeholder_0] => 126 [:db_insert_placeholder_1] => file
  [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] =>
  [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 698 of
  /includes/file.inc).

Short answer

It sounds like you have some code which deletes the node ID on saved nodes causing trouble.

Longer answer.

When you create a new node, Drupal will internally make an insert to the node table to generate an ID and then use that id to populate node_field_data and node_field_revision tables (assuming you are using revisions). The ID is also set on the node entity itself and is accessed via the id() method on the Node class.

The NodeForm does a check on the node object upon being saved, and rebuild the form in case the node doesn't get an ID.

Since you don't get an error for node_field_data and node_field_revision tables, it's pretty safe to assuming that the ID generation works and the node is populated with the ID (Core has lots of test cases covering this).

Since stuff reacting to the node being saved fails, with the missing ID, some code must delete the ID after it's set. Class instances are passed by reference, meaning that if you change one instance you change it every where that class instance is used. So most likely you have some code messing stuff up. There is a good chance that it's some code implementing hook_entity_insert or hook_entity_update (or the node specific variations of those hooks).


Can we pass argument to a form from a Twig template I have a form that accepts a custom argument sourceid

 public function buildForm(array $form, FormStateInterface $form_state, $sourceid = NULL)

Now, this form is displayed in a twig template multiple times using a for loop.
For each instance of this form the sourceid is different in the twig template.
The value of the sourceid is present in the twig template. Can I pass it to the form from the twig template itself? Or should I modify my controller and render the form in the template along with the id?

Code in the twig template displaying the form is as follows:

{% for item in field %}
    {% if item.content %}
      <p> {{ item.content|raw }} </p>
      <p> {{ item.sourceid|raw }} </p>
      <div>{{ metadata_form }}</div>
    {% endif %}
(% endfor %}

The variable metadata_form has the form element in it.

I think the most elegant way is to modify your controller so all the logic happens in the controller and only the markup in twig. If you have that option that's the way to go.

That being said, there are ways to get what you want.
The most convenient way I know is the twig_tweak module and use the function

{{ drupal_form('yourmodule\\namespace\\Form\\yourForm', sourceid) }}

I have not tested it myself but it should work.


How to add class to field--item element generated by paragraphs I have a paragraph type called "Grid Item".

I've created a file called "paragraph--grid-item--default.html.twig" where I print all my required fields.

It all works as expected, but I need to add classes (from some list fields) to the element "field--item". I can add classes in any other children of this element but on directly on it.

This is the current output I have:

This is the code I'm using in the template:

{% block paragraph %}

 {{content.field_image.0}}
            {{content.field_block_title.0}}

 {{content.field_body.0}}

     {{content. field_read_more_link.0}}

{% endblock paragraph %}

The classes content.field_block_size.0 and content.field_block_style.0 are applied as expected but I need them on the parent element...field--item

It depends a little on how your Paragraph is structured. Is it a single paragraph type with multiple generic fields in it or a paragraph with multiple other paragraph types inside of it?

If it's the latter, you have to create two twig files (For the parent and the child) but you can control output for each row and the contents of each row.

Alternatively, if you are just trying to style each item what's wrong with just selecting the field--item elements, eg:

 .field--whatever-parent-is-called .field--item { style here. }


Search only indexing public fields We have a problem with search only indexing fields that have their "Field visibility and permissions" either set to be "Public" or "Custom" with the anonymous user able to view. Any field that is private or has some other custom setting isn't indexed.

I only use Drupal occasionally so I'm far from an expert but as far as I can tell reading around, search should index everything except if it's explicitly told not to.

I've searched around and can't find any setting that would seem to be causing it to behave in this way.

Have I misunderstood how it should behave or is there a setting somewhere I'm missing?

cheers, Gordon

EDIT: I realise that I should have specified that the site is using the Field Permissions module to set the permissions on each of the fields.

Drupal renders a node and passes it to indexer. So whatever you see publicly that what is indexed.

but there are few options you can fix that:

to render a node for indexing this is called: $build = node_view($node, 'search_index'); view mode is search_index, so in your node template you can check what view mode it is and render it differently.
you can use display suite module and then use this display "Search result highlighting input" to configure what is indexed
after node is rendered this hook is called $extra = module_invoke_all('node_update_index', $node);  you could implement it and return extra information

hope it helps


Web application development with Drupal The project manager I am working with is convinced that Drupal can be used to develop a web application that allows user input and rating of the input.  I don't see beyond the Content Management uSage of Drupal.  I claim 100% ignorance. Can anyone point me in the direction of a tutorial or articles that can help me grasp how Drupal will work for the web application I desire to develop?

This is not the place to ask for tutorials.  Exactly what you need depends entirely on what exactly you are trying to accomplish.

To answer your question in general, yes Drupal can be used to create any sort of web app you want, with the proper modules.

First, you should look through the modules page to show the expandability of Drupal and determine which modules you need to accomplish the desired effect.  There are over 16000 modules available.


How to tell whether the current request is part of a cron run? I have a module that needs to behave differently when its hooks are invoked during a cron run.  (For example, my module should redirect normal page requests, but avoid redirecting during a cron run, so that the cron run is not interrupted.)

How can I programmatically determine whether the current request is part of a cron run?

Implement hook_cron_queue_info() to set a global flag indicating that the current request is part of a cron run.

/**
 * Implements hook_cron_queue_info().
 *
 * hook_cron_queue_info rather than hook_cron, to ensure it executes before
 * any hook_cron implementations.
 */
function mymodule_cron_queue_info() {
  global $mymodule_in_cron;
  $mymodule_in_cron = TRUE;
}

Then, elsewhere in your module, you can check this flag:

global $mymodule_in_cron;
if (!empty($mymodule_in_cron)) {
  return;
}

This works both when invoking cron via the web server and via drush cron.


Create a button with an icon in render array, that can be themed by arbitrary contributed themes Drupal 8 does not use HTML button tag for creating buttons, it instead uses the input tag to create buttons. This works fine for most part, except for buttons which include an icon gets messed up by themes which replace the icons with a gradient. For example, Bootstrap theme will replace the button icon with gradient, that makes the button empty.
Is there a way to create a button via render array that will generate <button ...><img ...  style button?
Alternatively, is there a way for a module to only use a twig template in special case, but  not all the time.
Other ideas?
Update: May 7 2020.

I have filed a Drupal Core issue to support new render type for imagebutton, hopefully it will get some attention, as this can't really be solved in contrib space.

You can create a custom HTML tag like this:

return [
  '#type' => 'html_tag',
  '#tag' => 'button',
  '#value' => 'whatever value...',
];

Another solution is to render a custom theme that creates the button, like:

return [
  '#theme' => 'your_template',
];

You can read more about rendering custom templates here.


Error using form API on AJAX submit I am writing a form using the Drupal 7 form API. On submitting the form (via AJAX), the following error is displayed:

  An AJAX HTTP error occurred.
  HTTP Result Code: 500
  Debugging information follows.
  Path: /en/system/ajax
  StatusText: Internal Server Error
  ResponseText: Recoverable fatal error: Argument 1 passed to drupal_array_nested_key_exists() must be an array, null given, called in /drupal7/includes/form.inc on line 1986 and defined in drupal_array_nested_key_exists() (line 6296 of /drupal7/includes/common.inc).

I have two buttons on the form (copy & submit); one is an AJAX call which does some stuff, and the other is used to save the entered data.

This is the code I'm using:

function foo_form ($form, &$form_state, $foo) {
  $form['#foo'] = $foo;
  $form_state['values'] = $foo;

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

  $form['copy'] = array(
    '#type' => 'submit',
    '#value' => t('Copy foo'),
    '#limit_validation_errors' => array(),
    '#submit' => array('foo_form_submit'),
    '#ajax' => array(
      'wrapper' => 'foo-form-wrapper',
      'callback' => 'foo_form_callback',
    ),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#maxlength' => 255,
    '#default_value' => (!isset($form_state['values']['name']) ? $foo->name : $form_state['values']['name']),
  );

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

  return $form;
}

function foo_form_callback($form, $form_state) {
  return $form;
}

function foo_form_submit ($form, &$form_state) {
  // Did we use the AJAX Call?
  // @todo: can we check this some other way?
  if (!isset($form_state['triggering_element']['#ajax'])) {

    // We didn't, save the entered values

    $form_state['rebuild'] = false;
    return;
  } else {

    // We did, do some behind the scenes stuff...

    $form_state['rebuild'] = true;
  }
}

Does anyone have an idea of what could be wrong?

This line is wrong:

$form_state['values'] = $foo;

No idea what you are trying to do here, but you must not mess with $form_state['values'] directly.

And what you are trying to do with the #default_value shouldn't be necessary either. Form API should automatically re-use an already entered value, without you having to set it as the default_value.


Child of a child theme I am building a series of very similar sites, and so opted to run them all from a singe installation of Drupal 7. I have this all set up and working correctly.

As mentioned, these sites will be almost identical, but branded differently - the only changes being different logos, colours etc. Structurally, they will all be a match.

I am using Zen and building child themes for each of these sites, but I would really like to be able to make a 'master' Zen child theme which contains the bulk of the customisations, then each site could have a child of that with the few applicable brand changes required.

1) I could change the name of the parent Zen theme and customise away (and am actually tempted to do that). Its not good form though.

2) I could make one of these sites the 'master' and symlink the important bits to the other sites.

3) I could stop trying to find a solution, and just get on with the job, copy/paste in hand.

Does anyone know if there is a 'proper' way to do something like this? I'm totally flexible on any of the details - don't have to use Zen, for example.

Thanks!

Yes you can do this.

I often use zen as a base theme and have some common things that are always in the sites we're building, so we have a common sub-theme theme of zen, and then each site has a sub-theme of the common sub-theme.
For things like this it is great to use this kind of setup.

So you have:
Zen > Zen sub-theme > Zen sub-sub-theme

In the sub-sub-theme the base theme would be the sub-theme.

For more detailed information on how it all works, see the Creating a sub-theme page.


How to fill select options based on previous select? I'm trying to get the hang of Forms'N'Ajax in Drupal 8.

I have a classic problem with my selects in D8:

$form['manufactureYear'] = array(
  '#type' => 'select',
  '#title' => $this->t('Manufacture year'),
  '#options' => $manufactureYears,
  '#required' => TRUE,
  '#ajax' => [
    'callback' => array($this, 'populateDurationYears'),
    'wrapper' => 'edit-loanDurationYears'
  ],
);

Then I have a second select:

$form['loanDurationYears'] = array(
  '#type' => 'select',
  '#title' => $this->t('Loan duration years'),
);

The function populateDurationYears is the one that are killing me. I've tried with the ReplaceCommand in a AjaxResponse, but when I submit the form the loanDurationYears select is empty.

Can somebody help me here?

EDIT:
 - If I change ReplaceCommand with AppendCommand it's almost correct. The code now looks like this:

<select id="edit-loandurationyears" class="form-select" name="loanDurationYears" data-drupal-selector="edit-loandurationyears">
  <div>
    <option value="3">3 years</option>
    <option value="4">4 years</option>
    <option value="5">5 years</option>
    <option value="6">6 years</option>
    <option value="7">7 years</option>
    <option value="8">8 years</option>
    <option value="9">9 years</option>
  </div>
</select>

What's up with that <div>? It messes up the select :-(

EDIT 2:

The populateDurationYears method looks like this:

$response = new AjaxResponse();
if($maxDurationYears != 0) {
  for($i = $minLoanDurationYears-1; $i < $maxDurationYears; $i++) {
    $option .= "<option value='" . (string)($i+1) . "'>" . (string)($i+1) . " år</option>";
  }
  $response->addCommand(new AppendCommand('#edit-loandurationyears', $option));
}
return $response;

I've figured it out on how to do this...

I fill out the #options for the second <select> when I build the form.
I hide it with a #states.

When the user then selects something in the first <select> I use the populateDurationYears method to remove invalid options like this:

$options = [];
if($maxDurationYears != 0) {
  for($i = $minLoanDurationYears-1; $i < $maxDurationYears; $i++) {
    $options[] = ($i+1) . " years";
  }
  $form['loanDurationYears']['#options'] = $options;
}
return $form['loanDurationYears'];

This does the trick :-) No need for AjaxResponse or anything like the ReplaceCommand etc... Keep it simpel Stupid! ;-)


Would be creating menus totally in views reasonable? Above question is about two situations:

Standard, simple menu with 1-2 levels of depth,
Catalog on commerce site, with number of products, next to every item (taxonomy term) of menu.

I can imagine, that counting all nodes related to every taxonomy term every time when site is accessed would kill the server (if there is like hundreds of products), but views have some cache option, don't they? Can they cache their output and make menus views driven reasonable?

Yes. That's the point of views, you should not worry about performance at that point, just build the menu and if later you find that performance is worse than expected start taking a look at this question, there is a big amount of information on views caching. If you need more you can also go here to find more information on caching and performance in general.


Some of my site's pages are retrieving the .css files from a different directory I've been working on theming a Pages page on my local machine. This has been going fine, but now I have pushed the changes to a remote server and see that the site is trying to retrieve the .css file from the wrong directory.

On my local machine, this is fine. On the remote machine, it seems drupal is trying to retrieve the .css file from sites all:

@import url("http:/mysite.com/sites/all/themes/custom/mytheme/css/main.css");

Where as my local version has:

@import url("http://localdev.mysite.com/sites/mysite.com/themes/custom/mytheme/css/main.css");

Would anyone know why this is and how I could correct it?

May I know where you have added CSS? on theme.info file or template.php

This issue occurring because of your theme has contained an absolute path, You need to replace absolute path the relative path.

First, you need to check that, On which file this CSS has called.

Remove from there and add CSS on theme.info file or template.php file.

On theme.info you need to add like stylesheets[all][] = custom/mytheme/css/main.css

On template.php you need to add css using drupal_add_css on template_preprocess_html(&$variables).


User Locked out after 5 failed login attempts - how to help him? I have a user with 5 failed login attempts...and now he's locked out. We reset his password...but is there something else we need to do to unlock his account on a basic Drupal 8 setup?

I'd rather not have to get into using drush on this remote server and messing around with db tables...especially since this is just one user out of thousands. I just want a simple UI solution.

Or does he have to wait 6 hours or something crazy?

If you use flood_unblock module you can just flush the flood for the specific user or ip.


How to create custom bundle of "User" entity using GUI? Is it possible to create custom bundle from "user" entity without programming? Only using drupal administration? Are there any modules that could help to create such bundles?

I would like to achieve, that some user roles would have custom fields. I have found this module for creating fields per user role, but maybe it would be better to create custom user bundle.

I had the same requirement recently and was able to achieve this using the Profile2 module.  Basically you set up profiles and add custom fields to that particular profile.  Then you create a user using that profile.  Works great but if you are pulling a view of these you must reference the profile in a relationship.

Profile2
https://drupal.org/project/profile2


How to message or invite a group without joining it? I'm using the Group module. I created a group(Job Post) with linked content types (Job details).

Scenario:
As a user, I created several jobs.

I want to be able to invite/message another group (Business) for them to be aware of my posting without joining this group.
Also, because I have more than one active jobs, I want to select a job to send the invite about.
Lastly, if I have already did an invitation to that group, I can no longer send twice.

Question: How can I achieve these three items above?

Note: a User is someone who creates or posts a job (example: electric power shortage). Businesses are created groups, like electricians. The user should invite this business to get notified about his job.

As answered in Get notification message in groups, you use Message Subscribe based on your criteria.

You expose the Message Notify for users, but only difference is here you use a custom module to conditionally display that notification form. If the user has already issued a notification, don't display the form. You should be able to search back through the message log to check if the user has previously notified about this message. Be careful you are not clearing out your message log too often in this case.

If you need to clear out your message log, then you may need to use Flag module to flag that the user has already notified about this job post. i.e. - mark the message / job post as flagged whenever a notification has been sent. Only display the Message Notify form for non flagged entities.


embedding Facebook Video with oembed What is the proper way to embed a (public) facebook video with the oembed field module?

I tried including a video with a link like https://www.facebook.com/video.php?v=55555555555 but when I tested the link I got an error message (log didn't reveal details).

  https://www.facebook.com/video.php?v=55555555555 is not valid oEmbed URL. Please check the error log for messages.

It also doesn't show up in the content type field.

The default schemes didn't do the trick:

http://www.facebook.com/video/video.php*
https://www.facebook.com/photo.php*
https://www.facebook.com/video/video.php*

So I've added this https://www.facebook.com/video.php?v=* in the media - oembed settings for facebook.

still, it didnt work.

Any ideas on what URL I have to provide for this to work?

EDIT:

I've posted an answer that worked for me.

Ideally, it should work without an embed.ly API key.

turned out i needed an API key for embedly service from http://embed.ly/. here is a good guide on oembed http://mustardseedmedia.com/podcast/episode54

strange. some images showed up even without an API key.


Why my Webform special token values not rendered correctly in D6? I am trying to use "Special Tokens" in the Webform module (6.x-3.18) on Drupal 6.  I'd like the data to populate a hidden field I've created with the email field on the same form.

Under default value for the hidden field I've tried using a number of different values including:

%post[submitted][email]

%post[email]

%post[submitted[email]]

None of this works.  If I go edit the email field, it tells me my key is email.  If I look at the name of the email field in the source code it's submitted[email].

If anyone has any suggestions on what I'm doing wrong?

In case anyone comes across this, I finally found a thread confirming that Webform tokens in D6 do not support arrays, and I had to apply a patch for the functionality to work.

This is NOT a problem in D7

http://drupal.org/node/824606

Patch - http://drupal.org/files/nested_tokens-824606-13.patch


Features workflow issue with deleting a field Suppose I have a content type Person with fields: Name, Age, Email

This content type is controlled by a Feature called test so I can source control it and push it to the live site.

My workflow goes like this:

I add a new field on Person called Phone
locally I do: drush fu test -y
I edit the test.info to increase the version number
I commit the changes to my repository
I push the feature to the live site (copy the feature files)
on the live site I do: drush fr test -y
on the live site I do: drush cc all

Then the new field appears on the live site's Person.

If on the first step I remove a field of Person the field will not be deleted from the live site. How do I solve this? I don't want to have to manually delete it from the UI on the live site.
Is this workflow correct?

The correct way to remove Features-created content is via hook_update_N (which should be implemented in the file your_module.install).

The main idea with Features is to manage configuration with code. Using hook_update_N is consistent with that, since the field deletion is in code (which can be managed with version control) — whereas the equivalent command drush field-delete field is not being called from managed code; it's a separate command-line step you need to perform (and to remember to perform).


how to make the field label in Views hidden or visible? i have a view page with Table format i want to control the label of the fields that i added befor .
i changed the php code in (views-view-table.tpl.php) befor so now i can't control the field label ( hidden / visible ) from the view
this is the code that i have now :

and this is the view page even i check the label nothing happen!

anyone can help me with this please ?

This is normal because you are using a template file, view's will use your template file and nothing from the UI (User Interface) for fields.

Therefore, you will need to type Address: in your template file, just like you did for Location:, on line 47.


How can I speed up the module registry approval proces on Drupal.org? The module is done, the code and documentation meets the prescribed standards for Drupal projects, the sandbox project has been created and submitted for review. What more can be done to help speed the review process for a contributors first module?

I don't actually have a module in this position, but recently met a developer who was trying to get a module approved that integrated his new CAPTCHA service into Drupal. Hopefully someone has reviewed and approved it, but you can take a look at the application here to see how the approval process can stagnate.

The process can be very slow unfortunately. There probably isn't a complete answer, but I can give a few hints.

Try to find users which test and report that it works (as detailed as possible), developers to review it and report that too. There are many ways to do that, for example for developers:

Ask in IRC (#drupal-contribute) (Remember to offer something in return, e.g. patch reviews). Do not ask multiple times and only when the channel is quiet.
Review/test applications of other users and ask for a review of yours in return.
If your module interacts with other modules, ask their maintainers to review the integration code. Again, you could help with the issue queue of these modules (review, write patches, answer support questions)

This has two advantages. a) It shows that your module works and users are interested in using it. b) It helps to keep it on top of the (very long) list of issues.

Also, try to make it as easy as possible to install and test your module. For example, if your module integrates with a third-party service/website, provide a test account for it or make it possible to register there for free (if it isn't anyway) and provide detailed installation instructions (for example in a README.txt or INSTALL.txt file).


Creating new bulk views operations (VBO) actions for custom entity types I have the following code and created a view for my custom entity type. I just want to create a new action button to be able to change a field's text to something else. I'm not sure why this custom action isn't showing up. Under which window am I suppose to see it? Execute arbitary php or modify multiple entity values?

Where is a good example code of getting a custom action working? Is there a pre-built VBO action example I can just download to see how it's made?

/**
 * Implements hook_action_info().
 */
function rubik_custom_action_info() {
  return array(
    'hideit' => array(
      'type' => 'entity',
      'label' => t('Custom Action'),
      'configurable' => FALSE,
      'triggers' => array('any'),
      'behavior' => array('changes_property'),
      'vbo_configurable' => FALSE,
      'pass rows' => TRUE,
    ),
  );
}

/**
 * Action function for MY_ACTION_NAME.
 */
function hideit(&$entity, $context = array()) {
  drupal_set_message('ok it works');
}

After your action has been defined, it can be added in the Views UI under Selected Bulk Operations in your Bulk operations field settings. It will be a separate checkbox alongside other actions like Execute arbitrary PHP script, etc. Once selected, it should show up as select option or action button (depending on how the VBO field is configured).

The VBO development guide on d.o. is a good example of working code for defining an action, adding a optional global/per-bulk setting form, & creating action handler.

Here's a very bare bones example:

//Will add a "User Action" option to Bulk Operations: User field in Views UI
function MYMODULE_action_info() {
  return array(
    'MYMODULE_user_action' => array(
      //Can be other entities used in a view (e.g. 'node')
      'type' => 'user',
      'label' => t('User Action'),
      'behavior' => array('changes_property'),
      'triggers' => array('any'),

      //Set to true if you an intermediate options form for your action
      //'configurable' => true,

      //Set to true if you want additional globaloptions
      //'vbo_configurable' => true,
    ),
  );
}

function MYMODULE_user_action(&$entity, $context){
  //$entity is the current entity being modified; it can
  //  modified directly to perform the action on the entity

  //$context is an array of contextual information about the
  //  current state of bulk processing  (e.g. items remaining)
  //  It also contains configurable options values if any were set (see below)
}

//If 'configurable' => true in hook_action_info() item this trio of functions
// will add/process an intermediate form just like any Drupal form
function MYMODULE_user_action($settings, &$form_state){
 //$settings['settings'] will contains settings set in
 //  MYMODULE_user_action_views_bulk_operations_form
}
function MYMODULE_user_action_validate($form, $form_state) {
}
function MYMODULE_user_action_submit($form, $form_state) {
  //return an array of values usable by MYMODULE_user_action
}

//If 'vbo_configurable' => true, in hook_action_info() this presents
// additional configurable options for the  VBO action.
// It returns a Drupal form array
function MYMODULE_user_action_views_bulk_operations_form($options) {
}


getting the value of line item entity field in CommerceLicenseRemoteBase class I am extending CommerceLicenseRemoteBase class for remote synchronization. I have added a custom line item and require that value in

CommerceLicenseSynchronizableInterface::synchronize().

How can i fetch the value of custom line item. I have tried

$license = entity_load_single('commerce_license', $id);
entity_metadata_wrapper('commerce_license', $license)

but that did not work.

Thank you

Generally you'd do something like this:

$wrapper = entity_metadata_wrapper('commerce_license', $license);
$wrapper->PROPERTY_YOU_WANT->value();

(See here for more detail: https://www.drupal.org/documentation/entity-metadata-wrappers)

You could always ask in the issue queue for the module:

https://www.drupal.org/project/issues/commerce_license?categories=All


can't remove js from page I've looked at this post https://stackoverflow.com/questions/9578013/how-to-unset-a-js-file-from-a-drupal6-installation-doesn%C2%B4t-work-with-remove-sc and this one How can I remove Javascript files?

and I've tried to duplicated it, but it wont work. I am trying to unset the regular jquery version. I've added this inside my phptemplate_preprocess_page function:

$js = drupal_add_js();
  unset($js['core']['misc/jquery.js']);
  $vars['scripts'] = $js;

when I print out $vars, it looks like it worked, but the original jquery is still included!

I can think of 4 things to check in this case, in order of likelihood:

What does the preprocess function stub look like?  Are you using the variable &$vars there, too, or are you using &$variables instead (which is how it appears in the documentation)?  They, of course, have to match.
Have you cleared your cache?  D6 was bad about sometimes needing the cache to be cleared twice.
Is the function actually running?  If not, then there may be a problem with the function name that it is not being recognized, or that the cache has not been cleared (which should be taken care of by checking #2).
Is something messing with the variable afterwards that is inadvertently re-adding the core js file?


Is there a way to iterate on all Drupal modules on d.o? I'd like to iterate on all contrib modules, pull their repos and extract information (such as drush commands, graph dependencies, etc.)

Is there a way to list all modules, other than scraping https://drupal.org/project/project_module?

Here is a sandbox module (from a Drupal user I trust) that does it:
https://drupal.org/sandbox/greggles/1481160


Add field to PDF template Hello I am working with Views PDF Module, and I am asking how could add a fields to the PDF template file

Thanks.

From the module page:

  With this module you can output a view as a PDF document. Each field
  of the view can be placed on the PDF page directly in the
  administration interface. Therefore a new display called "PDF" is
  added.

So from within Views, add a PDF page display. Then add the fields you like.


How to add onBlur attribute to ZIP code field in Address Field In order to control the input format in the ZIP code field in the dynamic address fields provided by the Address Field module (I use it in Drupal Commerce) I need to add the attributes onKeyUp and onBlur to this field. My plan is to use Javascript to manage the formatting, but I need to add the above attributes first. How do I do that? I imagine I should use hook_form_alter in my template.php, but I could need a pointer on how to do it.

if($form['#id'] === "edit-customer-profile-billing-commerce-customer-address-und-0-postal-code"){
  dsm($form); // devel message does not show up in the checkout page in question
  $form['#attributes']['onBlur'] = '(this)';
}

EDITED: I have now managed to add the attributes this way:

  function mytheme_form_alter(&$form, &$form_state, $form_id) {
    if($form_id === "commerce_checkout_form_checkout"){
      // Merge new attributes with existing ones.
      $form['customer_profile_billing']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
        'onBlur' => 'setZip(this)',
        'onKeyUp' => 'setLimit(this,5)',
      );
      $form['customer_profile_shipping']['commerce_customer_address']['und']['0']['locality_block']['postal_code']['#attributes'] = array(
        'onBlur' => 'setZip(this)',
        'onKeyUp' => 'setLimit(this,5)',
      );
    }
  }

And this is the js script (I found it here):

(function($) {
        $(document).ready(function(){
            'use strict';
        var setZip, setLimit;
        console.log('outside');

        function setZip(theField){
          console.log('setzip');
          var num = theField.value.replace(/\D/g,"");
          theField.value = num.substr(0,3)+" "+num.substr(2);
        }

        function setLimit(theField, maxDigit){
          console.log('setlimit');
          var num = theField.value.replace(/\D/g,"");
          if(num>maxDigit){
            theField.value = theField.value.substr(0,maxDigit);
          }
        }

    });

})(jQuery);

The problem now is that I get a javascript reference error like this:

  Uncaught ReferenceError: setZip is not defined at
  HTMLInputElement.onblur

I suspect this has something to do with the scope, so I have tried to place the js script with the setLimit and setZip functions in the header, in the body and in the footer, with the same error message. I also tried to remove the $(document).ready(function()... but the reference error reamins.

Any ideas?

In case anyone else has this same problem. I have learned that it's a better practise to only use Javascript with an addEventListener to do this job, due to the scope rules.

This is how I finally did it. Change the code to adapt the formatting to the standard format in your country. This one changes the ZIP code format to five digits with a space inserted between digit 3 and 4.

  if($("#edit-customer-profile-billing-commerce-customer-address-und-0-postal-code").length){
    document.getElementById("edit-customer-profile-billing-commerce-customer-address-und-0-postal-code").addEventListener("blur", function(){
        if(this.value.length>5 && /\s/.test(this.value)){
          this.value = this.value.substr(0,6);
        }   else if(this.value.length>5 && !(/\s/.test(this.value))){
                        this.value = this.value.substr(0,5);
                    }
        if(this.value.length===5 && this.value.substring(3,4) !== " "){
            this.value = this.value.split(/(?=.{2}$)/).join(' ');
        }
    });
}


Unflagging a node with Rules Scheduler I have got an issue unflagging a node with Rules scheduler when triggering it with cron. The node gets unflagged just fine if we execute the component manually, however, if I schedule it to unflag the node like 2 minutes after triggering the Rule, it doesn't unflag the node.  I ran cron multiple times, refreshed the page, but nothing.

I have done some preliminary testing and found out that flag_rules_action_info() is just not being called at all when executing this through cron. I have checked permissions and every thing looks good there. Would appreciate it if you guys could give me some input as to what might be the problem when triggering it with cron. I have included the rules debug info below and an export of the rule and the component. Thanks.

Debug Info:

0 ms Scheduled evaluation of action set my component, task Unbookmark 10..
90.748 ms Evaluating the action component_rules_my_component. [edit]
0 ms Evaluating action set my component.
0.473 ms Evaluating the action component_rules_my_component. [edit]
0.528 ms Not evaluating action set my component to prevent recursion. [edit]
1.07 ms Evaluating the action flag_unflagnode. [edit]
5.439 ms Evaluating the action add_badge_by_name. [edit]
7.16 ms Finished evaluation of action set my component.
98.707 ms Evaluating the action flag_unflagnode. [edit]
98.982 ms Evaluating the action add_badge_by_name. [edit]
116.401 ms Finished evaluation of action set my component, task Unbookmark 10..

Component Export:

{ "rules_my_component" : {
"LABEL" : "my component",
"PLUGIN" : "action set",
"REQUIRES" : [ "rules", "flag", "user_badges" ],
"ACCESS_EXPOSED" : "1",
"USES VARIABLES" : { "node" : { "label" : "node", "type" : "node" } },
"ACTION SET" : [
{ "component_rules_my_component" : [ ] },
{ "flag_unflagnode" : {
"flag" : "bookmarks",
"node" : "10",
"flagging_user" : [ "site:current-user" ],
"permission_check" : 1
}
},
{ "add_badge_by_name" : { "badge" : "4", "user" : [ "node:author" ] } }
]
}
}

Rules Export:

{ "rules_test_scheduler" : {
"LABEL" : "test scheduler",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules", "rules_scheduler", "flag" ],
"ON" : [ "flag_flagged_bookmarks" ],
"IF" : [
{ "entity_is_of_type" : { "entity" : [ "flagged-node" ], "type" : "node" } },
{ "node_is_of_type" : {
"node" : [ "flagged-node" ],
"type" : { "value" : { "blog" : "blog" } }
}
}
],
"DO" : [
{ "drupal_message" : { "message" : "this works" } },
{ "schedule" : {
"component" : "rules_my_component",
"date" : "+2 minutes",
"identifier" : "Unbookmark [flagged-node:nid].",
"param_node" : [ "flagged-node" ]
}
}
]
}
}

I have figured this out myself.  Please refer to Comment #5 in Issue 2094541 for the answer, located at the following link:
https://drupal.org/node/2094541#comment-7955705
Here is what it says:

Finally, figured this out! The problem is, we're not supplying the required parameters to the Rules component. If you have given it only 'node' as the parameter, then, when you add the action to 'Unflag a Node', you must give the 'User on whose behalf to flag' a data selector such as 'node:author'. You can't do something like 'site:current-user' because that parameter is not available to the component when run through Cron.
Once you give it the required parameters, it should unflag the node through Cron.


How to upload multiple files and predefine filetypes? Does someone know how it is possible to upload multiple files with the dropbox client module for drupal 7?

It would be nice if it could be integrated with plupload.

Also i would like to know how i can predefine the filetypes users can upload?

I'm a n00b in php, can someone give me some tips or solutions?

Here is the part of the upload funktion in the dropbox client module.

function dropbox_client_upload_form( $form, &$form_state ) {

  $form[ 'upload' ] = array(
    '#title' => t('Upload file'),
    '#type' => 'file',
    '#size' => 20,
    );
  $form[ 'submit' ] = array(
    '#type' => 'submit',
    '#value' => t( 'Upload' ),
    );
  return $form;
}

function dropbox_client_upload_form_submit( $form, &$form_state ) {

  global $user;

  $dropbox = dropbox_client_get_client();

  //Process files
  $uploads_dir = dirname( $_FILES[ 'files' ][ "tmp_name" ][ 'upload' ] );

  $tmp_name = $_FILES[ 'files' ][ "tmp_name" ][ 'upload' ];
  $name = $_FILES[ 'files' ][ "name" ][ 'upload' ];
  $filename = "$uploads_dir/$name";
  move_uploaded_file( $tmp_name, $filename );

  $dpath = (isset( $_GET[ 'dpath' ] )) ? $_GET[ 'dpath' ] : '/';
  $result = $dropbox->add( $dpath, $filename );

  if ( property_exists( $result, 'error' ) ) {
    drupal_set_message( $result->error );
  }
  else {
    drupal_goto( $_GET['q'], array( 'query' => array( 'dpath' => $dpath ) ) );
  }
}

Thank you!

Best regards,
meckl

Also i would like to know how i can predefine the filetypes users can
  upload?

Specify the file types restriction on the file field with 'file_validate_extensions' in the #upload_validators array in the file field.
See the form api for reference. See the file_managed field.


Can I set up Paypal recurring payments on Commerce Kickstart? Like the title suggests,
I am using Paypal for provide an apparent 'Trustworthy' service to my customers.
I offer a flat-price cleaning service.
I would like to offer a weekly, fortnightly and monthly service to my current 'products' at different discount rates on the original product.
can someone help me perform this?

The only existing module-based solution is Commerce SP plus Commerce SP PayPal.

The latter is in dev at the moment, but I've found it to work pretty well, albeit with a few minor business-specific alterations.


How to render taxonomy field_custom in page--taxonomy--term.twig? I have a custom field in my taxonomy. How to render programmatically this taxonomy field in page--taxonomy--term.twig?

You need to prepare the Twig variable in a preprocess hook:

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
    $variables['field_example'] = $term->field_example->view();
  }
}


CKeditor cannot find ckeditor.js I am in the process of upgrading a Drupal install from 6 to 7. Drupal 6 uses the ckeditor module without any difficulties.

As I upgraded to Drupal 7 and the latest version of ckeditor, the module no longer works.

Firebug gives me an error message:

Failed to load resource: the server responded with a status of 404 (Not Found) http://mysite/ckeditor.js?mcqjp7

I'm not sure why ckeditor is looking in the site room for that file.

It has no trouble finding the css file

<style type="text/css" media="all">@import url("http://mysite/cms/sites/all/modules/ckeditor/ckeditor.css?mcqjp7");

So why can it find the CSS file but not the JS file?

You have to check the libraries for ckeditor in your drupal site.

sites/all/libraries/ckeditor

In D7 the CKEditor contain the libraries for editor. if you don't have then download the module and library from http://ckeditor.com/download


How to add additional "items" on a webform in Drupal 7 I would like to provide the option of creating additional text fields under the same Label, if necessary. In the form of an "Add another" button. So when this button is pressed, an additional textfield will appear underneath. So, much like adding unlimited attachments to a node for example.

Is this possible using the Webform module?

The module Webform Add More does similar thing,

  Webform Add More enables selected fieldsets to be initially hidden and
  progressively shown with an Add more button, mimicking CCK multiple
  fields. The approach was proposed by Bartezz, and code originally
  implemented by span and kranklin 1. This module adds a checkbox
  setting to webform fieldset components to select which should have Add
  more functionality, as well as an advanced setting to override the
  button label per Webform.


How to add advertisement node at the end of Slideshow I have three content type
1) Slideshow
2) Slides
3) Advertisement

While creating slideshow we can assign slides to slideshow with nodereference field.
We have created a views for slideshow on the view page of slideshow we are displaying all the slides one by one and there are two links next and previous.
Now I want to add a single Advertisement at the end of this slideshow view.

I tried hook_views_api() and hook_views_query_alter().
Content type slides and advertisements have different fields.

slides are usually images or maybe node bodies (html). It doesnt really matter that advertisments have different fields. I had some code in Drupal 6 you could adapt to D7 or your needs, look into hook_views_pre_render() ...

You simply want to load your advertisement node(s) before the view is rendered and add them to the end of the slideshow ... see below.

//d6 example
function MYMODULE_views_pre_render(&$view) {

  if ($view->name == 'your_view' &&
    $view->current_display == 'slideshow_xyz') {
    // Insert something to the end of the view results.
    // For example another "node" or advertisement.
    $some_node = node_load(array('nid' => 456));
    // make a fake view row item with your advertisement.
    // you should create all fields used in "slides" from your
    // advertisement node data.
    $advertisement_item = new stdClass();
    // add your advertisement fields as fields being used by the Slide view.
    $advertisement_item->a_field_views_is_using = $some_node->advertisement_field_1;
    //  ... add all other view row items you are using ....
    // make this advertisement "row" in the results appending to the view results for slides.
    array_push($view->result, $advertisement_item);
  }
}


How do you output and modify the Content:Path variable using field:PHP global? I'm trying to modify the content:path variable using PHP field in Views for Drupal 7. The $data and the $row->path gives a blank result. Anyone know why?

It seems that I can grab it via the $views variable, but i have to dig deep into it in order to find it. Is there an easier to to access the content:path field via PHP in views?

To get the content id path data I had to get it from the $view variable:

$view->style_plugin->render_tokens[0]['path']

As seen below the $row->path data is NULL for some reason. Same goes for $data variable as that doesn't have any data at all.


D7: form input name array need to build a form which has fields of type array.
php normally would:

<input name="MyArray[0]" />
<input name="MyArray[test]" />
<input name="MyArray[1]" />

$array = $_POST['MyArray'];

already tried the following but is not input as an array:

$form["MyArray[1]"] = _d7_taxonomy_term_select($node_type->name, 2, $default_value);
$form["MyArray[2]"] = _d7_taxonomy_term_select($node_type->name, 2, $default_value);
$form["MyArray[3]"] = _d7_taxonomy_term_select($node_type->name, 2, $default_value);

someone help?

You need to specify them like this and set #tree to TRUE. Like this.

$form['MyArray']['#tree'] = TRUE;
$form["MyArray"][1] = _d7_taxonomy_term_select($node_type->name, 2, $default_value);
$form["MyArray"][2] = _d7_taxonomy_term_select($node_type->name, 2, $default_value);
$form["MyArray"][3] = _d7_taxonomy_term_select($node_type->name, 2, $default_value);


Add Menu Block (module) Menu To Page tpl Hello i am trying to avoid using the block system with drupal. Im using panels and i dont like having to add the main content if i use any block in a region. anyhow.... i was hoping to add a menu block i have to my page.tpl

The block i want to add has this url to it when i edit it-
block/manage/menu_block/2/configure

The code im using to add another block is

    <?php
      $block = module_invoke('md_megamenu', 'block_view', '1');
      print $block['content'];
    ?>

Ive tried a few things with not much success. If i was to choose my best effort it would be-

   <?php
             $block = module_invoke('menu_block', 'block_view', '2');
          print $block['content'];
        ?>

this just shows 'array' though.

could anyone suggest anything i should try?

Thanks

It seems like you're mixing the Drupal 6 and Drupal 7 api a little bit.

If you're on Drupal 7, you should print out your block like this:

<?php
$block = module_invoke('module_name', 'block_view', 'block_delta');
print render($block['content']);
?>

Note the 'print render'. (You're missing the 'render' part if you're on Drupal 7.

The only things you need to change are to put 'menu_block' for the 'module_name' and your block's machine name for 'block_delta'.

More info and examples are on drupal.org: http://drupal.org/node/26502

Does that work for you?

============ Edit ==============

On the other hand, if you're on Drupal 6, your call should look something like this:

<?php
$block = module_invoke('module_name', 'block', 'view', 'block_delta');
print $block['content'];
?>

In this case, you're fine with the just 'print $block['content']', but your arguments are a little off.  From what you're saying though, it sounds like you're on Drupal 7, and are just returning the array without rendering it!!! :-)


The page request for /admin/structure/block only returns part of the html and doesn't render it I'm logged in to Drupal and am requesting the blocks page at /admin/structure/block.  However, the page request doesn't render properly in my browser.  (I tried two different browsers with similar results).

The page I get begins with this:

d90
>configure
        delete

        Set Free - FAQ 1

   Region for Set Free - FAQ 1 block
  <select class="block-region-select block-region-user_first
form-select" id="edit-blocks-block-333-region"
name="blocks[block_333][region]"><option value="-1">- None
-</option><option value="help">He

Or this:

10000 ion><option value="map">Map</option><option
value="preface">Preface</option><option
value="breadcrumb">Breadcrumb</option></select>
 <input
type="hidden" name="blocks[block_110][theme]" value="omnia" />

   Weight for 30 DIGITAL TALENTS -
Home Corprate block   <input class="block

or this:

a46c t form-select" id="edit-blocks-block-366-region"
name="blocks[block_366][region]"><option value="-1">- None
-</option><option value="help">Help</option><option value="content">Content</option><option value="top_first">Top
First</option><option value="top_second">Top Second</option><option
value="top_third">Top Third</option><option value="top_fourth">Top
Fourth</option><option value="social_top">Social Top</option><option
value="search_form">Search Form</option><option
value="logo">Logo</option><option value="menu">Menu</option><option
value="strapline_first">Strapline</option><option
value="latest_first">Latest Work</option><option
value="sidebar_first">Sidebar First</option><option
value="sidebar_second">Sidebar Second</option><option
value="postcontent_first">Post Content First</option><option
value="team_first">Team First</option><option
value="logoslider_first">Logo Slider First</option><option
value="bottom_first">Bottom First</option><option

Every page refresh is different.

Anyone have any ideas?

I have a custom module or two, but I don't think they are doing anything bad.  We haven't touched the theme. I've cleared Drupal's cache.  I can't see anything relevant in Drupal's log or the PHP error log.  Every other admin page works fine.  Any ideas?

I got it working.  This is what I did: I restarted Windows.


How do I use a preprocess function to add custom classes to a view fields? I have a View that outputs several fields per row. I'd like to use a preprocess function to add a class to one of the fields, depending on the value of another field. How do I do that in Drupal 8?

Note, I do not want to add a class to the entire row -- just a specific field in that row. The output would be something like:

 ...

 ...

As mentioned in the comment you can add classes to fields through the interface, and you can use field tokens as CSS classes.

Add field-value-based CSS class to a field

Position the field with the value you want to use as the CSS class (the value-class field) above the field where you want the class to appear (the styled field).
Set the value-class field to Exclude from display if you don't want it to appear there.

If you need it visible in some other place then add that same field again where you need it, while keeping the first one for the token (because you can only use tokens of fields preceding in the Fields list).
Edit the field where you want to apply the CSS class (the styled field) >

Uncollapse Style settings >
Customize field and label wrapper HTML (or Customize field HTML if you don't need the wrapper) >
Create a CSS class and
enter the first part of your class (myclass)

(class names can't start with numbers and some special characters so it's good to control at least the first character to make it independent of the other field's value to prevent trouble down the line).

Uncollapse Rewrite results (don't enable it, you just need to temporarily reveal and uncollapse to copy the token),

uncollapse Replacement patterns,
copy the value-class field token and
paste it in the above CSS class field

(you end up with something like myclass-[field_name_a]).

Save the View and check your HTML output (in any theme), you will see a class based on your value-class field on the field where you added the class, something like class="views-field views-field-name-b myclass-namebvalue".


How to alter main_menu for logged user? I would like to alter/change structure of main menu links (programmatically!) for logged in users. What is the simplest way to do this?

I hope, Drupal 7 main-menu - change item text if user logged in you check this first.

If this does not complete your requirement, then, u have to override the theme_menu_link hook.

http://api.drupal.org/api/drupal/includes!menu.inc/function/theme_menu_link/7

You can check whether the user is logged in or not by checking boolean $logged_in. If it is true, user is logged in else not.


Best Approach for View Caching using a Proximity Filter I have a view that is time-based cached.

One of the options on the exposed form is a 'near me now', which sorts the results by distance and displays mileage.

The users location is provided by the IPM&V Module, and works fine with the view cache turned off.

The problem is that with cache-view turned on, sorting by near me now continues to display the results based on previous requests.  The view is 'cached' and not using the current users location.

I could simply turn views caching off, but hate losing the extra speed.

Is there a way (a hook or function) that tells views to 'refresh/clear cache' if certain conditions are met? Ie, if user selects 'near me now' do not cache.

I looked at a combination of rules/cache action, but couldn't get it to work on a specific filter input.

Any ideas appreciated.

How about this module:
https://www.drupal.org/files/images/Views_content_cache.png

Without testing it I cannot tell if it will expose the 'nearby' state as a filter for for the update cache  function but looks like a good place to start:


Which tables are safe to clear? I have inherited a client site that has an extremely large database for no reason. There is a moderate amount of content and very little enabled modules. However, the database is too large for moving around easily and I want to clean it out.

I have cleared out the standard cache tables, syslog and accesslog.

Are there any other tables I can safely truncate in a standard Drupal site?

Drupal 7 tables that can be excluded

Here is a list of tables in Drupal 7 that you can either clear (to reduce the database size) or safely exclude to do a migration (as in the question about How to reduce the locally exported database size to get around my server import limit?):

accesslog
batch
all cache related tables, such as:

cache*
cache_block
cache_content
cache_filter*
cache_form
cache_calendar_ical
cache_menu*
cache_page*
cache_views
*_cache, such as features_cache or views_data_object_export_cache

ctools_views_cache
ctools_object_cache
devel_queries
devel_times
flood
history
queue
various search_* tables, such as:

search_dataset
search_index
search_keywords_log
search_total

semaphore
sessions
watchdog
webform_submitted_data

Usually tables such as search_index and watchdog use a lot of database space, so just eliminating those 2 tables can make a huge difference already.

Other tables that might be excluded

Check the size of your remaining tables and identify which one of them are the biggest in size.

Typically you might find session tables for which no cleanup procedure is in place. Such tables you can probably also exclude.

Module Backup and Migrate

To further reduce the challenge as detailed in "How to reduce the locally exported database size to get around my server import limit?", look at the Backup and Migrate module also. Here is a quote from its project page (bold markup added here):

  Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.

And there is even more: if your local environment (e.g. Win or Mac) differs from the OS that the server of your hosted website is running (like Linux), then these differences between OS-es imply potential extra challenges. I've had good experiences with the Backup and Migrate module between different OSes, which didn't cause any problems (worked fine) in situations where the typical MySql export / import failed before.


Display additional fields in the Inbox? I have added two new fields (a Viewfield and a simple text field), and I would like to display these fields in the Inbox (/messages) along with the existing Subject, Participants, and Last Updated data. How can I add those fields to that page ? Is there a tpl format I could use ?

/**
 * Implements hook_form_alter().
 */
function modulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'privatemsg_list') {
    $form['updated']['list']['#header']['bar_column_field']['data'] = 'Bar Column';
    $form['updated']['list']['#header']['bar_column_field']['field'] = 'bar_column_field';
    $form['updated']['list']['#header']['bar_column_field']['class'][] = 'privatemsg-header-bar-column';
    $form['updated']['list']['#pre_render'][] = '_pre_render_bar_column';
  }

/**
 * Custom #pre_render function.
 */
function _pre_render_bar_column($tableselect) {
  $i = 0;
  foreach ($tableselect['#options'] as $id => $options) {
    $data = 'Bar data in the table ' . $i++ . '';
    $tableselect['#options'][$id]['bar_column_field'] = array('data' => $data, 'class' => array('privatemsg-list-bar'));
  }
  return $tableselect;
}

You can change the $data variable with any field's value, after performing a query or something, and placing your actual data to the new column.
A field could be attached to messaging (admin/config/messaging/privatemsg/fields) or to any other available entity.


How to use entityform and ajax_form_entity in a modal window? Just getting started with the entityforms module (and it looks sweet!).  I want to create a 'contact us' link that displays the form in a modal window, submits and then closes the window.

There is a related module, ajax_form_entity, that looks like it would help make a clean submission.  The demo site has a 'Views popup integration' section, but that doesn't look useful (or relevant, actually).

Anyone know how I can do an ajax submit of an entity form from a popup?

There is a sandbox module called Modal Entity Forms https://drupal.org/sandbox/andreymaximov/2058521

It depends on the Modal Forms module and will work in the same way, but for entity forms. I have tested the module and it works fine for now, although I want to submit 1 or 2 patches to extend it's functionality.

EDIT:
There is now a new module called Modal operations: https://www.drupal.org/project/modal
It's currently dev only (still better than sandbox) and so far it seems to work fine.


how to have conditional required fields through hook_form_alter? Here is basically what I'm trying to do.
If the draft field is present I would like to make the name field not required.

if($form_state['values']['field_draft']['und'][0]['value']){
  $form['field_name']['und']['#required'] = FALSE; }

Is this even possible? I tried after_build but it doesn't work.  If not, is there a better way to add draft functionality through hook_form_alter.

Thanks!

In Drupal 7, I would use the following code.

/*
 * Implements hook_form_alter().
 */
function test_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'your_form_id':
      $lang = $form['name_field']['#language'];//get field language
      if(isset($form_state['values']['field_draft'][$lang][0]['value'])){
        $form['name_field'][$lang][0]['value']['#required'] = FALSE;
      }
      break;
  }
}

Note: Never use und try to get the language for multilingual sites. If site is not multilingual, then best to use the constant LANGUAGE_NONE and not the string 'und'.


Why doesn't the "Edit" option always appear? I have a site with several custom entities. For one of the entity types, most objects are fully functional, viewable, usable, but on the entity list page do not offer the Edit option.  As my admin user, user 1, I can edit them using a custom form, but not from the default entity_form.

My EntityAccessControlHandler.php starts with:

$roles = $account->getRoles();
if (in_array('administrator', $roles)) {
  return AccessResult::allowed();
}

Why does the Edit option get suppressed?  I cannot find corrupted data in these nodes.

At this point, I have a workaround, using a custom form, but am trying to understand the depths of drupal at work here :) !

The user looking at the page the screenshot was taken on doesn't have the required level of access/permissions to edit those nodes.

There are many different ways that access/permissions can be configured to a single node, so you'll need to do some digging in your installation to find out whether it's simple core permissions, a contributed module, or a custom module that's causing the problem.


How to stop text-boxes in my custom block trailing past the block? I am creating a module with a custom block.  Even through googling, I still could not find an answer to my question "how do you theme the elements in a form?"  I think it is the fact that I don't completely understand the array elements that need to be set on each textbox.

Image of my problem: https://www.evernote.com/shard/s188/sh/3bf8cc91-5341-4c55-91ca-41e0ddbd1922/feb9698ff407e60a064f92421510059d

While creating this form in your custom module you set DIV class to form items which is textfield in your casy. All you will have to do is use #prefix & #sufix
You will start your DIV class from #prefix before #type of form items & close the DIV at #sufix.

Here is the example

$form['first_name'] = array(
  '#prefix' => '
',
  '#title' => t('First Name'),
   '#type' => 'textfield',
  '#suffix' => '
',
  '#maxlength' => 128,
  '#required' => TRUE,
);

Open the CSS file or create your own at your theme folder, but if you create your own then you will have to declare it in theme.info file.

Write CSS for the class demo-form which you have applied to the form element & resize it as your wish. If you have created your own CSS file then don't forget to clear your cache.


Add field 'link' in a block form? I would like to had a field link in a custom block. Here is my code to do that :

public function blockForm($form, FormStateInterface $form_state)
{

$form['key_1'] = [
    '#title' => $this->t('Key 1 label'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#required' => false,
];

$form['key_2'] = [
    '#title' => $this->t('key 2 link'),
    '#type' => 'link',
];

return $form;

}
Now, when I go in admin/structure/block/manage/myblock, I can see my key 1 field. The key 2 is not render. If I change the type for any other (textfield, textarea, file_managed) my field is properly render. The default link module is enabled.

Is the link field type only usable in node form ? I can understand why.

You should add the field from the Block Type interface. Either add to the block type that comes with core or create a new one and add your fields.

Also, no, Drupal Fields and Form API elements are two different constructs. That is why 'link' does nothing. It would simply be:

$form['key_2'] = [
    '#title' => $this->t('key 2 link'),
    '#type' => 'url',
];

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Url.php/class/Url/8.2.x

But you're creating more work that necessary.

In this context (a form) link pertains to a RenderElement and not a FormElement like url is.


Removed default login by mistake and logged out. Can't login I made the mistake of removing the user login block through the web interface, and logged out.

Now, I don't have the login interface anymore. Does anyone know how to solve this or is re-installing the only solution?

Furthermore, when I access example.com/user, the log-in form is shown, but it doesn't accept my credentials anymore.

I think I have found the "issue": The login page on mysite/user is the default login page for mysite; however, the default login block that is displayed on the front page is the login for the Drupal 7 web interface. These two are completely separate, that is why my credentials weren't working on mysite/user.

So in conclusion, if you removed the default login block and logged out of the drupal 7 web interface, then you are in troubles.

Please correct me if I'm wrong.

Jimajamma's answer is correct, but the real question here is: How do I hack a new password for user 1, given that I lost/corrupted/forgot my old one?

If you haven't turned off user registrations, create a new user. Now you have a password hash in your database for a known password. You could come up with some SQL to move this hash to user 1's password column, couldn't you? :-)

Then log in, change the password if you need to, delete the user you created, etc. And write it all down. :-)


how to add #states property to a field element in drupal 7? I wanted to add #states property to a select list field in cck input form created by content type. I ve tried the following code but the states property is not set to the field. Can anyone suggest on how to do it.

$form['field_ctype']['und']['#ajax']=array('callback' =>'_ajax_menu_check_boxes',
                                              'wrapper' =>'edit-field-sub-menu',
                                            'effect' => 'fade',
                                            'event' => 'change',
                                            );
$form['field_sub_menu']['und']['#states']=array(
                                  'visible' => array(
                                 ':input[name="field_ctype"]' => array('value' => '2')));

could anyone suggest me where I am going wrong. Is it possible to add ajax property ans states property to a same field?

Note : The Ajax property for the field_ctype works fine. Only the states property is not working.

Fields always have have nested names like field_something[und][value] or something like that. I guess your query (:input[name="field_ctype"]) is wrong.

I find the easiest way to get it right is using the Firebug/Developer tools Console. Play around with jQuery(':input[...]') until it matches what you're expecting. Also check the name of the form element.


How do I add jQuery Mobile.js? I'm attempting to add jQuery Mobile.js to handle the vclick event.

What would be the easiest way to add this functionality for an administrator that is new to jQuery?

There are jQuery Mobile module and Mobile jQuery Theme available. Looks like exactly what you wanted.

  The Mobile jQuery Theme is a powerful theme built on the jQuery Mobile platform. The theme adapts some of Drupal's base output to work with the highly themable designs built into the framework.

  This is an enhancement module for the Mobile jQuery Theme. You can also hook into the module with you own theme if desired.

So you have the module to provide functionality you need, and theme you can use by creating subtheme, or as a reference.


Add custom image styles to media browser display options I'm using the Media module in a project.

I've defined several custom image styles and would like to add them to the list of display options in the media browser. However, I can't find a way to do so.

Reading through issues similar to mine, I found this thread which suggested using hook_styles_default_presets() to render the options. But even with clearing caches, I'm unable to get my custom image styles to display as formatting options.

This tutorial ended up answering my question:
http://figure-w.co.uk/drupal-how-do-you-make-a-new-image-style-appear-in-the-media-browser/

Install the Entity View Mode module
Add new view modes
Configure display settings for view modes


How can I watch videos of the presentations from DrupalCon Sydney for free? I live too far away from Australia so I was unable to attend DrupalCon Sydney.  Is there any way to watch the videos online?  I tried looking on Blip.TV (where the videos for other DrupalCons are) but I couldn't find them.

For whatever reason, the DrupalCon Sydney videos are on YouTube, not Blip.TV.  The link includes instructions for downloading the videos from YouTube, but if you want them all, it's probably easier to use the torrent.


Get cart items and check for product of type X How do I?:

Get the current cart in commerce
For each item in the cart, check its product type?

I want to do the following:

foreach($cart_items as $item){
  if($item[product_type]=='X'){
    //perform a task
  }
}

I want to use this in the module code for a custom checkout pane.

Well this seems to work!

global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);

foreach ($wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $type = $line_item_wrapper->commerce_product->value()->type;
  if($type=='X'){
    //perform a task
  }
}


Picking image from server: FileField_Sources not working I currently have some nodes that use images.
Problem is: every time I want to choose an image, I have to upload it again.
It would be much better if I could just use a path picker, which could show which images are already uploaded.

This way I could upload the images through FTP and would make me able to give the authors only the rights to choose an already existing image, to be safe with author rights of the pictures.

I found that FileField_Sources can give the file picker, yet still have the upload function as well, ok fair enough, it's just a matter of telling the authors not to use the upload function.

Problem is, it doesn't work.

I installed the following modules:

FileField Sources
IMCE
IMCE for FileField

However, my original file upload is still unchanged

And I also don't have any new options to choose from in my content types manage fields part.

PS: Yes I activated all the modules in the modules page.

PS2: I also tried to use imagepicker as a module, but this adds a picture in the body. This is NOT what I want, I need the image to come into an image field.

A secondary question as well:
I want to put the copyights of the pictures on the site as well: preferably a bar coming over the bottom of the picture when you hover it, but a text below is also good enough.
If anyone knows a module for this or anything like that, it would very much be appreciated. If not I will just add an extra text field "copyrights" that I will just show below the pictures.

I just found the answer myself.

If anyone else would come into the need for something like this:

Download the 3 modules that I had typed in my question
Go to the Manage fields of your content type & click edit next to the Field
Scroll down and click Allow users to select files from IMCE File Browser for this field.

I forgot 2 & 3 :)

I do have to say that it's not 100% what I wanted, as I have different image fields in different nodes, and it only finds the image fields of the nodes that it's in. But I guess I should have used the references instead to make that work...

If anyone still has an answer for my secondary question, it would be much appreciated though, but I'll try to fix that myself tomorrow.


How can I more efficiently save nodes programatically with my custom module without cron? I have a scraper I created that aggregates data found on various sites, feeds, and databases. So that I don't hammer the servers to death that I am connecting to I have it set to sleep 5 seconds between requests.  When it finds what I need it saves it as a new node.  I have program set to fire on a cron run using hook_cron().

It's works fine but now I have added significantly to the sources I am searching through. The problem is this process could days, especially doing it in series. I have even had the case be that I get an error that cron tried to run while cron was already running.

How can I make this process go more efficiently? More quickly? And not depend on cron? Before I wrote a module for this I simply created several scripts - one script for each source -  and I fired them off simultaneously in terminal windows.

How can I do this with my module? I know I could run php's exec() function. In fact this is the commanad was calling with it when I was doing it manually:

php myscripts/search1.php < /dev/null &
php myscripts/search2.php < /dev/null &

When I try this in the module I get bootstrap errors.

When I wrote the module my individual scripts simply became functions in the module. I'm happy to go back to firing off the scripts simultaneously if someone can help me understand how to do that correctly in the module. Or, if you have another suggestion on how to do this quickly and efficiently, I'm all ears.  Realistically, I need to process a couple million items of content a week.

To fix the bootstrap issue you need to change the CWD (Current Working Directory) to where index.php is located. So in your case you are one directory deep so adding this to the top of your scripts inside of "myscripts" should make them work

// Change the directory to the Drupal root.
chdir('..');

If you were 2 directories deep the code would look like this chdir('../..');. If the errors had to do with php notices/warnings and things of that nature I would look at scripts/drupal.sh (checkout the "define default settings" section) or running your commands/functions with Drush.

There are a couple of options to help with dealing with millions of items of content per week. My recommendation is the HTTP Parallel Request & Threading Library. It will help with downloading things in parallel and doing things in background processes. As an example Link Checker recently integrated with it http://drupal.org/node/380052. With HTTPRL, Link Checker runs _linkchecker_check_links in a new process independent of cron, issue parallel http requests, and runs a callback inside of the event loop allowing work to be done locally while we wait for things to download.

The other options (That I know of) for dealing with LOTS of items are Elysia Cron and Background Process. The stock Batch API will be too slow if your looking to do millions of things per week (there are only 604,800 seconds in a week).


Pay to flag a node with drupal commerce Please help achieve the folowing:
I have a content type "proposal" with a field "prépayment_amount". I want the user who try to flag this node to pay the amount indicated in the field "prepayment_amount" and when the payment is successful, I want to notify this to the user who created this node, if not the flag is cancelled.

At least a partial answer could be to use Commerce in order to pay for access to a node. A user who clicks the link will be sent to the pay page, and upon completion of payment, the user will be assigned the role which can "flag" that proposal.

I'm not sure this would end up using the flag module, but you could theme it to look flag-ish.


How to implement custom Checkboxes in Checkout How can I implement custom checkboxes to drupal commerce checkout?

Those information I want to have attached to the order.

I have checked extra panes, but I haven´t found a way how to include those checkboxes.

Check out one of the following modules:

Commerce Checkout Field Group:

  Commerce Checkout Field Group turns Commerce order field groups into checkout panes.
  This allows to add custom fields to the checkout pages.

Commerce Fieldgroup Panes:

  This module creates for each field group of the order entity a new checkout pane. These panes can be activated or deactivated as usual.
  This enables an easy way to collect information in the checkout process. For example customer comments, feedback about where the customer founds the shop or any other fieldable information.


Drupal 7: How to use CKeditor with Rules email I'm trying to do the following to allow the CKeditor to be used with a rules-base email:

function mymodule_form_rules_ui_edit_element_alter(&$form, $form_state, $form_id) {
  $form['parameter']['message']['settings']['message']['#type'] = 'text_format';
  $form['parameter']['message']['settings']['message']['#format'] = 'full_html';
}

However, I receive the following warning among others:

Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain()

And the email I receive contains "Array" as the body. Seems like the issue is outstanding here: http://drupal.org/node/1031160

Is there a way to convert the output of CKeditor into a string?

Right now, I'm kind of missing the days where you just told CKeditor where not to show up.

I know this is an old issue but i had the same problem and could not find any answer so i figured it out myself.I thought i will put my findings here maybe it will help others.

Most important is that you should use text_formatted not text_format otherwise rules cannot render the field correct. Second is that you should use a different hook "mymodule_rules_action_info_alter" to change the type of the field. See in the example code how i changed the html body field for the mime mail rule "html email"

function mymodule_rules_action_info_alter(&$actions) {
  $actions['mimemail']['parameter']['body']['type'] = 'text_formatted';
  $actions['mimemail_to_users_of_role']['parameter']['body']['type'] = 'text_formatted';
}


How to add to 'Secondary Local Tasks' on Order page Can someone tell me how I can add another item on the Orders page to the existing 'Secondary Local Tasks' which is currently two buttons :- 'Apply Pricing Rules' and 'Simulate Checkout Completion'.

I am overriding page--admin--commerce--orders.tpl.php and would like to add a button to the $secondary_local_tasks variable but can't find where it's set. It's not a menu and isn't in template.php. Any ideas?

Just emulate what you see in the other modules:

  if (module_exists('commerce_order_ui')) {
    $items['admin/commerce/orders/%commerce_order/edit/refresh'] = array(
      'title' => 'Apply pricing rules',
      'description' => 'Executes the cart order refresh used to apply all current pricing rules on the front end.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('commerce_cart_order_refresh_form', 3),
      'access callback' => 'commerce_cart_order_refresh_form_access',
      'access arguments' => array(3),
      'type' => MENU_LOCAL_ACTION,
      'file' => 'includes/commerce_cart.admin.inc',
    );
  }

The important thing is the type and the path.


How to sort a view so that, say, all the nodes with stock=0 come last, and not sort by stock? I want to sort an output of a view so that the elements with a filed value of "0" be at the end of the list, but all the others are to be treated equally. In fact, it's an Drupal Commerce site, and I want all products with stock >0 to appear first in the lists, regardless of the stock quantity, so that the unavailable stuff get at the end, but still be in the view (after that, I sort alphabeitcally).
Any ideas how to do that?
That means making the output of a boolean forumla stock=0 the sorting criterion

You could do this if you use something like the Views php module, because that will allow you to use php code to sort by.  I know that module is currently looking for additional maintainers, I just can't think of an alternative.

Once you've enabled it, and added a php field to sort by, I'd have it return something like:

min([commerce_stock], 1);  // replace [commerce_stock] with whatever your available stock variable is.

What that code will do is return 1 (the minimum) if you have any stock more than 1, but it will return 0 if the product is all out.

So it will only return 1 (there are items) or 0 (there are none), which is exactly what you want.  Next, you can add a sort by name or whatever you want to sort these two groups further.

Let us know if it works.  I was having a bit of problems getting this rolling, since my stock variable is just returning my product ID, and I'm not sure if I'm just running slightly out-of-date modules or what.  So let us know if a similar approach works when you try it!!


Image field with url I'm searching for a image field in Drupal 8 with support to add images using url input. So when users has an image on his disk he can upload it and if the user has a image somewhere online he can link to it.

Does someone know a module that add this functionality to the image field?

Found a module that just did the job that I wanted.

The module is called FileField Sources


What are the implications of duplicate content issues with Drupal comments? Say we have a node called node/123 with comments enabled. When comments are made, additional URLs are generated /comment/1, /comment/2 ... and /comment/reply/2/1 etc. Unfortunately, these new URLs are a page that contains a full copy of the content in the original page /node/123 or the comment in reply. Core's robots.txt only has Disallow: /comment/reply/

Would there be any implications to adding the following to the robots.txt file? Would this be recommended (or even post a core issue pointing this problem out?)

# Paths (clean URLs)
Disallow: /comment/
Disallow: /comment*/
Disallow: /comment/reply/
Disallow: /comment/reply*/
...
# Paths (no clean URLs)
Disallow: /?q=comment/
Disallow: /?q=comment*/
Disallow: /?q=comment/reply/
Disallow: /?q=comment/reply*/

After investigating, I don't think there's an SEO problem here. It's an annoyance for sure but it's not a problem and here's why:

As per Google's recommendations here http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html on canonical URLs and duplicate content, you will not have any problems if you have duplicate content only if you properly specify your canonical URLs. Also, Google (and most probably all other search engines) will only display the canonical URL in search results and not the other URLs.

In Drupal's case, the canonical URLs are properly set. For example, I have created a test article (node/2) and added comments and replies to it and got the following pages:

/node/2
/comment/2
/comment/3

After inspecting their generated source code, they all have the same <link rel="canonical" href="/node/2" /> in their source code properly created. So basically only the main article page will display in the search results.

Now, whether to modify core to only generate a single page or to have the robots.txt file patched as you specified is beyond me. I'm sure there will be lots of considerations and special cases to consider before implementing any of the above and since there really isn't a problem maybe it's best to keep things as is.

Cheers!

Note: I'm using Drupal 7.17 (latest version as of today).


Contextual Filter tied to 2 relations? I've currently got a view on a Node type (Prospects) where part of the filtering is a Contextual filter filtering a 'Sales Region' taxonomy field against a Sales Regions taxonomy field in the User. The idea is that, given a path of, e.g., /user/4/prospects, the view should only show Prospects whose (single) Sales Region term matches one of those in the Sales Regions terms for user 4. This is actually currently working quite nicely.

The problem comes in that we have just added another pair of taxonomy fields to the Prospect and User - a Company field in each. The User has one Company term, and the Prospect can have multiple. The idea is to additionally limit the Prospects shown to those who have a Company Term that matches the selected user's Company Term. The issue (which I realized when I tried to modify the view to handle this) is that I essentially need to tie the one Contextual Field (a UID) to two different Relations - one for the user's Sales Region field, and one for the Company field, but the Contextual Field UI only appears to allow tying it to one Relation. Is there actually a way to do this, or am I going to have to do something like write a custom filter to handle the additional Company filter?

A colleague and I got this figured out after I posted the question.

To clarify the original question: the situation is, you've got a view with a path with one argument (e.g. user/%/prospects, where the argument is expected to be a uid), but you need to use that argument in two different contextual filters - in my case, two different taxonomy comparisons between the selected user and the content I've viewing.  The problem is, a contextual filter only lets you reference one relation.

The solution is to enter both contextual filters, but in the second one, in the "WHEN THE FILTER VALUE IS NOT IN THE URL" section, choose 'Provide default value', and in the type, choose (in this particular case) "User ID from URL".  Other 'from URL' types are available.  This allows you to 'share' one argument with two different contextual filters.


Entity Metadata Wrapper ->set saving data in incorrect language I'm using entity_metadata_wrapper to programatically create some nodes. I noticed that some of the fields weren't showing in the node/edit form after doing this, even though they are shown on the frontend. After lots of digging I found in the database that the field data is being saved with 'und' instead of my chosen language ('en'). What is the way to fix this?

The field 'introduction' is definitely translatable before anyone asks (otherwise it would show in the backend just fine).

$entity = entity_create('node', array(
    'type' => 'my_bundle',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
    'language' => 'en'
  ));

$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->language('en'); // Thought this would do it, but no dice
$ewrapper->title->set('This works fine');
$ewrapper->field_introduction->set('This doesnt');
$ewrapper->save();

Test the following described here:

$ewrapper = entity_metadata_wrapper('node', $entity, [
  'langcode' => 'en',
]);

instead of

$ewrapper->language('en');


How can we render graphviz diagrams in drupal pages? I'd like to be able to allow users to insert Graphviz images in Drupal comments and Wiki pages.

What's involved it doing this?

The benefit is that users could enter something like the following snippet to see a graph.

[code lang=graphviz]
  digraph G {
    a  [label="Hello", shape="square", URL="http://en.wikipedia.org/wiki/graphviz"]
    F1 -> a[label=".63"]
  }
[/code]

There's the Graphviz Filter module, which provides an input filter that will convert Graphviz DOT syntax to the required diagrams. You can find more information in the Drupal documentation on graphing modules.


Drupal Search Programmatically I need to implement my own search method in order to find nodes with some keywords in their title or body and with a specific type, but I don't know how to do this.

I tried with do_search() and node_search() methods but I don't get results.

You need to use search_data().

  Perform a standard search on the given keys, and return the formatted results.


How can I export a group of settings in Drupal 8 Drupal 8 has this new configuration management tool at /admin/config/development/configuration. I have an experimental site running Drupal 8 beta14, and I want to import a few settings into my new beta15 site. I don't want to copy everything, I experimented with various things on the old site and only need a few things on the new one.

What I want to copy are content types, the fields in those content types as well as image styles. But looking at the export tool, it seems I can only export a single item at a time.

Is there a way to export all items of a specific group at once, e.g. all content types or all image styles? And for content types, is there a way to export all the fields as well together with the content type?

There are two different things you can do.

You can, as you found, export and import single objects.

Or, you can do a config sync. Which means everything and is usually used to import configuration changes from staging to production or similar.

So you can do a full config export, then all the files will be in your staging folder (not the same as a staging environment) and import them in a different site. Note that there are some limitations, for example, you always need to do a full import (so export the existing config of a site, update it with some changes, then import it again) and the sync only works if the UUID in system.site matches, as it is not supported to import from a separate installation. (But you can import a group of files that don't exist yet.. careful with the UUID's, as the same object with a different UUID is treated as a delete + create, not update).

So you need to pick the files you want to re-use and put them either into an existing export from the target site or put them in a config/install folder of a module, then it will be imported when that module is installed (and only then, there are no automated updates).

You can also look at the 8.x version of the Features project, which basically offers a UI to pick a number of configuration files, similar to what you might know from D7.


Drupal filters are not cacheable I have a Drupal 7 site with many custom filters. Everything works correctly, but not quick.
It looks as though the filter cache system does not work properly because the cache_filter table is always empty.
There is the issues in d.o. but it isn't replied.

The cache is used only when the input format is enabled to use it; this means that none of the input filters that are used by the input format disable the cache.

The code of check_markup(), which the function that is called when an input format needs to be applied to a text, contain the following code.

$cache = $cache && !empty($format->cache);
$cache_id = '';
if ($cache) {
  $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
  if ($cached = cache_get($cache_id, 'cache_filter')) {
    return $cached->data;
  }
}

$cache is a parameter passed to the function, and $format is the variable containing the value returned by filter_format_load(); if $format->cache is FALSE, the filter cache will not be used.

In the case of the body content of a node, the function that is used to sanitize the body content (and the content of other fields) is _text_sanitize(), which invokes check_markup() without to use the fourth parameter ($cache), which by default is FALSE. This means that, whatever the filter is set to use the cache or not, the cache will not be used.

function _text_sanitize($instance, $langcode, $item, $column) {
  // If the value uses a cacheable text format, text_field_load() precomputes
  // the sanitized string.
  if (isset($item["safe_$column"])) {
    return $item["safe_$column"];
  }
  return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);
}

This is different from what done by user_comment_view() (the implementation of hook_comment_view() that is used to filter out the signature of the user who wrote the comment), which passes the fourth parameter to check_markup(), setting it to TRUE.

function user_comment_view($comment) {
  if (variable_get('user_signatures', 0) && !empty($comment->signature)) {
    // @todo This alters and replaces the original object value, so a
    //   hypothetical process of loading, viewing, and saving will hijack the
    //   stored data. Consider renaming to $comment->signature_safe or similar
    //   here and elsewhere in Drupal 8.
    $comment->signature = check_markup($comment->signature, $comment->signature_format, '', TRUE);
  }
  else {
    $comment->signature = '';
  }
}