'Add More' Taxonomy Term Widget I'm trying to create a field widget that is similar to the normal term reference widget with one key difference. The user needs to be able to add multiple new taxonomy terms at the same time, this may demonstrate it better:

I've got to a point where the functionality is similar to what the taxonomy/options/list modules provide (i.e. the checkboxes/radios are shown, saving etc.)

Here's important bit of the code I'm using in hook_field_widget_form():

 $element += array(
    '#type' => $multiple ? 'checkboxes' : 'radios',
    '#default_value' => $multiple ? $default_value : reset($default_value),
    '#options' => $options,
    '#value_key' => $value_key,
    '#element_validate' => array('options_field_widget_validate'),
    '#properties' => $properties,
  );

What's throwing me here is that $element isn't your usual form array so I'm not sure how to add the textfield and and button - especially as their values aren't meant to be saved. What's the best way to add these fields to my widget?

As for adding the Javascript needed, am I right in thinking I should use #ajax that calls a function that rebuilds the #options for the checkboxes?

Thanks in advance!

EDIT -
My initial question was quite vague, here's some more details on what I've tried:

  $element += array(
    '#type' => 'fieldset',
    '#delta' => $delta,
  );

  $element['value'] = array(
    '#type' => $multiple ? 'checkboxes' : 'radios',
    '#default_value' => $multiple ? $default_value : reset($default_value),
    '#options' => $options,
    '#value_key' => $value_key,
    '#element_validate' => array('options_field_widget_validate'),
    '#properties' => $properties,
  );

  $element['text'] = array(
    '#type' => 'textfield',
    '#title' => t('Add another'),
    '#weight' => 5,
  );

This a is an amalgamation of various examples I've seen, and seems to get me closer. The problem is when I submit the entity form I get the following error:

  Notice: Undefined index: tid in taxonomy_field_is_empty() (line 1402 of modules\taxonomy\taxonomy.module).

I've taken a closer look at this function and it's expecting $item to have the structure $item = array('tid', 2). When using the above code there seems to be a delta coming from somewhere and the structure of $item ends up being $item = array(0, array('tid', 2). I can't work out where '0' is coming from?

ANOTHER EDIT

I've been able to fix the above error with the following code by altering $element like so:

$element += array(
    '#type' => 'fieldset',
    '#process' => array('taxonomy_free_entry_ignore_parent'),
);

and adding the function:

function taxonomy_free_entry_ignore_parent(&$form, &$form_state, $complete) {
  array_pop($form['#parents']);
  return $form;
}

When I save the entity I'm getting a message telling me it's been saved. When I check the table for the field, it isn't being saved. What am I doing wrong?

I'm sure you could do this in hook_field_widget_form() (which I'm guessing is where your current code is) by just adding a child element to your existing element, e.g.

$element['text'] = array(
  '#type' => 'textfield',
  '#title' => 'Title',
  // etc...
);

If that doesn't work I know it will definitely work if you use hook_field_widget_form_alter().

For example, the following is a small function which enables the alt field for an Image field type using the Media Selector widget (for some reason it's not enabled by default):

function media_image_attributes_field_widget_form_alter(&$element, &$form_state, &$context) {
  if ($context['field']['type'] == 'image') {
    $element['alt'] = array(
      '#type' => 'textfield',
      '#title' => 'Image Description',
      '#weight' => 10000,
      '#default_value' => count($element['#default_value']) ? $element['#default_value']['alt'] : ''
    );
  }
}

As far as the ajax functionality goes, I think you're definitely going along the right lines. I think the Field Example module in Examples has some sample code which might help.


How to duplicate nodes programmatically? I want to create duplicate nodes of a content type programmatically.

Is there any way to do this?

Note: I don't want to use any module to do this.

You can read the values from the original node in an array and create a new node with the data:

$storage = \Drupal::entityTypeManager()->getStorage('node');

$node = $storage->load($nid);

$original_values = $node->toArray();

// assign content type as string, the array causes an error when creating a new node
$original_values['type'] = $node->bundle();

// change title
$original_values['title'] = $node->label() . ' (cloned)';

// remove nid and uuid, the cloned node is assigned new ones when saved
unset($original_values['nid']);
unset($original_values['uuid']);

// remove revision data, the latest revision becomes the only one in the new node
unset($original_values['vid']);
unset($original_values['revision_translation_affected']);
unset($original_values['revision_uid']);
unset($original_values['revision_log']);
unset($original_values['revision_timestamp']);

$node_cloned = $storage->create($original_values);
$node_cloned->save();


In what cases should I personally sanitize input & output when using the Database Abstraction Layer I'm trying to get a clearer sense of where security vulnerabilities on my site may lie. At no point in my code do I ever query the MySQL database directly; I always use the Database Abstraction Layer (db_query(), etc). Under what circumstances may this not provide sufficient protection against SQL injection attacks?

I am using Drupal 7.

If you use db_query() all the time without directly inserting variables, but using the arguments.

For example this is right: db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid)); it's perfect, you don't have to care about something else (except critical bug directly in Drupal).

On the other hand, if you do it directly: db_query("SELECT * FROM {node} WHERE nid = $nid"); you expose your site to SQL Injection.

From my own experience, Drupal alone (without other modules) is very secure and many times we tried to hack it with professionals.


What are my options to rename a (huge) cache_form table which takes way to long? I inherited a website that has cache_form more than 33Gb.

I've followed the following steps:

CREATE TABLE new_cache_form LIKE cache_form;

RENAME TABLE cache_form TO cache_form_backup;

And in other session:

RENAME TABLE new_cache_form TO cache_form;

Query is taking long long time and site is not responding.

What could the solutions be?

"Waiting for table metadata lock" will happen with a TRUNCATE or a RENAME and once this query is slated to run all other requests behind it will be stalled. There is no way to tell if a query will have a metadata lock unless you attempt to run it. So if the query does indeed cause a metadata lock you'll want to kill that query and use DELETE FROM instead as this is a DML statement where as TRUNCATE or RENAME are DDL statements.

I created a module that handles the above logic: APDQC

If you want to investigate this you self slides 104 - 113 of my 2015 DIY Drupal 7 Performance talk is a good start. How to create a stored procedure in order to auto kill stalled queries: http://mysqlblog.fivefarmers.com/2012/08/28/identifying-and-killing-blocking-transactions-in-innodb/


Adding checkbox in admin table display I'm trying to add a checkbox column in the admin table part of my module.
The idea is to add checkboxes at the beginning of each row, like in the normal admin content management form.

My table is build in a form function with the following code :

function myform_admin_form($form, &$form_state) {

$query = db_select('form_xml', 'f');
$query->join('form_xml_status', 's', 's.id = f.id');
$query->join('users', 'u', 'u.uid = f.uid');
$result = $query
        ->condition('s.status', 'todo', '=')
        ->fields('f')
        ->fields('u', array('name'))
        ->execute()
        ->fetchAll();

$header = array(
array('data' => t('ID')),
array('data' => t('Name')),
array('data' => t('User')),
);

foreach($result as $key){
$rows[] = array(
array('data' => t($key->id)),
array('data' => t($key->name)),
array('data' => t($key->user))
);
}

$form['table'] = array(
'#type' => 'tableselect',
'#header' => $header,
);

$output = theme('table', array('header' => $header, 'rows' => $rows));
$output .= $form;

return $output;

}

My tableselect doesn't display at all, but "Array" appears at the bottom of the table. Is it possible to add checkboxes in a table like this ?

Although there's actually no question, I've noted the last part of your code should look like:

<?php

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $rows,
);

return $form;


Mass update of taxonomy term references I need to update the taxonomy field on nodes with the term from a new vocabulary. I could accomplish this easily in Drupal 6, and haven't been able to find a method in Drupal 7. I am looking for a UI based solution like VBO.

There is no native support for this in VBO, due to the way that Taxonomy has now been moved into the fields API. There is an outstanding task that is being worked on to bring Taxonomy actions back into VBO.

In the meantime, you can try this patch against VBO 7.x-3.0-beta2, kindly posted by erik2e.


Block render array image_formatter How can I pass a renderable array from within a block?

$block['content'] = array(
  '#theme' => 'image_formatter',
  '#variables' => array('path' => 'hello.png'),
);

How do I pass the variables that image_formatter needs when I use a renderable array from within a block?

$image = array(
  '#theme' => 'image_formatter',
  '#image_style' => 'thumbnail',
  '#item' => array(
    'uri' => $user->picture->uri,
    'alt' => '',
    'title' => '',
  ),
);
$block['image'] = $image;


How to check if an article is referenced from a collection? I have a collection content type which is just a list of EntityReferences to articles.

When I am loading an article, how can I use the Entity API to check if it belongs to one or more collections?

Previously I would query the DB, but I wonder if there is a more idiomatic way?

To load all collection id's, which have a reference to $article_id:

$collection_ids = \Drupal::entityQuery('node')
  ->condition('type', 'collection')
  ->condition('field_article_ref', $article_id)
  ->execute();
if ( count($collection_ids) > 0 ) {
  echo "the article $article_id is referenced in one or more collections";
}


How to have multiple columns for a single field in view I created a content type with image field which accepts unlimited values. Now, I have 25 images uploaded to the field. I created a page view. I selected the image field. For the view settings, I selected Grid format > Number of column: 2.

When I go to views page, I expected to see 2 columns on the page views but I did not. How can I make sure I can see only 2 columns of images in the views page when I set number of columns equal 2 in Grid setting?

When you configure field in Views there is an option  Display all values in the same row  under Multiple field settings  uncheck that option. By doing this each image will display in separate column.


How to rollback jQuery Update module? I accidentally update jQuery version from 1.5.2 to 1.82 using Drupal's jQuery update module.  Is there any way to rollback the update and go back to my 1.5.2 version?

Changing the option exists only in the dev version. So I downloaded the dev version and set it to 1.5.2. However, now, I am getting this message:

  jQuery could not be replaced with an uncompressed version of 1.4.4, because jQuery 1.5.2 is running on the site.

Don't know what that means, because I am not trying to run 1.4.4.

Uninstall and then do a fresh start.

jQuery update won't break any of your existing code by uninstalling.


How to add a cron task I am new to drupal, now I have function get_node_from_rss() which the file is inside mysite\sites\all\modules\node\node_rss\node_from_rss.module the function will update node from the rss link every 1 hour. Now, I dun know how to make this function add to the cron task. Can I run it without using cron.php? I search in google, they something like simple change the function name like get_node_from_rss_cron(), I also putting some code like:

$interval = variable_get('get_node_from_rss_interval', 60 * 60);
if (time() >= variable_get('get_node_from_rss_next_execution', 0)) {
   watchdog('get_node_from_rss', 'get_node_from_rss ran');
   if (!empty($GLOBALS['wowfi_locamusic_addnode_show_status_message'])) {
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
    }
    variable_set('wowfi_locamusic_addnode_next_execution', time() + $interval);
  }

inside my code, but those still not working for me,
Any solution?

A hook implementation is simply a my_module_name_function implentation.
Your module's internal name is what you have used in the .module file's name.

So for in this case, it's node_from_rss (I'd recommend you to rename the folder name to node_from_rss as well so it reduces any confusion).

If you rename your cron function to comply with the above my_module_name_function pattern, function name has to be node_from_rss_cron

function node_from_rss_cron() {
 $interval = variable_get('get_node_from_rss_interval', 60 * 60);
 if (time() >= variable_get('get_node_from_rss_next_execution', 0)) {
   watchdog('get_node_from_rss', 'get_node_from_rss ran');
   if (!empty($GLOBALS['wowfi_locamusic_addnode_show_status_message'])) {
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
     drupal_set_message(t('wowfi_locamusic_addnode executed at %time', array('%time' => date_iso8601(time(0)))));
    }
    variable_set('wowfi_locamusic_addnode_next_execution', time() + $interval);
  }
}

Other than these changes, here are some of the Drupal best practices.

Drupal 7 has a REQUEST_TIME constant defined at the beginning of page processing. If this code is for D7, use it instead of time().

drupal_set_message() function sets a message to the screen. but cron functions will run without use interaction. You will not see this message unless you are running cron manually at admin/reports/status page.

Avoid placing folders such as 'node' inside sites/all/modules folder. Technically it's completely ok to do so. But I think it will confuse you and others in the long run. Usually we place modules like:

sites/all/modules/MY_MODULE/MY_MODULE.module


When directly loading a Commerce 2 Order Item, why is the entity cached for anonymous users? I'm using the following to load a Commerce 2 Order Item:

    $order_item = \Drupal\commerce_order\Entity\OrderItem::load($order_item_id);

If I empty the cart for an anonymous user (thereby removing the Order Item), using the above code still loads the item as if it still exists.

The caching issue does not exist when logged in.

Why is the Order Item caches when loaded directly like I'm doing above?

How can I load a refresh version?

The issue was due to the fact that the entity logic was running in a custom form and the form was caching the entity.

Simply setting:

   $form['#cache'] = ['max-age' => 0];

Resolved the issue.


How feature works with panels? I have created cusotm layout with panels on my dev and staging site. I added a class to panels region and exported using feature. Then I enabled it on stage site. But there was no changes on stage site. Is there anything more needed for panels update using features? Or have anyone a documentation on features with panels, panelizer and panopoly module?

I exported Panels: mylayout (Default Config)

I noticed that, any update from feature module works only if that was created using feature module.


Preventing Authors from entering pre-formatted text into filtered html field I have a form for my authors to use when entering records. The form has a 'filtered text' description field that also use WYSIWYG.

I'm noticing that some of my authors enter 'bad' text. What I mean is the text they are entering looks like it's been formatted with weird spans and divs from some other text editor (probably word), so that it breaks the formatting of the record when its published.

Anyone know of a way to auto-strip extraneous html when someone inputs a record, or is it just a matter of educating them?

They really don't know anything about HTML at all so a technical solution would be best sadly.

If you're using the Filtered HTML text format, it should be stripping out spans/divs that contain inline styling. You can double check this at the /admin/config/content/formats/filtered_html path. Make sure the limit HTML tags box is checked and the Allowed HTML tags don't contain any of the HTML elements you're trying to get rid of.

If you're using the CKEditor (I'm not sure of other editors combined with the WYSIWYG module), you have a few other options to scrub bad markup when it's pasted in. You can check this by editing your Filter HTML profile under /admin/config/content/wysiwyg.

One the toolbar options contains a Paste from Word button, that allows you to paste Word-copied markup into CKEditor. I tend to avoid this myself, but you might find it useful if your users work with many Word documents.

My prefered option is to use the paste plugin to strip out markup altogether; going this route allows you to restrict your toolbar to HTML elements that will render correctly in both the editor & your theme. You can find this option in paste plugin tab in your WYSIWYG profile page.


Webform, rename files to a constant name and bypass validation I have a webform where users can upload one pdf file. I'd like to have this pdf file always the same name foo.pdf.

To avoid conflicts I save each upload to a different directory with the pattern foo/[random:hash:md5].

When trying to save these settings I get the error message To create unique file names, use at least one token in the file name pattern. I understand that this error makes sense to avoid naming conflicts but the conflicts should be avoided with the custom directory.

Is there a way to bypass the validation check?

Edit: For clarification. I need to bypass the validation check in the settings page for the field of the file upload not the validation for the form submission itself

By looking at the source in /components/file.inc (in Webform module), you will see that the Webform declares a custom element validation callback that performs the check you want to avoid. In order to override this, you will have to hook into the settings form, and provide your own callback for this element.

Below is the code you would use to achieve that. Pay attention to the comments.

function YOUR_MODULE_form_webform_component_edit_form_alter(&$form, &$form_state) {
  // Override the element validation callback for renaming the file uploads.
  if (isset($form['extra']['rename'])) {
    // Loop through the validation callbacks and remove the one we want to
    // override. This way we will not affect any other module that alters this
    // part of the form.
    foreach ($form['extra']['rename']['#element_validate'] as $key => $validation_callback) {
      if ($validation_callback == '_webform_edit_file_rename_validate') {
        unset($form['extra']['rename']['#element_validate'][$key]);
      }
    }
    // Note: since the original validation callback provided in Webform module
    // only makes sure that the file names are unique, you don't need to provide
    // your own element validation callback. However, I would recommend doing so
    // just in case you have other webform nodes that will need this validation.
    //
    // Add our custom element validation callback.
    $form['extra']['rename']['#element_validate'][] = 'YOUR_MODULE_edit_file_rename_validate';
  }
}

function YOUR_MODULE_edit_file_rename_validate($element, &$form_state, $form) {
  // I recommend still limiting this only to specific nodes, content types, and
  // not disabling completely.
  if ($form['#node']->nid != YOUR_NODE_ID) {
    $rename = trim($form_state['values']['extra']['rename']);
    form_set_value($element, $rename, $form_state);
    if (strlen($rename) && !count(token_scan($rename))) {
      form_error($element, t('To create unique file names, use at least one token in the file name pattern.'));
    }
  }
}


Do not want  HTML tag when using footer region After running W3 Markup Validator on a site of mine, I received the following error:

Line 219, Column 57: element "footer" undefined
<footer id="footer" class="region region-footer">

Whether or not this is actually an issue, bad style, or what, I've decided that I don't want Drupal using the HTML footer tag. Is there a way that I can change this and have it just create yet another div?

did the validator know you where using an HTML5 site?
http://www.w3schools.com/tags/tag_footer.asp

... anyways you can always edit page.tpl.php or html.tpl.php for your theme to change global page markup like this to however you want.


How can i limit the drop down list of countries in exposed filter? I try to use the script https://drupal.org/node/1772498, but I don't get the right db_query for countries in the nodes. I change the script on these line:

$result = db_query("SELECT DISTINCT(l.country) FROM {location} l ORDER BY l.country ASC");

and get the error message:

Notice: Undefined offset: 1 in DatabaseStatementBase->fetchAllKeyed() (line 2180 of E:\xampp\htdocs\testsite\includes\database\database.inc).

It will be great, if somebody can help me!

fetchAllKeyed requires a 2-column resultset. You only have 1 column l.country in your resultset. I'm infering from your question here ...

Did you make a views exposed filter ?
Can you add a relationship to the view on the parent node to filter to the countries set on that node(s)?


Get paths of files attached to the node from field name How can I get the paths (URLs) of files attached to the node from field name in Drupal 8?

I tried using Drupal 7's node_load(), but that does not return paths of the files:

$node = \Drupal::routeMatch()->getParameter('node');
$node = node_load($node->id());
var_dump($node);

You can get it like this:

$file_uri = $node->field_machine_name->entity->getFileUri();

If your field allows for more than 1 value, then:

$file_uris = array();
foreach ($node->field_machine_name as $value) {
  if ($value->entity) {
    $file_uris[] = $value->entity->getFileUri();
  }
}


How to show the author of Blocked users's Content as anonymous in Drupal 7? I have a Content type Board. All authenticated users can add boards. when i displaying the Board's Nodes i am also showing the author name. All going good.
But when a user delete his account i set his status as blocked.
If a user has been blocked then i want to show Anonymous author on board's node created by that blocked user.
I searched here and there but could not find solution. Any Help please
Thanks in Advance.

You may use

function theme_username($variables)

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_username/7.x

$username = $variables['name'];

Check if user blocked

$variables['name'] = 'anonymous';


How to identify a paragraph? Is there a way to identify a paragraph in Drupal 8. Like is there a function to get the type as paragraph in code level?

I need to get it from a form alter function. My requirement is to get all the paragraphs in a form. Or identify the paragraph fields.

You probably should look at the paragraphs module code, it does a lot of this.

That said, the basic process would probably be:

Identify the form fields that are entity_reference_revision fields.
Check that the field is limited to paragraph types (can just check
1st one).
If it is an update form, get the referenced entities from the field.
You will then need some recursive code to walk the paragraph tree to
get sub paragraphs.

This will require using a lot of the field definition classes to get the information needed.


How to get form variables data into twig templates? I have a form like:

 public function buildForm(array $form, FormStateInterface $form_state, $short_title = '') {
$title = 'xyz';
}

In my .module file, I have a theme function:

function ip_mcq_theme() {
  return [
    'take_mcq_form' => [
      'render element' => 'form',
    ],
  ];
}

How to get form variables like $short_title and $title mentioned in form build function in my take-mcq-form.twig.html file?

Put the custom variable in a key with a '#', so that the formbuilder doesn't try to render this as a form element.

buildForm():

  $form['#myvars']['var1'] = 'xyz';

In twig you can access the variable in element:

form.html.twig:

  {{ element['#myvars'].var1 }}

If you set a template in #theme of the form build

buildForm():

  $form['#theme'] = 'take_mcq_form';

you get a second template inside of form.html.twig, where you can access the variable in form:

take_mcq_form.html.twig:

  {{ form['#myvars'].var1 }}


Customizing a View with Taxonomy, color coding and icons I have been searching for help with this and I am stumped.

I am trying to create an attractive, styled table with categories of Web Resources and associated icons for each category.

I currently have the following:

A Taxonomy vocabulary: technology categories (e.g. techA, techB, techC) with an icon image field
A Web Resources content type (title, link, description, tech category = taxonomy)
Block View of Taxonomy Terms in Table Format (built using these suggestions from Anoop Joseph (https://drupal.stackexchange.com/users/10405/anoop-joseph) How to list all taxonomy terms in a vocabulary followed by associated node titles in Views)

What I would like to do:

Show the Taxonomy icons next to the technology category names in the Views table
Style each Views generated table with a different css (e.g. border color, bg color)

But I can't find where I can create/generate specific CSS classes for each of the tables. They are all showing up in the output HTML as:

...

And I don't even know where to start to display the Taxonomy icons next to the Taxonomy.

Do I need to work in Templates? If so, how do I add the appropriate icon to the table captions without hardcoding (e.g. switch / case), because that won't be flexible in the long run. I want site maintainers (not me) to be able to simply add a new category to the Taxonomy and upload an icon to go with it and have it show up in the View as a header for that category.

Thanks to anyone who can help.

First, to have the associated icon show up with the taxonomy term, do the following:

add field: image field from taxonomy
add field: Global: custom text, set it to [name] [field_your_image_field]
exclude label from display
exclude these two fields from display
change your table grouping from taxonomy name to Custom text ( or whatever you named it )

To style the output, you'll use two settings:

under Format: table | settings, set the row class here

to style individual fields, click on the field in the fields list, click on style settings, and customize field HTML / create a CSS class

There are lots of options here for setting field and label classes, and html elements

Good luck


Is it possible to get original configuration when another Config Split is activated? (CONDITIONAL SPLIT is used) I have dev and prod environments.

I use payment getaway. There are different api keys for dev and prod envs, it's like test and live mode of the payment method.

There is active dev config split configuration which contains some config with test api keys (CONDITIONAL SPLIT).

So it means, there is also original config witch contains live api keys.

Is it possible to get programmatically both values (original and dev) for some specific configuration?

This is a follow-up to my comment on your question with some references:

When using Configuration Split to distinctively use a certain conditional configuration on your environments, then you won't be able to access both, your development and production values at the same time (without reading in these splitted configurations manually).

The reason is, that configuration split hooks into the import/export process of your configuration. Once you import your configuration, the values for the respective environment will replace your database-stored configuration.

If you need to access both values within the same environment, you should change from config split to configuration overrides.

By keeping the production API value database stored across all your environments (in your configuration files that apply to all environments) and having your test API value defined as override within your e.g. settings.local.php file, you'd be able to access both values using Config::get and Config::getOriginal within your dev/staging environments, while only the database stored value will be available in your production site.


Receive link from row in views-template file I changed a views-template and wanted to link all elements together. Is there a different way as getting the link via regular expressions?

Have you try the option in the field to "Reqrite the output" ?

First of all, you select "Exclude from display" in the fields you want to group together, then in the last field you rewrite its output using patterns. This allow you to put HTML or text before your fields for example something like this:

Address
City: [field_city_value]

Country: [field_country_value]

Then you also have the option to "Output this field as a link" which allows you to give your group of field a link. This option also provides a way to rewrite the link with patterns.


PHP Fatal error: Cannot call overloaded function for non-object in /var/www/html/includes/database/query.inc on line 331 We have a Drupal 7.12 Setup in production.

Recently we upgraded PHP to 5.4.10 and we are getting the following error,

  PHP Fatal error: Cannot call overloaded function for non-object in /var/www/html/includes/database/query.inc on line 331

What can be the possible reason for it and how do can we solve it?

If the above information is not good enough to know about the root cause,
how can some more data be logged about the error?

On the requirements page there is a "Version specific notes on PHP requirements" section that gives information on supported PHP versions.

Notice that it doesn't mention PHP 5.4 anywhere.
I take this to mean that Drupal 7 is not guaranteed to work with PHP 5.4.

In addition to this there is no hard requirement for any contributed modules to support PHP 5.4 yet.
Some modules will work and some will have problems.
Some modules have already had these problems fixed and I have seen in some cases, maintainers saying they will not support 5.4 if the fix causes problems for older versions, because php 5.2 & 5.3 are the main target versions of Drupal 7.

I would recommend if possible to not use PHP 5.4, and if you do you will quite probably be having to debug more of these issues as you encounter them.

Also, your version of drupal is 10 versions (more than a year) old. If you want to use the cutting edge version of PHP you have to also use the latest versions of all modules as this will give you the best chance of these kinds of issues having been fixed.

Not to mention that there have been some security fixes since 7.12 that you would benefit from having.

Is it an option for you to stay on PHP 5.3?


Is it possible to prevent a View from executing until the user has chosen filters? I have a rather complicated View (created with the Views module) with about a dozen filters on it, all exposed to the user. The View is very heavy on CPU, and I would like to prevent it from running until the user has applied his filter choices.

One suggestion for dealing with this is to make a filter "Required": then the exposed filter will be empty when the View is first run and as a result will force the user to apply filter values explicitly.

The problem is that the filters are almost all dropdown lists, so they get a value applied automatically and don't therefore stop the View from running. Does anyone know some other way to do this?

I'm assuming that for suggesting an answer to your "Does anyone know some other way to do this?", it's OK to also suggest another "module" (instead of just another "way") ...

The Forena module might possibly be a valid alternative for you to consider. For more info about this module, refer to either of these links:

its Community Documentation.
its Demo site, which includes Reporting Samples and Documentation about the module (also included in a site where the module gets installed).

In this specific case, you could consider transforming your "complicated View" into appropriate Forena data blocks (SQL queries) and custom reports (and/or charts ...). And for those reports to be generated (and the SQL queries to be executed), you could consider using the various Forena features related to "Report Parameters". A few more details about these Report Parameters:

refer to this (extremely basic) demo sample that uses such report parameter.
refer to this relevant part of the documentation (related to report parameters).


How to remove the Day field from a Date? I want to remove the day field from a Date dropdown of a webform. How to do that? I tried with hook_form_alter() without success. Any suggestions?
Thanks

There seems to be no coding-free way to achieve this but to create a separate Number-type field for year and month.


Sorting a view basing on the value of a boolean field I have a content type X. A view is used to display this content type (X), as a table. The content type has a field called "Preferred" which contains boolean values. I need to sort the table so that the "Preferred:true" items display at the top of the table.

How can I achieve it?

Add a new Sort Criteria sorter that sorts based on that field. Make sure it's at the top of your list of sort criteria.

If you don't want there to be a column for it in the table, click "exclude from display" in the field settings.


How do I get settings in admin/config/people/accounts/fields and admin/config/people/accounts/display into a Feature How I would get admin/config/people/accounts/fields and admin/config/people/accounts/display into a Feature. I have been looking everywhere...

For account fields, they will be listed under the 'fields' section just like any other. Just look for the fields that start with 'user-'.

For the view modes, I beleive you can export them to features by using the Dispaly suite module


How do you retrieve the node IDs of the nodes using a a taxonomy term? When you tag a content type with a taxonomy term, if you click on the term itself, Drupal will display a list of content tagged with that term. I have reviewed taxonomy_select_nodes(), but I wasn't able to get a working piece of code. I'm not sure this is the correct function to use when looking for the node IDs of the nodes tagged with a taxonomy term.

How do you retrieve the IDs of the nodes using a specific taxonomy term?

EntityFieldQuery to the rescue:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->fieldCondition('field_name_of_term_reference_field', 'tid', $term_id);

$result = $query->execute();
if ($result) {
  $nids = array_keys($result['node']);
}


Can I make search field with Views? I would simply like to create a search bar (a text field) that when filled out will return a list of a certain content type on a new page.

Right now with Views I have created a search bar (text field) as an exposed filter but it also shows all the content with it. What I want is to have the search bar but have the results content show in a new window when the search bar is submitted.

Can this be accomplished with Views?

At advanced, the column at the right, in the view config you can set the filters to apear as a block. You could place this at any random page and when submitting you will be send to the viewpage desiplaying the results from the filter.


Displaying taxonomy terms and its contents with views I am quite new to Drupal and I'm having troubles in some tasks.

I need to show food categories and food products as its contents. In order to do that,
To begin with, I created a content type with the field of taxonomy term reference for products and taxonomy vocabulary for categories.

Secondly, I added categories as taxonomy terms and products as content by choosing its related category. Everything is fine up to now.

For the categories page output, I created a view to show categories (taxonomy terms) and set details as below:

Fields
Taxonomy term: Name

Filter criteria
Taxonomy vocabulary: Machine name (= Food Categories)

path: /categories

This page help me to show categories.

For the other page that needs me show each product(content) for the selected category I created another view and set details as below:

Fields
Content: Food Category
Content: Title

Filter Criteria
Content: Type =(Food Product)

Contextual Fiter
Content: Food Category (filed_food_category)

Contextual filter settings are:

When the filter value IS in the URL or a default is provided
Option:   Override title is checked and value is %1

Specify validation criteria
Option: Validator is checked and set taxonomy terms where vocabuary is food categories
Filter value type set to Term name converted to term ID

Option: Transform dashes in URL to spaces in term name filter values is checked

path: /categories/%

This view is able to show me each content related category.
For example when I tried to type /categories/category-1
I can see output through this view properly.

And I needed category titles from the first taxonomy terms page redirect me second view which shows each product under the related category. To achieve this I set url each alias of taxonomy terms as categories/category-name and checked the option of the filed Taxonomy Term:Name as Link this field to its taxonomy term page.

But here is the problem. When I attempt to click link on each food category (taxonomy term) provided by first view redirect me another page while it is supposed to redirect to second view page. After some research I figured out that links on the first taxonomy terms view redirect me default taxonomy page. And I read that it's possible to override default taxonomy page by using some extra module called Taxonomy Display and Display Suite. After installation modules and I follow the insturctions, I found out the option taxonomy terms page display under the related taxonomy vocabulary. I set Associated content display as views and picked related view(second view I created) but I can't get output of second view. I get all content listed(not filtered).

Please help me, I feel very desperate.
Thanks in advance.

Open a view you have create

1) set the path: /categories

2) add a CONTEXTUAL FILTERS as

3) OR add a RELATIONSHIPS as

after save a view


Drupal 7 - Programmatically create field collection within field collection Example: Map (node) has unlimited areas (field collection field). Each area has unlimited layers (field collection field). The area fc. have normal fields and the layer fc. The layer fc. only have normal fields.

I can create a field collection on the node, but unable to figure out how to attach another field collection to it. I assume the 2nd fc. should use the 1st fc. id as HostEntity.

The code is running in a custom module, and it should create the Map node.

Any ideas, suggestions?

I just figured this out, please see field collection module issue:

http://drupal.org/node/1393552#comment-5428548


Field Collection module Ajax error I'm utilizing the Field Collection module to allow me to associate objects of one content type (say, Authors) with another content type (say, Books).

When viewing the Edit page for one of my specific Book objects, whenever I try to use the "Add another item" or "Remove" buttons within the Authors section -- which operate via Ajax -- I'm getting an Ajax "403 Forbidden" error on the following URL:

field_collection/ajax

One key piece of information is that this happens with only one specific object; the functionality of those buttons works perfectly fine on the edit pages of other Books.

When I visit the Recent Log Messages page -- admin/reports/dblog -- it displays the following error message:

Notice: Undefined index: form_build_id in ajax_get_form() (line 320 of .../includes/ajax.inc).

I checked though, and the form_build_id does, in fact, appear to be included with the POST data being submitted to field_collection/ajax.

Is it possible that that form_build_id is somehow invalid?

I'm sort of at a loss here. Any thoughts?

UPDATE:

I set up watchdog to log the POST data, and it seems like there's absolutely no data available in $_POST once it hits the field_collection_remove_js function within the Field Collection module code...

Is there a chance I'm hitting some sort of POST length/size limit? The node in reference does, in fact, have a whole bunch of data associated with it.

In case it helps anyone else, I believe I was running into memory limit issues in PHP. Adding the following to my sites/default/settings.php seems to have resolved the issue:

ini_set('memory_limit', '128M');


If user requests page that is unpublished, gets permission denied and page dies with too many redirections When users without permission to administer nodes want to see content that is unpublished, they get a redirect loop.
I would rather show them a "this content is not anymore available."

Why is the redirection loop happening?

The problem was, i had settings for user to redirect to user/login after permission check, so teh system somehow ended in loop. I set special node page for such occassions, and now everything went normal again. Gisle thanks for comment (which easily could be answer to question)


The requested page "/http://.. could not be found. (puts slash in front of URL) All of a sudden I cannot login because it says
The requested page "/http://testsite.com/user/login" could not be found.
It puts a slash before the URL

I have no idea where that comes from.

Check whether you have changed the $base_url variable in settings.php file in sites/default folder.


views 3: select only one value from a multivalue field I have a content type which has a multivalue image field. I need to create a view that displays a list of nodes of that type but displays only one value of that multifield, not all of them.

I need to get something like this:

node title
first image

node title
first image

etc

Any ideas? Thanks, M.

It under the "multiple field settings" in the settings of your image field.

You should choose "Display all values in the same row", separation mark: "", display 1 item, offset 0. (translated from my own language so names might be a bit different)

UPDATE
You will need to display fields rather then the whole node though. (I don't know how you did this before)


How can I display comments/comment form with a custom module? I have created a module which returns a render array via page callback in hook_menu. The render array contains several arrays that render markup and tables (and data from a particualr node: passed in by a wildcard in the submitted URL). At the bottom of the rendered page I would like the comments and the comments form to be displayed.  My plan is to get the comments via a database query, put them into an array and add them to the render array. For the comments form I was going to use the following code:

    $comment = new stdClass;
    $comment -> nid = $nid;
    $form = drupal_get_form('comment_form', $comment);
    return $form;

How do I append this to my page callback function so that my table/markup render arrays and comments/comments form appear on the outputted page?

Thanks. Hope this makes sense. I'm open to changing my plan if you think there's a better approach.

Solution

To append the comments form, add this to your render array:

$foo = array(
    'comments' => drupal_get_form('comment_form', $comment),
),

Add this, just above your render array:

$comment = new stdClass;
$comment -> nid = $nid;


How can you add a template for a custom confirmation page URL? I want to show custom message on confirmation page (on custom URL).
I created a custom URL in *.routing.yml file and added a method in controller class that returns an array :

return [
  '#theme' => 'mycustom_confirmation',
  '#test_var' => 'Test Value',
];

Next, in *.module file,

I added hook_theme function to return below array:

    'mycustom_confirmation' => [
          'variables' => ['mycustom_var' => NULL, 'webform' => NULL, 'source_entity' => NULL, 'webform_submission' => NULL],
        ]

I added template_preprocess_mycustom_confirmation function to add my customized variables.

Then I created a template file: mycustom-confirmation.html.twig file where I consume the customized variables to show custom message.

After all that, when I landed to confirmation URL (that I set in to admin/structure/webform/manage/webinar_training_request_1/settings/confirmation page) after webform submission , I dont see any message. I dont understand what I missed in module.

This would be a nice starting point:

/erlendsays.module

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function erlendsays_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  array_unshift($form['actions']['submit']['#submit'], 'store_doublecheck_form_result');
}

function store_doublecheck_form_result(array $form, FormStateInterface $form_state) {
  Drupal::request()->getSession()->set("webform_result", $form_state->getValues());
}

/**
 * Implements hook_theme().
 */
function erlendsays_theme() {
  return [
    'doublecheck_form_result' => [
      'variables' => [
        'form_result' => NULL,
      ],
      'template' => 'doublecheck_form_result',
    ],
  ];
}

/erlendsays.routing.yml

erlendsays.doublecheck_form_result:
  path: '/doublecheckformresults'
  defaults:
    _controller: '\Drupal\erlendsays\Controller\DoublecheckFormResultController::index'
    _title: 'DoubleCheck Form results'
  requirements:
    _permission: 'access content'

/erlendsays/templates/doublecheck_form_result.html.twig

TODO: print the form result.

/erlendsays/src/Controller/DoublecheckFormResultController.php

<?php

namespace Drupal\erlendsays\Controller;

use Drupal\Core\Controller\ControllerBase;

class DoublecheckFormResultController extends ControllerBase {

  public function index() {
    return [
      '#theme' => 'doublecheck_form_result',
      '#form_result' => \Drupal::request()->getSession()->get("webform_result"),
    ];
  }

}


How can I bootstrap a multi-site instance? It's possible to bootstrap Drupal 8 and create a new node using answer # 174474.
define('DRUPAL_DIR', '/usr/share/nginx/html');

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);
$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create([
  'type' => "article",
  'title' => "test entity",
  'body' => "body body body",
]);
$entity->save();

Is it possible to bootstrap a subsite database when using multisite to create the new node in a specific subsite?
In Drupal 7, this can be done by using the function drupal_override_server_variables, but this function doesn't exist in Drupal 8.
I also tried modifying the $_SERVER['HTTP_HOST'] and $_SERVER['SCRIPT_NAME'] variables according to this forum post, with no luck.

I was able to get this working by setting the server variable  $_SERVER['SCRIPT_NAME'] to '/subsite/index.php' (where /subsite/ is the url path to the subsite).

$_SERVER['SCRIPT_NAME'] = '/subsite/index.php';

define('DRUPAL_DIR', '/usr/share/nginx/html');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);
$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create(
array(
  'type' => "article",
  'title'=> "test entity",
  'body' => "body body body",
));

$entity->save();


Return inserted serial from drupal_write_record I have a module which creates records in the db via drupal_write_record and this works perfectly. However I need to get the automatically assigned serial number for each record which is written into a variable.

Does anyone know how I can achieve this and get the index #?

I need the index variable to use in another table to create the reference...

Edit: Clives answer worked as below:

// Create object
$call = new stdClass;
$call->uid = $user->uid;
$call->call_type = $call_type;
$call->cli = $cli;
$call->start_nid = NULL;
$call->timestamp = $timestamp;

// Insert call row in db
drupal_write_record($table,$call);

// Test correct index
drupal_set_message($call->call_id);

drupal_write_record() populates the serial field of an object you pass to it automatically. So assuming you have a serial field in your table called id, if you run code like the following:

$record = new stdClass;
$record->title = 'Title';
$record->some_other_field = 'Something';

drupal_write_record('table_name', $record);

the $record object will be auto-populated with a member representing the serial column when the function returns. In this example you can access it with $record->id.


Problem with date formatting I've a strange problem with Date formatting in Chinese.

The 年 string has to appear after year(for example 2013年). The string appears in all years before 2013 and also in 2013. But if it is future year(2014, 2015 etc) then it doesn't appear.

This is the date format used.

Y\年 n\月 j\日

I am not sure if it is Drupal's problem or PHP's. And I have no clue how to debug this issue. Any kind of hint is most welcome.

I don't know really why but I have a solution for you
first put you result in a variable, ( try you result something like this Y/n/j )
then exclude variable by / and finally use your character.

$temp=date('Y/n/j');
list($y,$n,$j)=exclude('\/',$temp);
$final="$y\年 $n\月 $j\日";

I hope be useful for you. :)


How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc? How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc...

Is there any easy way to migrate a Drupal 6 Ubercart store to another CMS or shop system?

What would you use instead of Drupal Ubercart?

How to migrate Ubercart Shop (drupal 6) to another CMS / Shop system as Commerce, Magento, etc...

A typical approach to migrate such site to D7 is to use the Migrate module.

  Is there any easy way to migrate a Drupal 6 Ubercart store to another CMS or shop system?

Using the Commerce Migrate Ubercart module will pretty sure simplify things. Some details from its project page:

  Commerce Migrate Ubercart is a migration using Commerce Migrate and the Migrate suite that can migrate 6.x and 7.x Ubercart stores from either the existing Drupal database or an external database on the same machine.

Since this includes D6 and Ubercart, you should definitely have a look at this module if you go for Drupal Commerce

  What would you use instead of Drupal Ubercart?

Going for the Drupal Commerce module is definitely an option you should consider, and the modules mentioned above should help (a lot?) to get you there.


Drupal 7 with Display Suite and Apache SOLR search environments I have the magnificent Display Suite working for search results but I can't for the life of me figure out how to use it to modify a search environment defined on admin/config/search/apachesolr/search-pages.  Please can someone explain how do I use DS to change the display?

Outstanding.  After a weekend of searching it turns out this is a known bug (http://drupal.org/node/1166114) which may be fixed in Drupal 8.

Does anyone know the best method for encouraging it to be fixed quickly in D7?  I'd be prepared to contribute to a bounty.

The second branch of Display Suite has full support for Apache Solr pages, it basically takes it over by default. This hasn't been committed to the first branch as it involves to much changes.

The second branch doesn't have much changes - you might get some notices first, but re-saving the Display configuration solves those.

The biggest change is the default template files which are a little different because the 'Hide empty regions' option has been removed. The logic for collapsing regions is now in the template file itself. That's why we now ship with a 2 column and 2 column fluid template for instance.


How can I write dynamic query? Can anybody suggest to me how I can write a dynamic query in Drupal for the below MySQL query.
Any suggestion will be appreciated.

select * from cap_pas where pas_uid not in
  (select pas_uid from cap_boat_to_pas)

There are many similar questions on Drupal Answers.

$subquery = db_select('cap_boat_to_pas', 'cp')
  ->fields('cp', array('pas_uid'));

$query = db_select('cap_pas', 'cp')
  ->fields('cp')
  ->condition('cp.pas_uid', $subquery, 'NOT IN');

results = $query->execute()->fetchAll();

Note: to write this in a single query (by using joins), take a look at leftJoin().


Most efficient way to change CSS between pages I'm looking to change certain parts of my design for my site through the CSS, my basic principle is that when you navigate to a certain page, it will kick in to effect, and change some CSS values.

Say for example you navigate to mysite.com/colour/red. It would change certain parts of the styling to red (like border colours, underlines, link colours etc) and it would remain in red until you then navigated to something like mysite.com/colour/green at which point, everything that had previously changed to red, now becomes green.

I have already written some code which runs a function when you navigate to one of these pages and sets a session variable using the Session Cache API so that I can set a temporary colour change for the site.

My question is, what is the best way of injecting the new lines of CSS into my site at this point? My initial train of thought is that I can extend the function I currently have to pull in an external CSS file with those specific colours already defined (ie if you go to mysite.com/colour/red, it will pull in red.css, with the border/underline already specified). Or alternatively, I have thought about using the html.tpl file to perform a check against the session parameter, and pull in a CSS file through there.

What would be the most efficient way of changing my stylesheet? Is there a function already in Drupal which would allow me to do something like this

NB. I am using the Alphorn Omega theme template

I think the usual method of adding per-page CSS is in your template.php file using HOOK_preprocess_page(). A couple of examples:

alphorn_preprocess_page(&vars) {
  // Add CSS based on path (beware if you change your path structure!)
  // But as a bonus, this will add the CSS for any path under "/colour/red"
  if (strpos($_SERVER['REQUEST_URI'], 'colour/red') !== false) {
    drupal_add_css(drupal_get_path('theme','alphorn').'/css/red.css');
  }

  // Add CSS based on NID, with an out because this hook may be called on non-node pages
  // or pages that otherwise don't return anything useful for menu_get_object().
  @$node = menu_get_object();
  $red_nodes = array(1, 2, 3, 5, 8, 13);
  if(isset($node) && in_array($node->nid, $red_nodes)) {
    drupal_add_css(drupal_get_path('theme','alphorn').'/css/red.css');
    // If your stylesheet is really simple you could always inline it.
    drupal_add_css('body { background-color: #FF0000; }', 'inline');
  }

  // Then you need to plug your added CSS into your variables or nothing will happen.
  $vars['styles'] = drupal_get_css();
}


Custom fields always empty I followed the steps on skvare to index Civicrm contacts via Search API, then to have Views list the contacts with the search box as an exposed filter. This seems to work overall, but custom Civicrm fields don't seem to be showing up via Views. For example, I've got records showing up with display name, bio, and contact ID. But they're also supposed to have custom fields called "designation" and "role". I've checked that the corresponding contact created in Civi has values (strings "test" and "pencil sharpener" respectively) for these fields. I've made sure that these fields are indexed in the search API and I've rebuilt the search index, to no avail. I'm able to select the fields in the Views UI but when I look at my View, I don't see them and when I do a dump of the fields variable in the View template, those fields are there but they just have an empty value.

Why are my custom Civi field values empty when I try to display them on contacts indexed with the search API via Views? This is all in Drupal 7.

Hard to confirm why yours are not showing. If I am comparing like with like then I have built some Views and used Search API to give the custom data in the View columns and to provide blocks showing the count for each of the sub-types of that custom data.

Thing is there is so many steps involved I don't really know how to provide a clear recipe for you to follow assuming of course that would be better thank Mark's since I know I used that as part of my own journey on this.


How do I display image title in "Manage Display"? How do I display image title in "Manage Display"?

I have add title in my image.　But it is not showing in article.

Image title is a part of the image field not the main node title. So, you can't see the image title field under manage display.


change an exposed filter from a select box to a text field search I have a view that utilizes a node-reference field. I want users to be able to filter by this field using a search-box (or an autocomplete field), but when I set the exposed filter to the node-reference field, all I get is a drop-down. How can I force this to be either a text field or autocomplete?

Thanks!

views 3
drupal 7

This might help you,

http://drupal.org/node/506654#comment-6412784

Views autocomplete filters


Update image tags using entity metadata wrapper I'm trying to bulk update image tags using entity_metadata_wrapper.

I'm unable to see the image field when I use $emw->getPropertyInfo().

The bundle is called hub_page.

The code I'm using is:

$wrapper = entity_metadata_wrapper('node', $node_id, array('bundle' => 'hub_page'));
var_dump($wrapper->getPropertyInfo());

Is this the correct way?

You must pass in a node object as the second value, instead of a node ID.

$node = node_load($node_id);
$wrapper = entity_metadata_wrapper('node', $node, ['bundle' => 'hub_page']);

That might be your problem. Check out the docs: Entity metadata wrappers.


Custom packaged CKEditor: Make buttons available on profle configuration page We wanted buttons to add Definition Lists (dl, dt, dd tags) in CKEditor using this CKEditor plugin ckeditor-plugin-descriptionlist. There is already ckeditor_descriptionlist module but not available for Drupal 7 at the moment.

So, we packaged CKEditor to have descriptionlist plugin in it. Here is that custom built CKEditor package: ckeditor-4.5.11-full-with-descriptionlist.zip.

Problem is that three buttons from descriptionlist plugin is not available in CKEdior profile configuration pages to add to any particular profile.

I know we can backport above mentioned ckeditor_descriptionlist module to work in Drupal 7. But I am asking whether it will be possible to bring that buttons for configuration without using a drupal module as we have CKEditor package with required plugin?

I found the solution myself.

Earlier I was using "CKEditor 4 Presets Builder" available at https://github.com/ckeditor/ckeditor-presets . That is not required. I just have to put copy of descriptionlist plugin within "plugins" directory of CKEditor library. Then those three buttons started to appear in CKEditor profile configuration page.


Get view result with sorting option programmattically I've a view with sorting, that I need to call programmatically like,

$view_name = 'view_name';
$display_id = 'page';
$exposed_input = Array
(
    ['field_year_value'] =>
    ['shs_term_node_tid_depth'] => All
    ['field_federal_entity_value'] => All
    ['order'] => title
    ['sort'] => desc
);

$exposed_filters = Array
(
    ['field_year_value'] =>
    ['shs_term_node_tid_depth'] => All
    ['field_federal_entity_value'] => All
)

$view = views_get_view($view_name);
$view->exposed_input = $exposed_input;
$view->exposed_raw_input = $exposed_filters;
$view->set_display($display_id);
$view->pre_execute();
$view->execute();

But the result is not sorted.

Is there a way to accomplish this?

You could check this sample code. It contains additional methods in Views that you could use like in the line:

//Here we can alter the order
//$view->set_item('default', 'sort', 'random', NULL);
if(isset($alter['node_created_order'])){
  $view->add_item('default', 'sort', 'node', 'created',array('order' => $alter['node_created_order']));
}


How to render an Image Field as a URL in node.tpl.php I have an image field called field_body_image

I want to render it in my tpl.php file with a custom image style. I am using the following code (from this thread) to do this:

<?php $view = field_view_field('node', $node, 'field_body_image', array('settings' => array('image_style' => 'thumbnail')));?>
<?php print render($view); ?>

However, I want to display the URL of the image. How can I do that?

This thread has a solution, but it is for user photos and so you cannot specify a custom field.

Image Url Formatter is a module that can do this, but I would rather achieve it without an extra module.

This page has some advice, but apparently it is not best practice.

You can do this by getting the path to the file.

<?php $file = file_load($node->field_body_image['und'][0]['fid']); ?>

Then render the path:

<?php print file_create_url($file->uri); ?>

I tested this and it works. In my case I had an event image in my local dev site and it rendered:

http://events.dev/sites/default/files/event-images/imagefield_7tgPJ7_0.jpg

In your tags, you did not specify Drupal 6 or 7 but my code above would be for Drupal 7.


boolean function to determine whether an commerce order id exists? is there a boolean function that exists OOTB that allows you to determine if a commerce order id exists?

I'm trying to pass an order id and check if is actually an existing order regardless of order state.

There isn't a function that returns only a boolean, but commerce_order_load() returns FALSE if no order is found so you can use it in an if statement quite happily:

if (commerce_order_load($order_id)) {
  // Order exists
}

If you want to be bit more militant about it you could use this:

if (commerce_order_load($order_id) !== FALSE) {
  // Order exists
}

But it shouldn't really make a difference.


How do I add an additional database for migration? I have a Drupal 8 site running in Lando. I need to have the 8 site connect to a Drupal 7 database so I can run a migration.

My understanding is I can import an additional database through Lando, but from the documentation I cannot figure out exactly how to do this.

I've tried adding this to my .lando.yml:

services:
  legacydatabase:
    type: mysql
    creds:
      user: root
      password:
      database: legacy

and then multiple attempts at the lando db-import command to no avail.

I need to know what exactly goes in .lando.yml and then what exactly goes in the lando db-import arguments to get this working.

You are on the right track. You can use

services:
  legacydatabase:
    type: mysql

And do a lando rebuild to spin up a second DB server. If you did not specify the credentials you can check them with lando info.

To use db-import (or export) you have to specify which host to use. By default it uses 'database' and not legacydatabase or whatever you called your second DB server. As per the documentation:
Options:
  --host, -h      The database service to use                  [default: "database"]

So the command to use in your case would be:

lando db-import --host legacydatabase [your_mysql_file]


How do I load external JavaScript before local JavaScript? I try to load JavaScript with drupal_add_js(), but it's not easy, and after fixing the loading of external JavaScript, I faced off a loading order issue: My external JavaScript is loaded after my local ones, and I would like the opposite behavior. Is it possible with Drupal 6?

Additional problem but optional: Is it possible to load these in footer instead of the header?

This is my code.

function d6_ce_susy2_preprocess_page(&$vars){
    //http://www.zites.net/en/load-external-javascript-files-drupal-6/
    $external_js1 = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js';
   drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js1 .'\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');
    $external_js2 = 'http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js';
   drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js2 .'\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline','header');
    $external_js3 = 'http://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.2/masonry.pkgd.min.js';
   drupal_add_js('document.write(unescape("%3Cscript src=\''. $external_js3 .'\' type=\'text/javascript\'%3E%3C/script%3E"));', 'inline');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/jquery_init.js','theme');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/js_jquery_new.js','theme');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/jquery_exit.js','theme');
   drupal_add_js(drupal_get_path('theme', 'd6_ce_susy2') . '/js/js_jquery_defaut.js','theme');
      }

You can below preprocess function with scope and weight. You would need to set scope as footer and add the variable to html.tpl.php before body tag.

function paddle_theme_preprocess_html(&$variables) {
  drupal_add_js(drupal_get_path('theme', 'paddle_theme') .  '/scripts/footer.sticky.js',
  array(
    'type' => 'file',
    'scope' => 'header',
    'group' => JS_THEME,
    'every_page' => TRUE,
    'preprocess' => FALSE,
  ));
}

Also for Drupal 6, you can check the following reference with Advance JS aggregation or LABjs which can do the parallel loading.

http://www.drupalden.co.uk/move-render-blocking-javascript-bottom-page


How to display a Flag in a tpl file for different View modes? There is no field in manage display of content type to display Flag link.
There is a tpl file (node--article--teaser.tpl.php) for teaser mode displaying bookmark

<?php if (isset($content['links']['flag'])) : ?>
    <?php echo render($content['links']['flag']);?>
<?php endif; ?>

But for another mode this having View mode teaser_2_col and tpl file name node--teaser-2-col.tpl.php, $content['links'] does not have a Flag element.

You actually can display a Flag link as a pseudofield, which can be ordered among other entity elements in the Manage display settings for an entity type. Go to admin/structure/flags and pick the Flag that you need. Next, check Display link as field in the section Display in entity links. You can now use the link in your template files by rendering the node and getting the right field (use Devel for this).

Alternatively, you can output a Flag link by using flag_create_link($flag_name, $entity_id). In that case you don't need a pseudofield.


How to add a placeholder to an exposed date filter form field? This is the structure of a date field in my exposed form:

<input id="edit-date-filter-value-datepicker-popup-0" class="form-text hasDatepicker date-popup-init" type="text" maxlength="200" size="20" value="" name="date_filter[value][date]">

I added this code under

function bartik_form_views_exposed_form_alter(&$form, &$form_state) {}

to add place holder.

$form['date_filter']['#attributes']['placeholder'] = t('YYYY-MM-DD');

But place holder is not coming. Can anyone help?

jQuery may be a solution.

jQuery(document).ready(function(){
 jQuery('#edit-date-filter-value-datepicker-popup-0').attr("placeholder", "placeholder to show");
});


Display different fields depending on field value in node template I have a field named field_event_type. When creating a node, you can select one of two options for this field from a drop-down list:

birthday party
Wedding

I want to be able to display different fields in my node depending on which type of event is selected. So in node--events.tpl.php, my node template, I wrote the following:

if ($element['#object']->field_event_type['und'][0]['value'] == 'birthday party' )
   {
      print render($content['field_some_field']);
   }

else
   {
      print render($content['field_some_other_field']);
   }

However, this does not seem to be working the way I intended it to, not only is it not displaying the additional field content in either event type, but I'm also getting an error in Drupal about an undefined variable. Is my code incorrect?

You may find it easier to use the Conditional Fields Module:

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. You can, for example, define
  a custom “Article teaser" field that is shown only if a "Has teaser"
  checkbox is checked.


The directory does not exist TL;DR

In Report → Status, I’ve the following error:

Writable (public download method)
The directory /var/priv_fls does not exist. You may need to set the correct directory at the file system settings page or change the current directory's permissions so that it is writable.

How can I solve this error?

Full Story

In my webhosting at Forpsi, I’ve got FTP access to folder, in which there is www folder (let’s call this folder web_root). I’ve installed Drupal 8 in web_root/www. Then, I’ve added to web_root I’ve created a folder called priv_fls—for private files—and chmod’ed its permissions to 777 (I know it’s not secure). In web_root/www/sites/default/settings.php the following line: $settings['file_private_path'] = '/var/priv_fls'; and Cleared all caches (in Drupal). Then the error above appeared.

It might be that it is not /var/priv_fls from Drupal’s point of view, but even tried to change it /priv_fls in settings.php, but the error remained.

Update

I emphesise that web_root is only a substitution for the ‘root’ folder to which my webhosting provider (Forpsi) gives me access. If I login to the server using FTP, this web_root folder lists the following files:

/> ls
drwxr-xr-x    9 66573      users            4096 Sep  5 20:10 .
drwxr-xr-x    9 66573      users            4096 Sep  5 20:10 ..
-rw-rw----    1 66573      users               7 Sep  1 02:39 .ftpquota
dr-xr-xr-x    2 0          0                4096 Jul 15 22:01 backups-forpsi
drwxr-xr-x    2 66573      users            4096 Sep 23  2010 data
drwxrwxrwx    2 66573      users            4096 Sep  5 20:10 priv_fls
drwxr-xr-x    3 66573      users            4096 Sep  1 12:54 softaculous
drwxr-xr-x    2 66573      users            4096 Sep 23  2010 stat
drwxr-xr-x    2 66573      users            4096 Sep 23  2010 tmp
drwxr-xr-x   10 66573      users            4096 Sep  4 19:40 www

But I can’t get the absolute path (pwd gives me ftp://user@server.com:/>; ls .. gives me same output as ls; both of which are useless from the point of getting the absolute path).

Anyways, Drupal is installed on shared webserver.

TL;DR
web_root = /web/htdocs4/username/home/, where username is (at least in my case) my ftp login (they use the following convension: for domain example.com the username is examplecom)
Full Story
I’ve just accidently found out what is the absolute path of the web_root.
I installed TCPDF module and enabled both TCPDF and TCPDF Example. The latter created a link TCPDF example in the second (right) sidebar, and when clicked that link, it showed me the following error:
 Fatal error: Class 'TCPDF' not found in /web/htdocs4/username/home/www/modules/tcpdf/src/TCPDFDrupal.php on line 16


Forced HTTPS not working on Home Page I'm using HTACCESS to force all my pages to redirect to the HTTPS version. However the home page is still able to go to the HTTP version.

I tried 2 examples from this post: How to simply make the whole site HTTPS?

And they work, but not for my home page as I mentioned. HTTPS is redirecting everywhere except the home page.

RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^www\.yourdomainhere\.com*
RewriteRule ^(.*)$ https://www.yourdomainhere.com/ [L,R=301]

And

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Edit: When I go to the HTTP version of the home page, any time I click a link it redirects to the HTTPS home page instead of the respective link. After that once on the HTTPS home page all links work correctly.

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    </IfModule>
    <IfModule mod_headers.c>
        Header always set Strict-Transport-Security "max-age=31536000; $includeSubDomains"
    </IfModule>

Is what you are looking for. Make sure to place these rules before any other rewriting rules (that may e.g. come from your webserver config).


Ajax Effects using Ajax #commands Assuming I have the following PHP. I want to add different effects to each of the ajax commands

function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1),
      ajax_command_replace($selector2, $html2),
    ),
  );
  return $result;
}

I understand the default is something along the lines of:

ajax_command_replace($selector, $html, $settings = NULL)

However I do not know what to do with the $settings = NULL for a fade or slide to work. I've tried all combinations, but to no avail.

e.g.

ajax_command_replace($selector, $html, array('effect' => 'slide'),
ajax_command_replace($selector, $html, array('#effect' => 'slide'),
ajax_command_replace($selector, $html, 'slide')

I found the best solution to this was using ajax_command_invoke() and layering the required ajax effects together.

For example, you won't be able to directly fade in an element, but you can use replace or prepend, etc., then hide the element, then fade it in.

function my_ajax_callback($form, $form_state) {
  $result = array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace($selector1, $html1), //add your element
      ajax_command_invoke($html1, 'hide'), //hide it
      ajax_command_invoke($html1, 'fadeIn'), //now use the effect you're after
      ajax_command_replace($selector2, $html2), //add your other element
      ajax_command_invoke($html2, 'hide'), //hide it
      ajax_command_invoke($html2, 'show'), //use the other effect
    ),
  );
  return $result;
}


Start nodejs server on centos I install Nodejs integration module in drupal7, then install Nodejs package on CentOS 6.4; In instruction nodejs integration i see:
'In your terminal window, start the node server using the following command:'

node server.js

but in module directory, i haven't file "server.js"

can anyone help?

The server.js file has indeed been removed from the package. The solution is in the readme:

  Setup

  Install drupal-node.js packge with npm:

  npm install drupal-node.js

  Make sure to do this outside of your Drupal modules directory, else
  Drupal may try to process folders containing Node.js module
  information and fail. Follow the install instructions in the
  drupal-node.js NPM package. You will need to provide the hostname and
  port of your Drupal site to the Node.js process, and ensure that the
  service token matches between Drupal and Node.js.

I suppose they separated the server from the Drupal module to allow more frequent updates.
The npm package contains a settings file and app.js, which includes server.js.


How to get url alias of a link, when rewriting field output in Views I have an image field in Views, for which I must use "Rewrite output" option. The output of the image field is this:

[field_image]

So, it contains a link to taxonomy term. But I would like this link to be the custom url for this taxonomy term, instead of raw Drupal path. My Pathauto pattern for taxonomy term is:

[term:vocabulary]/[term:parents:join-path]/[term:name]

But in Views, the [term:parents:join-path] token is not visible on the list of Replacement Patterns.

How to achieve this?

The Global Redirects module (drupal.org/project/globalredirect) would be one potential solution! It will automatically redirect all links on your site that are like that globally.


how to depricate repeated field values from my view? Look at my screenshot i don't need repeated employee id and name...i
 just want to print emloyee id and name once but i want to display the others records with blank employee id and name but not salary, month and year....I am using JOIN
 query in my hook view... So gyus please suggest me any trick to remove
 those field value...

edited question for clarity...

You can apply GROUP BY or DISTINCT by enabling views aggregation
  settings to remove duplicate records.

  Go and edit your view
  In Advanced » OTHER section by enabling Use aggregation: Yes
  In FIELDS or FILTER CRITERIA section, select and apply Aggregation settings for which fields you want to group by or distinct.

source: https://www.drupal.org/node/1704962


How to count the number of votes for each star in fivestar? I'm using Drupal 7, Voting API and Fivestar.

I try to count the number of votes for each star, and display the percentage, like :

It is at present possible to have only the number of total vote.

How can I achieve this?
With Voting API (hook_votingapi_results_alter) or Views ?

For information, i'm using comments for rating nodes.

Once i tried to find some function that could do it. But i found just
 fivestar_get_votes($entity_type, $id, $tag = 'vote', $uid = NULL). It returns full voting score.

You can get some info here or on other sites.

I think it is possible with some sql queries EG:

   $query = db_select('votingapi_vote', 'vote');
   $query->condition('vote.entity_type', 'node');
   $query->condition('vote.entity_id', $nid);
   $query->condition('vote.tag', 'vote');
   $query->condition('vote.value', '60');
   $query->addField('vote', 'uid');
   $three_stars = $query->countQuery()->execute()->fetchField();

Here $nid is your your node's nid and 60 means three stars (20 - 1 star, 40 - 2 stars etc), vote.tag is tag that you assigned for your votes.


PlaceHolder in comment Form I want to add a placeholder to my all comment form , here is what i did :

template.php

function ThemeName_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        // HTML5 placeholder attribute
        $form['search_block_form']['#attributes']['placeholder'] = t('Serach ...');

    }

    switch ($form_id)  {
        case 'comment_form':
            $form['name']['#attributes']['placeholder'] = t( 'Name' );
            $form['subject']['#attributes'] = array('placeholder' => t('Subject'));
            $form['comment_body']['#attributes'] = array('placeholder' => t('comment'));

            break;
    }

}

nothing happend , Any Help ?

Thanks

Update
Finally i could add placeholder to comment form like this

function sizin_form_comment_form_alter(&$form, &$form_state)
{
    $form['author']['name']['#attributes']['placeholder'] = t( 'Name' );
    $form['author']['name']['#title']= FALSE;

    //Subject
    $form['your_comment']['subject'] = $form['subject'];
    $form['your_comment']['subject']['#title'] = FALSE;
    $form['your_comment']['subject']['#attributes'] = array('placeholder' => t('title'));
    unset($form['subject']);
    $form['your_comment']['subject']['#weight'] = -10;

    //Comment
    $form['your_comment']['comment_body'] = $form['comment_body'];
    $form['your_comment']['comment_body'][LANGUAGE_NONE][0]['value']['#attributes'] = array('placeholder' => t('comment'));
    unset($form['comment_body']);

}

But i couldn't add to textarea(comment Body) ? AnyHelp ?

Reading through Placeholder module I come to know this

  Once FAPI uses HTML5 to render elements, this module can be replaced
  by the "placeholder" attribute available as part of the HTML5 spec.
  You can update the FAPI to use the "placeholder" attribute right now
  by using elements module. This means that this module is only useful
  if you are concerned about older browsers that do not support
  "placeholder".

try using elements module so the support for HTML5 attribute can become available in your installation.

Here is the way to add default placeholder attribute.


Can I set Drush to always use verbose? Its quite annoying to have to type -v.

Is there a way to change the drush settings so that it will always use verbose mode so I dont have to bother typing -v?

This works for me in Drush 5.

In a drushrc.php file (I tested with my ~/.drush/drushrc.php you could do this per-project as well).

I simply added:

$options['v'] = TRUE; somewhere in the file. Then try issueing drush commands.

This works because of how drush_parse_args executes.


After installation of Drupal commons-7.x-3.13 in windows. I got this type of error? I am using Drupal Commons-7.x-3.13 module to install in windows. After installation I can't logged my site.

Please help anybody. I am in critical situation.

You need to allocate more memory. There is not enough for mysql to run. There is an entire handbook page dedicated to this common issue. See https://drupal.org/node/259580


Drupal and jQuery Plugins (ie tools) - overlay - mask isn't working - suspect javascript issue G'day all,

I've implemented the demo available at http://flowplayer.org/tools/demos/overlay/modal-dialog.html in a hook_menu to test (note that this is the jquery tools plugin, available via the module jquery plugins). Everything works fine with the exception of the mask, I cannot get it to work.

The only difference between the example javascript on the above link and what I'm using is that I had to encapsulate the javascript with the following:

(function($){
  $(document).ready(function() {
    <demo javascript code goes here>
  });
})(jQuery);

The demo code appears to be using:

var triggers = $(".modalInput").overlay({
  // some mask tweaks suitable for modal dialogs
  mask: {
    color: '#ebecff',
    loadSpeed: 200,
    opacity: 0.9
  },
  closeOnClick: false
});

Which all makes sense to me and I cannot see why it wouldn't work.

My version of the javascript is (I removed one button): http://pastebin.com/MH6ehmTR
My version of the html is: http://pastebin.com/aW6UpFBQ
My version of the css is: http://pastebin.com/tUQWDqZp

The html is taken from the generated html by drupal.

The reason why I need this fixed is to disable access to the rest of the page while the dialog box is open (thus becoming modal). The current situation is that a person can interact with the rest of the page while the dialog is open.

FYI the browser is firefox, it works for the demo code, just not for the drupal implemented one. Also the method of getting jQuery tools overlay available is via the jQuery plugins module.

I had a similar problem where the overlay was displayed in IE7, no elements on the page displayed, including close button. All elements were behind the mask. Adding this in the overlay() settings solved the issue:

onLoad:  function() {
  this.getOverlay().insertAfter('#exposeMask');
}

now the login popup in my site riparotto works fine.


Fetch node value in Rules I am trying to get option value from node in drupal rules. I have a form-group which consists of fields. The field in question is a select list - it consists of different names, with every option there is an email. They are stored in this way:

0|NONE
example@example.com|EXAMPLE
example2@example.com|EXAMPLE2

So option value for EXAMPLE is example@example.com
Let us call this field operator.
So I want to send/get email from this node
What I have atm in rules is
    [node:field-operator:value]
which does not work.
    [node:field-operator]
for example just fetches the name e.g EXAMPLE.
 I have tried tons of ways by now but I know that solution must be simple, it's just my first time using drupal and been looking for an answer for hours.
Thank you for your help.

Make sure you already have the Token module  installed in your site. The Token module.

on your site go to /admin/config/workflow/rules
Select send an email on the action section of the rule
Click switch to data selection
Click DATA SELECTORS and find your select list Eg:(node:field-select-list) token and add it into To box.

Hope it help


Why isn't code for $op == 'presave' being executed in hook_nodeapi? I want the administrator users can publish nodes of the story content type; the other roles can unpublish. The following is the code I am using, but it doesn't work. I unchecked the box "published", which is in the "story" content type.

   function mymodulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
     global $user;

     if ($op== 'presave' && $node->type == 'story') {
       if (in_array('administrator',array_values($user->roles))) {
         $node->status = 1;
       }
     }
   }

I am using echo 'test' above on the if ($op....), the page outputs "test." When I put the echo 'test' into if body, the page doesn't output "test." but When I delete $op == 'presave'， it can output "test."

Regarding your problem, you're editing the node right ? Because presave acts during saving.

On a site I use this module which is quite handy, maybe it can help you: Publish Content


Reload a View with AJAX on a click event I have a view displaying a table of related nodes that is embedded on another node's page. The info displayed in embedded view is periodically changing, I want to allow the user to refresh the view by clicking a "Refresh View" link or button without reloading the entire page.

I've checked out the views-hacks module which provides the auto-reload feature, but that doesn't do exactly what I need it to do.

I'm afraid you won't do without a bit of coding here. What first comes to mind is a combination of

Form API for the refresh button,
views_embed_view() for retrieving the current version of the view.
AHAH javascript replacement for the view output replacing, and

Modules Views Auto-refresh mentioned by you or Ajax Views Refresh may not do exactly what you're after, but their code could be a source of inspiration when implementing views refreshing.

I also recommend having a look at the code of the Drupal core's Poll module, mainly the functions poll_choice_js (the callback function for the path poll/js) and poll_form ($form['choice_wrapper']['poll_more'])


Webform Build Tab not displaying correctly We just installed the Webform module, but as I'm going in to create and edit a new form, the "Build" tab is only allowing me to enter Elements with YAML code (pic one below). In the module description, it shows a preview of the Form Builder (pic two below), which doesn't look anything like what we have.

Is there an add-in that makes it looks like the module description...and therefore easier to use?

You need to enable the Webform UI module.


Copy blocks from one drupal installation to another With a lot of help from the users of this forum yesterday I managed to get my local installation running.

I have copied across the theme from the site I wish to base mine on (with the permission of the theme owner, so nothing dodgy is going on).

But when I go to Blocks, there are none present. If I look in the admin on the old site, there are a number of blocks that appear in the header (menu, search bar and so on). If I click on create new block on my install I get a blank form. Is there any way to copy existing blocks from the install I am mimicking to mine?

Blocks are considered content, like nodes are. So basically you want to migrate content? You could work with Migrate or Block Export Import.


How to create a contextual filter using a current user multivalue field as the default value How to create a contextual filter using a current user multivalue field as the default value?

The idea is to filter content in a view, based on a value present in a multivalue field that the currently logged in user account has.

I tried using views php in the default contextual filter:

$user_profile = user_load($user->uid);
$statusvalue= $user_profile->field_status['und'][0]['value'];
return $statusvalue;

..but that works for a single value and thus does not work in my case.

In your contextual filter go to bottom and in tab "more" check "allow multiple value" checkbox and return value 1+2+3 (OR) or 1,2,3 (AND).


Importing a feed from a filefield? I'm ultimately needing a way to regularly upload and parse through a multi-page spreadsheet and then summarize some data from it.

After trying Sheetnode (and disliking its Excel importing implementation, which creates a new node for each sheet in the spreadsheet), I'm thinking the Data module coupled with Feeds might be the best solution.

However, I'm needing some way to download the original spreadsheet after parsing. Ideally, this would mean the user adds a spreadsheet to a filefield and hits upload, after which the original is stored in that field and Feeds API is starts to do its magic.

To this end, is there any way of having Feeds import from a file uploaded via the Field API instead of through Feeds' import page?

(Or alternately, the user uploads via Feeds' Import page and the original spreadsheet is then stored in a fieldfield -- either works.)

Many thanks!

well bottomline is:

You want to import a spreadsheet (maybe with multiple sheets in it) on a regulary basis.

I'd suggest the module migrate, you find the possiblility to import csv-files (and also an example if i remember right).

Migrate has maybe a little more effort in the start, but it also has many nice features like a hightwatermark, means if there is a counter or a timestamp in your file (for each record), then migrate can skip easily over former imported items.

Also tranformation of data is (if neccessary) with migrate possible.

At least you should have a close look at the module migrate.


how to download zip file through browser I have written a module that creates a zip file in the /tmp and then downloads the zip file through browser i.e. it will be downloaded in the ~/Downloads directory by itself.

I don't want to use hook_file_download() because it executes everytime you try to download a file, but I want to be specific while downloading. The above code snippet is written in the same function that creates the zip file.

I have taken the help of davidwalsh blog to create the zip file.

I can create the zip file in /tmp directory, but how to download the zip file.

My code looks like this:

$fp = fopen($filesystem_filepath, 'rb');
header('Content-type: application/octet-stream');
header('Content-Length: '. filesize($filesystem_filepath));
fpassthru($fp);

At first I tried downloading simply using header() function and then after more googling I took the help of readfile($filesystem_filepath) instead of fpassthru($fp) but its not working.

You don't mention exactly what's not working, but at a guess it might be that the download works in all browsers except Internet Explorer?

IE is an annoyance when it comes to forcing downloads, you really have to go around the houses to get all versions to respect what you're trying to do.

Here's the code I use to force downloads, and it works cross browser (updated to address @MPD's comment below):

function force_file_download($path, $filename) {
  // Most of this is only necessary because of IE
  header("Cache-Control: public");
  header("Content-Type: application/octet-stream");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0");
  header("Content-Disposition: attachment; filename=\"$filename\";" );
  header("Content-Transfer-Encoding: binary");

  $fp = fopen($path, 'rb');
  fpassthru($fp);
  exit();
}

You'd use it in a page callback like this:

force_file_download($filesystem_filepath, 'file.zip');

That code works perfectly for me for any type of file, cross-browser, and if you change the exit() to drupal_exit(), it will also work great for Drupal 7 (currently it's a Drupal 6 snippet).


I enabled certain page view (which is a clone of currently working view), but its page link returns 404 page The view is enabled, but its page returns 404. in what cases can such problem exist?

Save the views and then in admin/config/development/performance do clear cache


Field Entity Autocomplete filter the published nodes my problem is that I have a custom form with an autocomplete entity field for the search.
The problem is that the field shows me both the published fields and those that do not. Is there any filter or parameter to prevent this from happening?

$form['my_element'] = array(
'#type' => 'entity_autocomplete',
'#placeholder'=>'Search',
'#target_type' => 'node',
'#selection_settings' => [
    'target_bundles' => array('products'),
  ],
);

The entity reference appears on the registration form, and the applicant is able to view and choose unpublished nodes from the list.

An anonymous user can see nodes of this type, but obviously they are not meant to see unpublished nodes of this type. On the rest of the site, they cannot see these unpublished node (only the autocomplete ignores this.)


Build-in query persist? Is there a default Drupal 8 database persist function? Like as for Doctrine.

for($i=1;$i<100;$i++) {
    $query->persist();
}

$query->flush();

I want to collect first a lot of data and bulk send it to the database.

The code I am using now is the following.

$db = \Drupal::database();
foreach($response->customer_products as $itemCode) {
    $productNode = $this->loadObjectProduct($itemCode);
    $db->insert('customer_product')
           ->fields([
              'card_code' => $cardCode,
              'item_code' => $productNode->id()
           ])
       ->execute();
}

That requires too much memory, and it fires a lot of queries.

Is there some way to collect the queries and bulk-send it to the database?

It's possible to stuff more values into a custom insert (or merge) by using the values method. This isn't comparable to the persist functionality, and can only be used in limited scenarios such as a single table. A more complex storage scenario, such as with entities, would not be possible as a single entity save operation could be writing to multiple tables (unless someone rewrote a custom entity storage layer).

Also, I am not sure what the loadObjectProduct exactly does in your code, but this seems to be loading node entities. It would probably be best to use an Entity Query::condition and fetch back multiple entities.

Finally you need to use an array map/reduce to map the values.

Something like the following pseudo-code:

// Using Database static method from \Drupal\Core\Database\Database.
$database = Database::getConnection();
// Assumes loadObjectProduct is refactored.
$nodes = $this->loadObjectProducts($itemCode);
// I tend to think backwards about this sort of thing. :-)
$values = array_reduce($nodes, function (&$result, $productNode) use ($cardCode) {
  $result[] = [
    'card_code' => $cardCode,
    'item_code' => $productNode->id(),
  ];
  return $result;
}, []);

try {
  $database->insert('customer_product')
    ->fields(['card_code', 'item_code'])
    ->values($values)
    ->execute();
}
catch (DatabaseWrapperException $e) {
  // Catch errors
}


How to upgrade the WebForm module? I'm planning on upgrading the WebForm module in my Drupal 7 site. The current WebForm version is 7.x-3.19 and I'm upgrading to 7.x-4.2.

Question: Is it as simple as uploading the new version? Do I need to run update.php afterwards?

Somehow I seem to remember that updating the WebForm module is not as simple as other modules and can cause existing webforms to break.

You should be fine with the upgrade.  Back up your DB, of course.  If you are uploading the module instead of installing through the UI, then yes, you need to run /update.php.


Add class to one SPECIFIC menu item I'm looking for a way to add an extra class to a specific menu item in my main menu. I see ways to add classes to the entire menu, but not one specfic item.  Can someone point me in the correct direction.

This is for Drupal 7.

You probably want to install Menu Attributes.

  The module currently allows you to set the following attributes for
  each menu item: Id, Name, Target, Rel, Class, Style, Accesskey


How can I display the block title when rendering a block using Twig Tweak? Block title when using twig-tweak plugin, not showing. I created a block-type view. And using the module's cheat sheets, I called:

{{ drupal_view('views_name', 'block_1') }}

You'll have to manually type it on your twig, as per https://www.drupal.org/project/twig_tweak/issues/2738781

If you don't want to type it on twig, a work around would be to add a "Text area" to your view's Header and use replacement patterns,
[view:title]
.

Alternatively, you could ditch Twig Tweak and do it yourself by creating a variable:

function MY_THEME_preprocess_HOOK(&$variables) {
    // replace HOOK with the template file you're trying to add it to. Ex: node, page, block etc..
    $view  = views_embed_view('view_name', 'block_1');
    $variables["my_view"] = \Drupal::service('renderer')->render($view);
}

Then in the template file you just do {{ my_view }}