How to render custom entity I have a custom entity and i don't have any fields in the entity.Instead what i have is:- Adding custom entity page has a form where we have several fields where we are able to fill all the fields in the form.Now the problem which i m facing is is: how to display the entity added  on my_entity/% page?

if you are using Entity API, you can take a look to this article http://www.trellon.com/content/blog/creating-own-entities-entity-api and to the example_task module:

The process works like this:

  // Your entity view path
  $task_uri = 'task/%example_task';
  $task_uri_argument_position = 1;

  $items[$task_uri] = array(
    'title callback' => 'entity_label',
    'title arguments' => array('example_task', $task_uri_argument_position),
    'page callback' => 'example_task_view',
    'page arguments' => array($task_uri_argument_position),
    'access callback' => 'entity_access',
    'access arguments' => array('view', 'example_task', $task_uri_argument_position),
    'file' => 'example_task.pages.inc',
  );

/**
 * Task view callback.
 */
function example_task_view($task) {
  drupal_set_title(entity_label('example_task', $task));
  return entity_view('example_task', array(entity_id('example_task', $task) => $task), 'full');
}

This will invoke to the function in entity/includes/entity.controller.inc folder of Entity API module:

  /**
   * Implements EntityAPIControllerInterface.
   */
  public function view($entities, $view_mode = 'full', $langcode = NULL, $page = NULL) {
    // For Field API and entity_prepare_view, the entities have to be keyed by
    // (numeric) id.
    $entities = entity_key_array_by_property($entities, $this->idKey);
    if (!empty($this->entityInfo['fieldable'])) {
      field_attach_prepare_view($this->entityType, $entities, $view_mode);
    }
    entity_prepare_view($this->entityType, $entities);
    $langcode = isset($langcode) ? $langcode : $GLOBALS['language_content']->language;

    $view = array();
    foreach ($entities as $entity) {
      $build = entity_build_content($this->entityType, $entity, $view_mode, $langcode);
      $build += array(
        // If the entity type provides an implementation, use this instead the
        // generic one.
        // @see template_preprocess_entity()
        '#theme' => 'entity',
        '#entity_type' => $this->entityType,
        '#entity' => $entity,
        '#view_mode' => $view_mode,
        '#language' => $langcode,
        '#page' => $page,
      );
      // Allow modules to modify the structured entity.
      drupal_alter(array($this->entityType . '_view', 'entity_view'), $build, $this->entityType);
      $key = isset($entity->{$this->idKey}) ? $entity->{$this->idKey} : NULL;
      $view[$this->entityType][$key] = $build;
    }
    return $view;
  }
}

As you can see the content is finally rendered through a render element using "Entity.tpl.php"

A way to add your customizations to the view in order to render elements which are not fields may be extending from "EntityAPIController" and writing builContent function:

class ExampleTaskController extends EntityAPIController {

      public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
        $wrapper = entity_metadata_wrapper('example_task', $entity);
        $content['author'] = array('#markup' => t('Created by: !author', array('!author' => $wrapper->uid->name->value(array('sanitize' => TRUE)))));

        // Make Description and Status themed like default fields.
        $content['description'] = array(
          '#theme' => 'field',
          '#weight' => 0,
          '#title' =>t('Description'),
          '#access' => TRUE,
          '#label_display' => 'above',
          '#view_mode' => 'full',
          '#language' => LANGUAGE_NONE,
          '#field_name' => 'field_fake_description',
          '#field_type' => 'text',
          '#entity_type' => 'example_task',
          '#bundle' => $entity->type,
          '#items' => array(array('value' => $entity->description)),
          '#formatter' => 'text_default',
          0 => array('#markup' => check_plain($entity->description))
        );

        return parent::buildContent($entity, $view_mode, $langcode, $content);
      }
    }


Image style copy or clone Is there a UI way to clone/copy image style?

/admin/config/media/image-styles

lists all styles. I wish to modify one of them but I don't want to override it and I don't want to start from scratch.

imagecache_actions module implements this for D7 (brand new, in 7.x-1.x-dev only yet). It is based on a feature request for D8: #1403962. The dev version also implements a rudimentary export/import to copy between different systems (or the issue queue) without a need for features.


Form field with support for multiple values I'm building a costum form using Drupal (7) Form API

I want to create a text field with possibility to add multiple values through autocomplete.
The idea is to allow the user to add taxonomy terms to my instance that is to be saved through the form.

Final goal is to present selected values in a table with fields

Term name | Vocabulary | Actions

Where Term name is a input field with autocomplete. When a term is selected, Vocabulary name is appended through JS, and actions just contains a "Remove" button.

And finally under this table I'll have a button with "Add another value".
I'm seeing this done through the Fields API, if I'm setting a field to allow unlimited values. But I want to build this my self, as I'm not using a field, but my own costum database.

How do I accomplish this through Form API?

Found the solution in AHAH

With AHAH you can dynamically add new fields to the form using JavaScript.
Be sure to read http://drupal.org/node/331941 with examples of implementations from e.g. the Poll module.


Adding tabbed content in D7 What module should I use to make a tabbed block bringing views, custom content or forms?

For example I want to have a
News | Twitter | Facebook | Feedback

Which would have a list of news (or a news block), twitter updates etc.
Feedback would have a form.

Any suggestions?

It sounds like you are looking for something like the Quicktabs module. I have an implementation here: http://gamebah.com/gsqrd/node/24.

You  will make a block for each tab (Twitter, Facebook, Feedback, etc.) and then using Quicktabs (under Admin > Structure > Quicktabs) you can add the blocks to a new tab set. It is very self explanatory but if you need more help, don't hesitate to ask.


Panels content not displaying on copied site I'm prepping to convert a large D6 site to D7, so I've copied everything from the server to my local Mac, something I've done a bazillion times w/o a problem.  Concurrently, I changed my dev environment from MacPorts to Homebrew, using PHP54 and MySQL from Homebrew along with the native Apache (2.2.22) on the Mac.  What I'm running into is that Panels content isn't being displayed at all.  I've tried two other sites of ours, one with Panels and one w/o Panels, and the one w/o Panels displays fine.

On my panels pages (using 6.3.9 of Panels), all of the panes are filled by Views content panes and nodequeues, so here's what I've done:

checked the nodequeues to make sure they have content (they do),
edited the view itself to make sure content is being returned (it
is).
cleared caches (I actually don't export cache_* table content
when I get the SQL dump from the server)
went through all of my Apache and PHP configs to make sure everything is set up the same.

The code I'm using is identical to the server (both git clones), and this exact same site worked fine before I switched to Homebrew.  Any thoughts on what would keep the panels content from being displayed like this?

Thanks.

Check your Apache error logs and see what errors are reported when loading the Panels page - this is an essential part of your debugging toolkit.

Are you really using PHP5.4? That is likely to be the issue. http://drupal.org/node/1469736 indicates that the published release of Panels is not PHP5.4 compatible, but the dev release may be.


Why would I want to use Universally Unique IDentifier (UUID) in Drupal? I see that a lot of people are using Universally Unique IDentifier (UUID). What is it? And, why do I want to use it with Drupal?

If you want to create an UUID for you content you should use the modules. UUIDs can be used for content staging and such.

The problem is that Drupal uses serial ids for the content (nodes), so if we have the same site installed different places, the id for the same content most likely will be different. (fx in one environment the node id might be 137, while it on another might be 153)
This makes it very hard to track changes on the same content in different environments. The idea with UUIDs is to create a id that is the same on all environments.

So you could have content writers work on a stage site, have it reviewed, and the put the changes out on the production server, without messing everything up in the process.


Drupal 7 Can a custom textarea render html without a rich texteditor enabled? I am using Drupal 7, (fairly new to module dev) here's my use case- I am trying to add a terms and conditions field directly within the user_registration screen. The Administrator sets the terms, so they have access to change the field values, but the authenticated user will not.

I am adding a custom field and when the field is loaded paragraphs, breaks, quotes are converted to html characters instead of rendering as an actual paragraph - I am assuming because the textarea isn't seen by ckeditor library? Im trying to display the field with the rendered paragraphs and breaks as this displays fine for admin users. It almost as if I need to specify rich-text

How would I do this?

function myModule_form_user_register_form_alter(&$form, &$form_state, &$form_id) {

 $form['field_agreement']['#access']=FALSE; //the default field is hidden from authenticated users

 //adding in custom field for auth users

 $form['Agreement'] = array (
  '#type' => 'textarea',
  '#title' => t('Terms & Conditions'),
  '#default_value' => $form['field_venue_agreement']['und']['0']['#default_value'],
  '#weight' => '10',
  '#description' => t('You must agree to our terms each time a new user is added'),
  '#disabled' => TRUE,
);

}

I didn't find the answer I wanted to find, but after careful examination of the form api, I discovered markup and it led me down the path of fooling the end user into thinking it looked like a field with some css manipulation. This is working for me

$form['Venue Agreement'] = array (
 ['0']['#default_value'],
  '#weight' => '10',
  '#markup' => $form['field_venue_agreement']['und'['0']['#default_value'],
  '#prefix' => '
',
  '#suffix'=> '
',
);


bypass a character limitation rule (webform) Maybe someone could help me ...

Ive got a webform with an input (postal code). I want its maxlength to be 5.

When users fill it, once the 5 digits entered, an autocomplete callback retrieves corresponding cities.

When a city is chosen, the input content is rewritten like "XXXXX - CITY".
Now the field length is more than 5.

When the form is submitted, it is not validated.

I would like to bypass the validation of this specific property (maxlength) ...

Is it possible ?

you will need to write your own validation function - borrowed from here:

Adding custom validation rules - Webform Validation hooks

Last updated January 7, 2014. Created by svendecabooter on September 11, 2010.
Edited by Liam Morland, wundo, crystaldawn. Log in to edit this page.

This page describes how to write custom validation rules for your webforms. This requires installation of the Webform and Webform Validation modules.

The following code should be implemented in your own custom module.

Adding custom validation rules
The following steps will let you add custom validators through your module:

1/ Implement hook_webform_validation_validators().
This hook implementation should return an array of validator key => options array entries.
The options array can contain the following configuration keys:

name (required): name of the validator

component types (required): defines which component types can be validated by this validator. Specify 'all' to allow all types

custom_error (optional): define whether a user can specify a custom error message upon creating the validation rule.

custom_data (optional): define whether custom data can be added to the validation rule

min_components (optional): define the minimum number of components to be selected for creating a validation rule

max_components (optional): define the maximum number of components to be selected for creating a validation rule

description (optional): provide a descriptive explanation about the validator
See function webform_validation_webform_validation_validators() in

webform_validation.validators.inc for a live example

2/ Implement hook hook_webform_validation_validate($validator_name, $items, $components, $rule).
This hook gets passed 4 parameters, which will allow you to react to your custom validator (or any other validator for that matter).
Explanation about these parameters:

$validator_name: this is the validator name (i.e. array key as entered in hook_webform_validation_validators)

$items: array containing user submitted entries to be validated.
$components: this array contains the definitions of the webform components in your form

$rule: this array contains the details of your validation rule
See function webform_validation_webform_validation_validate() in webform_validation.validators.inc for a live example

Additional hooks
The hook hook_webform_validation($type, $op, $data) can be used to react on various webform_validation based actions.`

$type - possible values: 'rule'

$op - possible values: 'add', 'edit', 'delete'

$data - array with rule data in case of $op add/edit, rule id in case of $op delete.

The hook hook_webform_validator_alter(&$validators) can be used to alter the array of validators that is being generated by hook_webform_validation_validators().

$validators - array of validators as supplied by modules implementing hook_webform_validation_validators().
Example

<?php
/**
 * Implements hook_webform_validation_validators().
 */
function idvalidation_webform_validation_validators() {
  return array(
    'validate_id' => array(
      'name' => "Validate ID",
      'component_types' => array(
        'textfield',
      ),
    )
  );
}
/**
 * Implements hook_webform_validation_validate().
 */
function idvalidation_webform_validation_validate($validator_name, $items, $components, $rule) {
  if ($items) {
    switch ($validator_name) {
      case 'validate_id':
        $valid_ids = array(1, 2, 3); // get this from database source instead
        foreach ($items as $key => $val) {
          if ($val && (!in_array($val, $valid_ids))) {
            $errors[$key] = t('%item is not a valid ID', array('%item' => $components[$key]['name']));
          }
        }
        return $errors;
        break;
    }
  }
}
?>


How do I use "drush make" modules with a local module code? I got to love the workflow "drush make" gives us. I am sure there are others who would want their development code to be put into a make file with it not being ready for drupal.org, for example, deploying a new development testing instance of the site quickly with a bash script or from what I have seen in Aegir.

It seems the current workflow that may suit this would be to utilize a git repository of your development code. However, my development machine is Windows 7, and I would like to use "drush make" in a virtual box with an Ubuntu server instance.

You can set up local domains and local git repositories or tarballs like so:

projects[my_module][type] = "module"
projects[my_module][download][type] = "file"
projects[my_module][download][url] = "http://localhost/my_module.tgz"
projects[my_module][subdir] = "contrib"

Then in your build script you could just recreate the tgz


Issues with theme on moving drupal website to new server I have never used drupal before, and just have been tasked with moving a drupal website to a new server. I've moved the files and database successfully - had a bit of a fight with clean urls which were a pain to switch off, new host did not have them enabled.

The website is mostly working fine, except themes. Anything theme related (images etc) is not loading. If the direct url of a theme item is placed into the browser address bar it is opened successfully. I have a feeling its to do with the first item after the temporary address of the new server, the /~balliolj part, but have no clue where to fix this.

Old website: http://www.ballioljcr.org/
New website: http://31.193.134.90/~balliolj/

I'm trying to get everything working as before prior to moving the domain, hence the temp address.

Any input on how to fix this would be greatly appreciated

At https://groups.drupal.org/node/104694 having a tilde in the url was successfully solved usign RewriteBase /~user on the .htaccess file.


How to delete an image I uploaded? When I delete an image I previously uploaded into an Image field, the file stays on my server. It takes up space and remains publicly viewable.

Is there an easy way to get Drupal to clean up after itself by deleting uploaded files that are no longer in use?

Images should be deleted automatically during cron runs, if they are not used anymore. Meaning, their file_usage count is 0.


How to programmatically change a Views page's html  separately to its on-page title? Similar to Views: how to programmatically change Views title?, I want to update the title of a Views page using logic/data only possible in PHP.

However, I want this to update only the appropriate
 part of the <title> of the HTML  without  mirroring the change in the displayed title in the 's
.

To illustrate, imagine a view with some exposed filters that are used for navigating a product catalogue. Currently, every filtering of this page has the same titles:

<title>Products | My site name</title>
...

Products

I've written some code requiring access to $view->exposed_input that generates an appropriate string based on exposed filter choices (for example, "red, low cost, good condition"), similar to Using exposed filters as part of the rendered page's title. I want these in the html head title, so each navigable URL has a unique title with appropriate keywords for the content. I don't want them in the
, however, because they're already clearly visible in the exposed filter page UI and I don't want to duplicate the information. I want it to look like this:

<title>Products: red, low cost, good condition | My site name</title>
...

Products

Things I've tried:

Everything on that linked question applies to both the head and body titles

<title>Products: red, low cost, good condition | My site name</title>
...

Products: red, low cost, good condition

drupal_set_title() doesn't work at all from any of the Views hooks I've tried, presumably because the view overrides this further down the line. I've tried:

hook_preprocess_views_view
hook_views_pre_render
hook_views_post_render

Setting $vars['head_title'] in hook_preprocess_views_view also doesn't work, presumably for the same reason: Views overrides this.

Someone commenting on the hook_views_post_render API page with the exact same problem as me 3 years ago reports that it still doesn't work if you pass the variable to through to hook_preprocess_html and apply it to $vars['head_title'] from there

I think what you're looking for is hook_preprocess_HOOK where HOOK is either html, page or both.


Set multiple items for an argument in embeded view I'm using this code to display a view inside a node:

$view_args = array($node->field_page_cck[0]['value']);
$view = views_get_view('my_view');
$view->is_cacheable = FALSE;
$view->set_display('default');
if (!empty($view)) {
    print $view->execute_display($display_id , $view_args);
}

The argument is set with the option Allow multiple arguments to work together.

I tried with:

$view_args = array($node->field_page_cck[0]['value'], $node->field_page_cck[1]['value']);

but no luck.

I also tried to convert to a string like this: argument1+argument2+.... or argument1,argument2,.... still no luck.

Any help, please?

The argument itself needs to be configured to take multiple items. There is a checkbox which says "Allow multiple terms per argument".

After that you should be able to have a string with commas separating them

$view_args = array($node->field_page_cck[0]['value'] . ',' . $node->field_page_cck[1]['value']);

Note that you are still passing an array, but the first item is a comma separated string.


What is the best way to minify drupal's aggregated javascript (automatically)? Have just run Google pagespeed over my newly created drupal 6 site, and it reports:

Minifying the following JavaScript resources could reduce their size by 15.6KiB (12% reduction).

    Minifying http://[sites]/sites/default/files/js/js_9f19b87ffb72ca233ea7e45dda2f20f9.js could save 15.3KiB (18% reduction). See optimized version or Save as.

The above file was generated through drupal's default JavaScript aggregation method, but apparently it could be 18% smaller (which is a big deal for this site). What approach is considered the best when it comes to minifying JavaScript on a drupal site without breaking any existing code?

I created a new module to tackle a lot of the aggregation issue & I hope to get a large chunk of it into D8; and yes it's a D6 module: http://drupal.org/project/advagg. Uses the jsmin+ lib for compression of JS and the CSSTidy lib for CSS compression. Main advantage of this is the css/js aggregate file doesn't change names unless it needs to; these files also have a 1 year cache lifetime & has imagecache generation so 404s to your CSS file should be a thing of the past.

Update: AdvAgg 7.x is being developed and comes with minification of JS as an optional sub module. Other D7 options:
http://drupal.org/project/speedy
http://drupal.org/project/uglifyjs


Issue with options in ICME file uploader missing I'm using Drupal 8 and I added IMCE so that we could upload files. But, some things seem to be missing. First I can only upload images now, there's not option to search the website directories which means that if I have a icon I use in many places I have to upload it each time. You can search the website directories when you link to files though.

Secondly there are no link options like choosing targets like _blank. Is this the way the module works or is something conflicting with it?

I have the same issue. This is a big headache.
We want to make all off-site (external) links have target = _blank.

Solution: The CKeditor Anchor Link module, anchor_link, adds the other link properties (as it existed in Drupal 7). You have to edit the text formats and include the new buttons that anchor_link creates. However, these buttons are identical to the ones created by the Link module (in core D8), so make sure to remove them and drag the new ones (from anchor_link) in.


How to migrate from Commerce Kickstart to Drupal Commerce? What’s the recommended way to migrate users, orders, products including products variation... simply everything to Drupal Commerce 7?

tl;dr - Essentially, you're building a new theme on top of a site that is populated with content:

  Find or create a new sub-theme (that doesn't use omega_kickstart as a parent).
  Create a new home page.
  Create new blocks for menus and taxonomy terms.
  Re-implement any social features you were using.
  Examine and fix any order, user, or content related problems.
  Enable the new theme and configuration.
  Disable all of the kickstart modules.
  Test and repeat until you're happy with the results.

More information:

Let's say you disable all of the Kickstart-specific modules by running these commands:

drush -y dis commerce_kickstart_block commerce_kickstart_blog commerce_kickstart_comment \
  commerce_kickstart_inline_help commerce_kickstart_menus commerce_kickstart_merchandising \
  commerce_kickstart_order commerce_kickstart_product commerce_kickstart_product_ui \
  commerce_kickstart_reset commerce_kickstart_search commerce_kickstart_slideshow \
  commerce_kickstart_social commerce_kickstart_taxonomy commerce_kickstart_user

And then you can disable the other modules:

drush -y dis commerce_kickstart_help commerce_kickstart_migrate

Here's a picture of what your site's homepage will look like if you afterwards (assuming you're still using the same base theme):

You'll find that:

All of the home page content is gone.
The menus are gone.
The admin menus are damaged but usable. (There appears to be a one-pixel line at the top of the page that allows you to click on menu items unless your screen is extremely wide.)
All of the theming done for products is gone.

The good news is that:

All of your content is still there.
Links to existing products will work (albeit not as pretty).
Administrative functionality is A-okay.

Given the current situation, you'll probably want to go ahead and create a new theme. I suppose you could sub-theme the existing theme, but I'm not sure why you would given that everything is now broken.

The homepage will also need to be replaced. Views, panels, or a node would all be good choices, depending on your needs. The rest of the blocks and menus will also need to be created as blocks and re-added to your theme, but you'd need to do this anyway so it's probably not a big deal.

Any other customizations around comments, users, orders, etc. will need to be reevaluated and implemented as you see fit.

Once you're happy, you'll just need to test, test, and test some more to make sure you've cleaned up all the edges.


Custom theme for module? I am creating a new module in drupal 7 called coolmodule and I'm trying to figure out how to bind content to the file sites/all/modules/coolmodule/coolmodule.tpl.php file.  Here's the block view code in my coolmodule.module;

function coolmodule_block_view($delta = '') {

    $block['subject'] = t('My Special Module');

    $block['content'] = theme('coolmodule', array('myvar' => 'helloworld'));

    return $block;
}

But for some reason, pages with this block does not render sites/all/modules/coolmodule/coolmodule.tpl.php.  What am I doing wrong?

you are missing a hook_theme() function

see you defined a theme for your block by using:

$block['content'] = theme('coolmodule', array('myvar' => 'helloworld'));

but you never told it how to relate your theme with the template file, this work is done in hook_theme() function.

function coolmodule_theme() {
    $items['coolmodule'] = array(
        'template' => 'coolmodule',   // here comes your template name
        'render element' => 'content'
    );

    return $items;
}

Don't forget to clear your cache


Node export to POT for translation I think I'm missing something pretty basic here.

I'd like to be able to export all node content as POT files to send along with the other POT files for translation.

I have i18n installed, and a handful of dependencies and "Translation template extractor".

I am able to export nearly everything on the site (menus, taxonomy, strings from modules, etc) but I do not see an option to export "nodes" or "node content".

Is there a way to do that?

No, there isn't.

I maintain the Translation Management Tool project, that offers a way to export nodes and other translatable content as XLIFF. There is no POT export option but it should be possible write an export format for that.


Programmatically set active facets on non search page I'm using facet api with search api and SOLR. This all works as expected.

For non-search pages I use the views facet block and this displays the facets as required.

What I want to do though is have some of the facets pre-selected on non search pages.

For example:
I have a views page: example.com/london I would like to show facets with 'london' preselected as if I was on a search page for london.

I've tried using a contextual filter on the views facet block and it half works. It shows only the selected city BUT the facet checkbox isn't checked; and if I click any of the other facets it does not show results filtered by city...

Any suggestions how I can get this to work?

So, despite the overwhelming response ;) after about 20 hours of banging my head against the desk I have this figured. I'm not sure if it is the most efficient way to do this, but I don't think the overheads are massive.

I did end up hooking into the adapter class but I couldn't find a facetapi hook that was called at the right time. In the end, I used hook_init.

You will need to get your parameters ($SOME_ID_VARIABLE) into the code. I used the current URL via request_path() and got node IDs from this.

The important bits of the code looks something like:

function MY_MODULE_init(){
  $searcher = 'search_api@MY_INDEX';
  $adapter = facetapi_adapter_load($searcher);
  $param_arr = array();

  $param_arr['f'][] = 'field_WHATEVER_FIELD:'.$SOME_ID_VARIABLE;
  $param_arr['q'] = 'VIEWS_SEARCH_PAGE/search';
  $adapter->setParams($param_arr);
}

Oh, and you still need to use a views facet block to get the facets to show up on the non-search page. I have used some caching on this block and everything still seems to work as expected.

The info on this page got me going in the right direction.


How to delete block on hook_uninstall? I have a custom module, mymodule, that will create custom blocks, block_test and block_test2 on mymodule_install().

When the module is uninstalled, I want to remove any blocks created by mymodule. How would I delete the block generated by a module being uninstalled?

drush command (local dev):

drush pmu mymodule -yv

mymodule.uninstall()

function mymodule_uninstall() {
  // Delete Blocks generated by module.

  /** @var \Drupal\Core\Entity\EntityStorageInterface $block_storage */
  $block_storage = \Drupal::service('entity_type.manager')->getStorage('block');
  /** @var \Drupal\block\Entity\Block[] $blocks */
  $blocks = $block_storage->loadMultiple();
  foreach ($blocks as $block) {
    // I am stuck here.
  }
}

Yes, then the best thing would be to follow the enforced config dependencies part above, if you create the content blocks with a fixed uuid then you can just put the block config entities in your config/install folder, with the config dependencies as explained there and it should be uninstalled automatically.

At least the config entities, if you want to delete the block_content entities too then load them by UUID with $block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', 'YOUR_UUID'); $block_content->delete()


http request with authentication I'm trying to get data out of an .NET Web API into drupal in code. Everyting is working when the Web API is not secured/authenticated using the code below.

$request = drupal_http_request('http://10.129.132.253/StappAncor/api/person/1');
$items = drupal_json_decode($request->data);
dpm($items);

But when I publish the Web API onto my live server (behind authentication and https), I can't use the default drupal function drupal_http_request because it only supports basic authentication.

Any suggestions? Are the other WebClients I can use?

When Drupal requests are not enough, I found cURL a good way.

PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

It can either be used directly, or via cURL HTTP Request wrapper module.

This is a module intended for developers, as it provides just one API to call: chr_curl_http_request() (use curl_http_request() for versions 1.5 and earlier).
The function chr_curl_http_request() is an alternative implementation of Drupal core function drupal_http_request() using cURL.
The function intends to be backwards compatible with drupal_http_request(), by accepting the same parameters in the same form and by returning the response in the same format.


How to schedule a Rules component at the end of the month? The users on my website can flag articles with Flag. I want them to be able to do this exactly once every month, but they do not have permission to unflag content. Therefore, my plan is to create a Rule that triggers when an article is flagged and that schedules a Rules component that takes care of the unflagging.

How can I schedule this component at the end of the month, i.e. which value should I add in the field Scheduled evaluation date of the action Schedule component evaluation?

Introducing last day of 23:59 works for me (last day of is the last day of the current month, and 23:59 just before the day ends). You can see the full reference of DateTime relative formats here: http://php.net/manual/en/datetime.formats.relative.php

In general, you can pass anything recognised by strtotime() as the scheduling date.


Views argument settings Views 2 for Drupal 6 had settings for the arguments passed to a view.
Does Views 3 for Drupal 7 still have those settings? Have those settings been renamed, or removed?

This is the partial screenshot that I see when I edit the taxonomy term view (the screenshot appears blur because I resized it to 70% of its original dimensions).

If this makes any difference, the screenshot is for the development snapshot of Views (7.x-3.x-dev), used together the development snapshot of Chaos Tools (7.x-1.x-dev).

The argument settings have not been removed; they have been renamed, and in the actual development snapshot they are called Contextual Filters.


Related Content entity query I'm a little new.
I need to create a view for related content between different content types, some have same taxonomies field other no. It is a multi language site. So, the view was a little complex, then I am trying with EntityQuery. This search needs to be updated each time that the user update a taxonomy

How can I present the result of my entity query in a node? in a custom block? where can I put my code ?

I asking for a structure or a way to do it this.

How I solved my issue with this structure.

I created a manager here my_module/scr/Pluging/myManager.php

Here I have a function with a entityQuery that return a list of nodes.

I created a block here my_module/scr/Pluging/Block/myBlock.php

Here in my build function a call my function in myManager.php and I pass the name of the theme, and a variable with my list of nodes

I updated my .module here my_module/my_module.module

In hook function my_module_theme()
I add my theme and varibles to be pass.

I created a twig here my_module/templates/block-related.html.twig

Here I just do a for to display all field of each node.

Then in my admin/stucture/block I added my block to display in Content section  in specific content type.


cannot remove $base_url address from a link There is a Ads block in my website in which some websites logo and their address are placed in there. I created a content type for it , called Ads (and also a view Ads__view). it has two fields : 1.link 2.logo . I created a slide show using slideShow module and it slides the logos. I want my website to redirect to these websites when user clicks on any of them, so I created a page called views-view-fields--Ads__view.tpl.php and this is the code of it :

<?php
$address = strip_tags($fields['field_Ads_link']->content);
?>
<a href="<?php print $address ?>"><?php print $fields['field_Ads_photo']->content; ?>

the problem is $base_url of my website is attached at the beginning of the  ($fields['field_Ads_link']->content for example www.google.com will be www.mywebsite.com/www.google.com . how can I remove this attachment ?

You need to prefix http:// with your link. If you will not add prefix http:// with your link, Drupal will treat this as internal url of Drupal site.

So, you should add url http://www.google.com in your content.

Or you can use Link module to create a link field.

  With link module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.


Is there any security consideration with webform and Salesforce API? We are implementing the Salesforce webform module for our client and they are asking us if there are any security issues to consider by having SOAP installed on their server.

(The Salesforce API requires SOAP to be installed for drupal to communicate with it.)

PHP SOAP will not introduce any security issues in itself; it's more about how it is used. If it's used via unencrypted HTTP, for example, the data could be intercepted, like any other data. If you need the data to remain secure, then obviously this would be a consideration.


Custom content type and custom list view Hi totally new to Drupal and I've managed to set everything up I needed to. Custom content types, taxonomies etc.

Firstly I'd like to know how to link to a page which will display all the posts in my custom content type.

If you're wanting to build "lists" of things then I would check out the Views module. You will create a new content view and filter by the new content type. If you're struggling building a View just google for 'drupal views tutorials' and there will be a ton to show you how to build things with views.


Listing a Members of a Household I am building a Church Management System, I am working on the members database at the moment. I have 2 contact types, Individual & Household.

The individual has fields for personal details & contact details one of which is a field for selecting which Household they belong to.
The Household has fields for the address of the household & contact details for the household.

When viewing the content for an Individual, I want to be able to click the listed Household which takes me to a page that shows me the details of the Household. e.g. Location, Contact Details & a list of the members of the household.

Is there a way to just put this into the Household Content type as a field, or how do I do this in Views?

I can set up the View to display the general details, but I cannot work out how to have it to show only the clicked household from the individual page and the individuals associated with the Household.

Thanks in advance.

Im still a bit confused I attempted pizzasynthesis suggestion and couldnt get it to work, and I have changed my thinking a bit. I am including screenshots of my config if anyone can give me ideas and/or suggestions on what to do would be awesome.

I am now thinking of using a block view that is only shown in the Household content type page and lists the Individuals of that Household(not sure it is possible to do but please tell me how best to do it).

Individual Content Type:

Test Member Edit Contact Details:

Household Content Type:

Household Edit Details:

Household Members View Block:

Individual:

Household:

I only want to be able to see the Individuals listed for that specific Household.

Any help would be greatly appreciated.

OK Heres where I am at now.

Block View:

Household:

Ive done what pizzasynthesis said and this is what Ive got.

When you want to create relationships between various Content Types, the first solution many go to is Entity reference.

  Provides a field type that can reference arbitrary entities:

It creates a new field type available on all entities that can reference entities of other types. You can specify, with granularity, what types of bundles to reference (in this case you'd want to select the bundle 'Node').

Once you've created this field, you can now reference the Household directly through the node edit form. From that point forward, in Views, you can create a Relationship to the Content being referenced through the entity reference field (search entity after Adding a new relationship to find this), and then you can render any type of attached Content you wish (the Title as a link to the Node, via field settings; the entire rendered Node, etc.) through either Fields (in Views) or using Display Suite.


Cannot create release for my contributed module I am trying to create a release for my contributed module

https://www.drupal.org/project/taxonomy_facets

I created a tag an that seemed to get trough OK:

git push origin tag 8.x-1.0-RC1

Total 0 (delta 0), reused 0 (delta 0)

To git.drupal.org:project/taxonomy_facets.git

 * [new tag]         8.x-1.0-RC1 -> 8.x-1.0-RC1

I am on the right branch:

git branch

  7.x-3.x

8.x-1.x

But when I go to "Add new release" page:

https://www.drupal.org/node/add/project-release/1334080

In the select "Git release tag or branch" I do not see my release, I only see 7.x branch?

Is there a Drupal git suport email, I tried IRC but no luck, I also tried Drupa forums
https://www.drupal.org/forum/support/module-development-and-code-questions/2017-12-08/cannot-create-release-for-my

There is just a small change that you need to make. The projects on drupal.org are expected to have the releases in lowercase. This is done to support the project infrastructure which is in place like update status and the testing bot.

You should be able to create a new release with a tag like 8.x-1.0-rc1

More info here : https://www.drupal.org/node/1015226


problem with templates in custom module I wrote a simple module that uses hook_theme().

/**
* Implements hook_theme().
*/
function test_theme() {
  'upload_page' => array(
  'template' => 'templates/upload_page',
  'arguments' => array(
    'uploadurl' => NULL,
    'options' => NULL,
    'title' => NULL,
    'user' => NULL),
   )
}

I still have an error.

  Warning: include(./sites/all/themes/test/templates/upload_page.tpl.php): failed to open stream: No such file or directory

How do I change this path to ./sites/all/modules/test/templates?

Drupal won't look for the template in a theme path unless

You've added this code to a theme instead of a module or
You've put your module in the theme folder instead of sites/all/modules, and then perhaps moved it once installed (less likely I think).

If you've done either of these I'd advise fixing that problem and putting the code/module where it's supposed to go.

If you're too invested at this point, though, you can use the path argument to hook_theme() to provide a static path to your theme's implementation folder:

'upload_page' => array(
  'template' => 'templates/upload_page',
  'arguments' => array(
    'uploadurl' => NULL,
    'options' => NULL,
    'title' => NULL,
    'user' => NULL
  ),
  'path' => drupal_get_path('module', 'test')
)

The docs I've linked to are for Drupal 6 as I assume from your code that's what you're using; if you're using Drupal 7, the arguments property should be changed to variables.


how to map fields in feeds module with csv that has no headers? Can feeds module still know how to map the fields correctly even if there are no headers in a .csv file. I am trying to migrate sample data from database which i exported to a .csv file through phpmyadmin. i am testing the feeds module if it can handle large file migrate.

if the answer is no, can i manually input the headers in the excel files? or it has to be exported again with headers?

The Feeds module support CSV files without column headers.  On admin/structure/feeds/foo_importer/settings/FeedsCSVParser, you just need to select "No Headers".  Then on admin/structure/feeds/foo_importer/mapping, you use the column numbers for the source.

Be careful when entering the Name of source field. Your first column is named '0', the second '1' and so on.


How to configure the Answers module to organize questions by product subpages? I want to use a question and answer system for different subpages. I have many products and on each product page should be a question and answer system. The "Answers" module is good, but I can only configure it for general use. Users can see all questions and answers there.

I want to configure it so that they can only see questions and answers to the specific product (subpage), like these relative paths:

/category/product1/question1
/category/product1/question2
/category/product2/question1

How can I configure the Answers module to get this result?

I'm assuming you're using the most recent 7.x.-4.x version of the Answers module. The new demo site uses a further enhanced version of the most recent dev release. For example the views have been enhanced and will be pushed to D.O shortly. These views are available already in Views Export format via files attached to comment #5 in issue #2783513).

Here is a screenprint of the (new) view to show all the questions:

Note the Topics column in the above views result: it's just a term reference field, added as an extra field to the "Question" content type (which comes with the module). With that in mind, you could use a similar approach:

Step 1: Add a similar (mandatory) field, I'd recommend an Entity reference field. So that when a question is created the question author indicates which product your question is about.
Step 2: Enhance the view to add a filter related to the product.
Step 3: Adapt the path of your enhanced view that matches your requirements.

Note: regarding the "...so that they can only see..."-part of your question it may be sufficient to just filter the view as described above. But if you actually want to restrict access to any of the questions, you can use the access method/module of your choice to limit access to the Question nodes. Red flag: be aware of the "Disable Query Rewriting" discussion (and tune that views setting if needed).

Disclosure: I'm a co-maintainer of this module.


Webform field options missing Entity Reference? We're using Webform 3.27 in Drupal 7 (not my call, don't yell at me) and it looks like one of the field type options should be Entity Reference, but we don't have that option. Not sure what's going on there.

Ultimately what I'm trying to do is add an Entity Reference select field that, when an option is selected, will populate up to four other existing fields (like Entity Reference Autofill works in a Content Type). Is that even possible using Webform?

This module might do what you want, webform references.

From description,

  Provides a webform component that can reference a node/term/user in webform. It provides "Select List", "Autocomplete", "Checkbox" and "Radio" as widget.
  A view with entityreference display can also be used to get the list as options.


Difference between field form hooks for settings I created a field for my module and now I want to create settings for this field.

Now I found four hooks:

hook_field_settings_form
hook_field_instance_settings_form
hook_field_widget_settings_form
hook_field_formatter_settings_form

What is the difference between these hooks?

I think "formatter_settings" is for settings to change the later display of the output on the entity. Right? And the other hooks?

Let me explain to you briefly what each of them does. Basically a field has two prime components, one is widget and the other is formatter. The widget is the input part( like checkbox, select list, textfield). This helps field to grab data from the user. The other one is formatter. Formatters are responsible for how output is rendered by that field.

Now regarding the hooks you mentioned:

I will try and help you visualise these by comparing to the steps which you encounter while creating a field.

hook_field_settings_form - this is the global settings form, the first page which you encounter when you create a field.
hook_field_instance_settings_form - this the instance level field settings form, usually same options as global settings form but applicable to each instance.
hook_field_widget_settings_form - This is the settings form for the widget, which i have already described above.
hook_field_formatter_settings_form - This is the settings form for the formatter. This exposes options that will be used to render the value of the field.

Observe closely the forms and steps that come up while you create a field through UI in Drupal and you will gain more insights on these components. hope that helps.


How to load conditionally a script depending on whether element exists in DOM? I have a Drupal.behaviors.leftmenusticky script that converts a left menu to a sticky menu (100% height,position fixed and the like) but I want to drupal_add_js it only if the menu actually exists in the page shown.

(function ($) {
  if ($(".full-height").length > 0 ) {
  Drupal.behaviors.leftMenuSticky = {
      attach: function (context, settings) {
        var contentHeight = $("#main").innerHeight();
        var viewportHeight = $(window).height();
        var offsetTop = $(".full-height").offset().top;
        if (contentHeight < viewportHeight) {
          jQuery(".full-height").height(viewportHeight-offsetTop);
        }
        else {
          jQuery(".full-height").height(contentHeight-offsetTop);
        }
        leftColumnResizer();
        $(window).bind("resize", leftColumnResizer);
        function leftColumnResizer () {
          var toto = $(".region-sidebar-first").width();
          $("#block-paddle-menu-display-management-level-4").css("width", toto);
        }
      }
    }
  }
  else {console.log('notfound');}
})(jQuery);

The Javascript way would be to check whether or not the class I'm targetting exists or not:

  if ($(".full-height").length > 0 )

but 1) I don't know where to place this check exactly and 2) I'd prefer to have a template.php way of doing that by making use either of settings or of context...

Is this possible?

drupal_add_js() happens server-side, it can't possibly have exposure to what's in the DOM (unless you pass that info back to the server with AJAX, but that would be a very weird thing to do). The correct solution is the javascript one as you've mentioned.

You want that code to run whenever the DOM is ready, so in the Drupal paradigm immediately inside the attach function of your behaviour:

(function ($) {
  Drupal.behaviors.leftMenuSticky = {
      attach: function (context, settings) {
        if ($(".full-height").length > 0 ) {
          var contentHeight = $("#main").innerHeight();
          // ...


Main menu alias links my current menu links are generated but those are not the alias urls as follows:

theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('class' => array('nav nav-pills'))));

I would like that the menu generated is with alias urls instead the 'content/name-of-node'. How do you generated menu with alias path links? Is there function i can get only array of links for the main manu, so i can parse out the html myself? Thank You for help

p.s. This is Drupal 7.

Thank You Chris...the menu_load_links() was exactly what i was looking for. Here is my custom main menu array that i later parse in html teplates as needed:

$mainMenuArray = menu_load_links('main-menu');
$finalMainMenu = array();
foreach($mainMenuArray as $key=>$menuItem){
    $finalMainMenu[$key]['active'] = false;
    $linkPath = $menuItem['link_path'];
    $linkPathAlias = drupal_get_path_alias($linkPath);
    $currentId = $vars['node']->nid;
    if(drupal_get_path_alias("node/$currentId") == $linkPathAlias)$finalMainMenu[$key]['active'] = true;
    $finalMainMenu[$key]['url'] = $linkPathAlias;
    $finalMainMenu[$key]['title'] = $menuItem['link_title'];
}
$vars['mainMenu'] = $finalMainMenu;

I have this in template.php hook 'theme_preprocess_page' where the $vars['node'] is used to determine what is the current node loaded. I hope it useful for someone. Thank you Chris for answering my question.


How to display the values after submit in drupal 7 I have a three form fields like Name,phone,email now after inserting the values in my db i want to display the values into same page or another page like
 Name:XXXXXXXXXXX
 Phone:5545445454
 email:yyy@some.com

how can do this in drupal7

You can use the function hook_form_FORM_ID_alter to do that.

Just replace the FORM_ID with the ID of your form.
Lets say the id of the form is my_custom_form, then the values could be printed as,

function MODULE_form_my_custom_form_alter(&$form, &$form_state, $form_id){
  //add a new function(submit handler) on submit button.
  $form['#submit'][] = 'new_submit_function';
}

function new_submit_function(&$form, &form_state) {
  // the $form_state['values'] array contains all the
  // values from the fields of the current form stored in it
  drupal_set_message("name : " . $form_state['values']['name']);
  drupal_set_message("phone : " . $form_state['values']['phone']);
  //and so on.
  //the message will be displayed on the page after form submit
}

If you are not sure how to find the id of the form, then use hook_form_alter to do that, e.g.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
}

this would print the form id of every form you are on, so that you can use the id of the form you wish to change and perform a hook_form_FORM_ID_alter to change anything you wish :-)


Check if the connection to the database is available I have 2 databases, the first one with Drupal and the second one with external data. In a controller I want to read data from that second database and display it.
As the external database can be available or not, is there any method to check if the connection is available or not?
My code is working, but if the DB is not available (or unset) I get the following error:

Drupal\Core\Database\ConnectionNotDefinedException: The specified
database connection is not defined: schedules in
Drupal\Core\Database\Database::openConnection() (line 364 of
core/lib/Drupal/Core/Database/Database.php).

Code:
abstract class AbstractSchedulesRepository {

  /**
   * Schedules repository target.
   */
  public const SCHEDULES_REPOSITORY_TARGET_DATABASE = 'default';

  /**
   * Schedules repository key.
   */
  public const SCHEDULES_REPOSITORY_KEY_DATABASE = 'schedules';

  /**
   * Drupal\schedules\Repository\SchedulesCache definition.
   *
   * @var \Drupal\schedules\Cache\SchedulesCache
   */
  protected $schedulesCache;

  /**
   * Drupal\Core\Language\LanguageManager definition.
   *
   * @var \Drupal\Core\Language\LanguageManager
   */
  protected $languageManager;

  /**
   * Drupal\Core\Database\Connection definition.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * Constructor.
   *
   * @param \Drupal\schedules\Cache\SchedulesCache $schedulesCache
   *   Schedules cache.
   * @param \Drupal\Core\Language\LanguageManager $languageManager
   *   Language manager.
   */
  public function __construct(SchedulesCache $schedulesCache, LanguageManager $languageManager) {
    $this->schedulesCache  = $schedulesCache;
    $this->languageManager = $languageManager;
    $this->connection      = Database::getConnection(self::SCHEDULES_REPOSITORY_TARGET_DATABASE, self::SCHEDULES_REPOSITORY_KEY_DATABASE);
  }

is there any method to check if the connection is available or not?

If you mean class method, then no, because it wouldn’t be necessary. You can simply catch the exception, which will tell you immediately that the connection was not successful:
try {
  // Code using a database connection
} catch (ConnectionNotDefinedException $e) {
  // No database for you
}


Complicated views with dates I need a somewhat complicated view setup. I don't know if I can even do it with views...

I have a page, we'll say the url is "/example". When a user hits "/example", they'll see a main content area and a sidebar. The main content area has a list of nodes. The one requirement I can't seem to figure out is how to have this list be limited by time, rather than number. I want the last 3 months of nodes to show up, not a set number.

Then in the sidebar is an "archive" view (seems best to me to just have it be a separate view from the main one, even though it concerns the same content) where the years should be listed (if they have nodes) and under each year the months should be listed (again, only if they have nodes).

Such as:

2012
February
March
2011
April
December
2010
January

I see an example "archive" view in the default views, but it's not quite set up like this.

I know views is very capable, but can it do this?

For the second view , I think it's possible using agregation : you will have to select two times the field dates , the fist one will be displayed as year and second one month , then use group by the first date field. If it doesn't work then in the fields settings you will have to separate the date as one field for year , and one field for month , then you will have to group by the year field in the views.

Here is a great tutorial from nodeone.se of how to use agregation in drupal 7  :


Show form errors before opening AJAX modal I have a form that adds a product to the cart.

The form uses AJAX to open a modal when the form is submitted.

I want to show form errors (if any) before the modal opens and avoid opening it if there are errors.

Here's my form submit element:

$form['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#ajax' => [
    'callback' => '::submitAjaxForm'
  ],
  '#attached' => [
    'library' => ['core/drupal.dialog.ajax'],
  ],
];

My submitAjaxForm:

public function submitAjaxForm(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new OpenModalDialogCommand(
    $this->t('Product added to cart!'),
    [
      '#theme' => 'some_theme',
    ]
  ));

  return $response;
}

And my submitForm:

public function submitForm(array &$form, FormStateInterface $form_state) {
  // Add product to cart.
}

I have tried by adding this code to the AjaxSubmit but it only shows the error messages once the page has been reloaded.

if ($form_state::hasAnyErrors()) {
  foreach ($form_state->getErrors() as $error) {
    $this->messenger()->addError($error);

    $message = [
      '#theme' => 'status_messages',
      '#message_list' => $this->messenger()->messagesByType(MessengerInterface::TYPE_ERROR),
    ];

    $messages = $this->renderer->render($message);

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#result-message', $messages));
    $form_state->setRebuild(TRUE);

    return $response;
  }
}

How can I show the errors without having to reload the page?

I see two things that stand out to me:

1) Setting the '#name' attribute on the submit button. You should never do that. I've learned over the days that there is always a better way to do whatever you're trying to do when setting the #name attribute, and setting it causes some wonkiness. This may be why your form is not rebuilding.

2) You are rendering your status messages in a D7 way. Use this instead:

$messages = ['#type' => 'status_messages'];
$response->addCommand(new PrependCommand('#target-div', \Drupal::service('renderer')->renderRoot($messages)));
It looks weird, because the messages aren't being retrieved, but by setting the #type to status messages, Drupal will handle the retrieval in the background. This is probably why you are seeing some funkiness with the messages.


Ctools nested modals I am familiar using ctools and modal forms. But now I have to implement multiple nested modal forms.
I have a link "Edit contact", this opens a modal form. At the top of the form I have another link "Delete contact", which opens a second modal form which asks the user if he/she is sure if he/she wants to delete the contact.
The response of the first modal form (as expected) is in JSON format:

This works nice and easy.
When I click "Delete contact" (second modal form), the response is HTML:

Because of this reponse I get following error:

Help? :)

I think you need to create your own ajax handler for this. The idea would be to check if an existing modal exists and rather than add a new one, simply run a replace in your existing one. If non exists, you'd need to setup a new modal.

The other approach you can take, is rather than just forcing it to opena new one, send an ajax request to close the existing one and then present the new one.

Either way, I do not believe there is an easy or straight solution for this particular problem.


Default Billing Information on PayPal site using WPS I'm looking for a way to default the Billing Information on the PayPal site when using PayPal WPS to process my payments in Drupal Commerce (v7). Currently, I have the Billing Information defaulted correctly on my Drupal site from the user profile so the customers do not have to enter it again during checkout (already entered when they registered), but do not want them to have to fill their Billing Information on the PayPal site once redirected during payment processing.

I have done this before when creating my own "home-grown" solution using the simple Pay Now button at PayPal by setting input form fields on the page that submits the form to PayPal.

<input name="first_name" type="hidden" value="frank" />

It would be a far better experience for users that do not have PayPal accounts to have this information defaulted on the "Pay with a debit or credit card" section of the PayPal page.

Thanks for any help!
Frank

Thanks for your helping clues.
I'm using Drupal Commerce V7.x-1.8 with drupal 7.26 and commerce_paypal WPS 7.x-2.3.

I made a custom module named my_module. Code Below :

function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $user = user_load($order->uid);
  $profile_id = $order->commerce_customer_billing['und'][0]['profile_id'];
  $profile = commerce_customer_profile_load($profile_id);

  $data['first_name'] = $profile->commerce_customer_address['und'][0]['first_name'];
  $data['last_name'] = $profile->commerce_customer_address['und'][0]['last_name'];
  $data['address1'] = $profile->commerce_customer_address['und'][0]['thoroughfare'];
  $data['address2'] = $profile->commerce_customer_address['und'][0]['premise'];
  $data['city'] = $profile->commerce_customer_address['und'][0]['locality'];
  $data['zip'] = $profile->commerce_customer_address['und'][0]['postal_code'];
  $data['night_phone_b'] = $profile->commerce_customer_address['und'][0]['phone_number'];
  $data['email'] = $user->mail;

}

Now the customer billing informations are automatically filled up in the Paypal Form.
Notice for phone field : I used "night_phone_b" field for European phone format.
I also hope this helps someone else.


How to make search on all fields (title and tags as well as body)? The built in search engine in Drupal 7 doesn't search on the title or tags fields, just on the body of the node. I need to be able to search on all fields.

What is the best module to install for this if I'm running Drupal on Apache on Windows?

One thing you can do to control which fields are included in your search index is to go to your specific content type's 'Manage Display' page.

So go to Structure --> Content types --> Your content type --> Manage display.

On that screen, you'll see a collapsed section called 'Custom Display Settings'.  Just click on it to expand it.  You should see that you can check to enable the 'Search index' display to be customized (Usually only the teaser or summary is included for customization by default).  Check the 'Search index' box and save:

That will provide you with a brand new "Search index" tab on this screen.  Click on it and start customizing which fields you want to be included for this content type's search index:


How to create a custom field programmatically on content type creation? I have a module which creates custom fields to the selected content type. This works fine when the content type already exists.

With hook_form_node_type_form_alter I create a extra tab on the edit page of the content type. In this tab is a simple checkbox.

function hook_seo_form_node_type_form_alter(&$form)
{
    /* @ CREATE VERTICAL TAB ON CONTENT TYPE TO ADD OR REMOVE SEO  */
    //get node type
    $bundle = $form['type']['#default_value'];
    if ($bundle != null) {
        $node_type = NodeType::load($bundle);
        $default_value = $node_type->getThirdPartySetting('seo', 'seo_options');
    } else {
        $default_value = 0;
    }

    //create vertical tab
    $form['seo'] = array(
        '#type' => 'details',
        '#title' => t('SEO'),
        '#group' => 'additional_settings',
    );

    //add checkbox to vertical tab
    $form['seo']['seo_options'] = array(
        '#type' => 'checkbox',
        '#title' => t('Use custom SEO fields'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => 10,
        '#default_value' => $default_value,
    );

    //create submit handler
    $form['actions']['submit']['#submit'][] = 'seo_form_submit';
}

I use  the following function to see if the form of the content type is submitted and run my script to add fields.

function seo_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    /* @ ON SUBMIT SAVE CONFIG & ADD/REMOVE FIELDS  */
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);
    $checkbox = $form['seo']['seo_options']['#value'];

    //set checkbox value to config and save
    $node_type->setThirdPartySetting('seo', 'seo_options', $checkbox);
    $node_type->save();

    if ($checkbox == 1) {
        //Add fields
        seo_enable_field(
            'add',
            'node',
            $bundle,
            'page_title',
            'string_textfield',
            'basic_string',
            'Page title',
            'Description'
        );
    }

But for some reason this only works when the content type already exist and I edit it. When I create a new content type it doesn't work and my fields are not created.

How can I solve this?

It is the NodeType::load() in seo_form_submit() that is failing because the bundle doesn't exist at the time the form is submitted for the first time.

My recommendation would be to redesign this code so that the logic to create/destroy the field is in both a hook_node_type_insert() and a hook_node_type_update().

You will need some way to pass the value of the checkbox on the form to these respective hooks. Most likely through a custom configuration or schema.

Edit: It looks like there is more than one design pattern that would work as well as the one I recommended in this answer. Please reference Entity CRUD, editing, and view hooks.


Blocks: Old vs. "Custom" and Config vs. Fields I have quite a bit to ask in this question, so I apologize in advance. I believe these questions are all related, and I'm trying to grasp some thoughts on the new block system in Drupal 8.

Background

I am troubleshooting a custom block implemented by a vendor. This block is not listed in the Custom block library, but I can add it to the page with the Place Block link on the Block layout page (note: this makes me think it's an "old-style" block, as in D7 type block). When I place a new block, I am presented with a "Configure block" screen, which I believe shows and stores the values of these fields in config. The custom class extends BlockBase, so the form I'm seeing is built/shown/processed with blockForm() and blockSubmit() in the code.

The problem I am having is that files/images added via these "config" fields (aka a form file upload field, or a wysiwyg editor's IMG button) upload "temporary" files to the file system, which are then later deleted as orphans by a cron run a few hours later. I realize I can turn off that cron job, but I am looking for a BETTER solution. When I go to the files page (/admin/content/files), I want to see that my uploads are "used in" at least one place, and have that place show correctly as a link to the block. My belief, is that if this block were built as a custom block type, using fields, that Drupal would by default take care of the association of these images, which really are content.

Questions

So this brings me to some questions... Am I on the right path here? Should I be using fieldable, custom blocks for this implementation? If the image is a field, and the body is a field, and saved appropriately in the database, then the files page will be able to see this content correctly. This is do-able, correct?

So this brings me to my next question, when should I be using blocks/configuration and when should I be using blocks/fields? This particular example screams "content" at me, and in that case, I think the argument is for fields. Does that sound right? I can think of another example off the top of my head that I'm a little more fuzzy on. We offer a custom block for "Polls" on our website where, when creating a new poll, you choose a reference to a poll, and can optionally set (override) the Title shown in the block. That's 2 settings that a site admin should be able to change. Are these still content, or are they config? To me, it seems like the "poll reference" could go either way... I assume most custom blocks have some combination of "content/fields" AND "config", right? For example, all the "Visibility settings" for a block get saved as config, right?

Any help understanding all of this is much appreciated! Thank you!

What you describe are three different things:

If you put code in a class that extends BlockBase, then yes, this is
a block plugin.
If you add a custom block in the block library, then you store
content in the database as block_content.
If you place a block in the block library then you add a block
configuration, this is a config entity with the name block.

In a block configuration (3) there can be either a plugin (1) or a block content (2).

You can configure fields in (2), then the storage will be managed by drupal, also for image fields.

If you put form fields in (1) then they are not content, but config. You need submit code to handle this. The result of a file field remains temporary until you decide to save it. And combining config with an uploadable file seems a bit odd, but is possible, see for example the site logo.

Comparing both, I would start with (2) and only use (1) if I need code to make something that (2) does not provide.

Edit: Answer to the comment

If you use (2) you probably should be able to solve most of the tasks you describe in the comment in theming (preprocess + twig).

If not, there may be a solution by using (1) + (2). Put the image in block content (to store it properly in the database), but then use this not as a custom block as in (2), but pull the data in your own plugin. For this put a field in blockForm() to configure the block content id and then use in build() the entity api to load the field data of the configured id.

In fact drupal does the same to get the block content entity into a block, it uses also a plugin for this, but you would make your own.


How does one create terms on hook_install if hook_taxonomy_default_vocabularies is used in the same module? I'm attempting to create taxonomy terms in a module that provides the vocabulary needed to create these terms.

The issue I'm having is the vocabulary is not available upon install.

My module implements hook_taxonomy_default_vocabularies.
I would like to create these terms in hook_install.

What is the best way to create these terms?

Although you can use hook_install(), it's best to use hook_enable() to check if the vocabulary exists and, if not, create it programatically:

$vocabularies = taxonomy_vocabulary_get_names();
$pos = array_search('my_vocabulary', $vocabularies);

if ($pos !== FALSE) {
  // its a keyed array so the $vid is actually $pos
  $vid = $pos;
} else {
  // arrays are more convenient to initialize
  $vocabulary = array(
     'name' => t('My Vocabulary'),
     'machine_name' => 'my_vocabulary',
     'description' => t('My description'),
     'hierarchy' => 1,
     'module' => 'your_module', // or nothing
     'weight' => 1
   );
   // argument must be an object
   $vocabulary = (object) $vocabulary;
   taxonomy_vocabulary_save($vocabulary);
   // horray, we have a vid now
   $vid = $vocabulary->vid;
}

// now that the vocab exists and you know the $vid, create your terms
// ...


Right way to add JS and CSS to node/edit and other forms I am making a site with a lots of JS, and I am wondering where I should put the JS code. Optimally I would like to keep the JS with each module and not the theme layer. Some content could be exposed as blocks etc.

But I am having some issues with the cache. In my example I need to add JS & CSS to the node edit form. I have used hook_block_view, but it is cached. So if there is an error in the node edit form, the drupal_add_js & drupal_add_css functions are not called. The same seems to be true for hook_node_prepare.

Where would you input the JS & CSS layer? and are there hooks that get's called even if there is an error in the node edit form?

If you wish to add JS and CSS to the node edit page in particular (or any form in general), the best and the right place to do so is the hook_form_alter() and the property you should be using is #after_build.

This comment on DO tells you exactly what to do - http://drupal.org/node/1253520#comment-4881588

Hope this helps :-)


Boost not updating without www site after clearing cache Boost is working good on my website but the problem is that after making any changes to my website I clear all cache from performance page. The changes I have done are reflecting if I am accessing site with www but not updating if I am accessing website without www

You need to clear the Boost cached pages, i.e. the static pages. You can do that on the Boost settings page at the bottom under Clear Boost's Database & File Cache. If you only have changed one page you can just clear this page by enabling the boost block Boost: Pages cache configuration.

Edit: After a bit more thinking I am not sure clearing the Boost cache will fix your issue. However, do yourself a favor and change your .htaccess rules to redirect users to either with www or without www. I would suggest with as that is working for you. Having both counts as duplicated content in search engines and you risk to loose ranking.

To fix this, uncomment the following part in your .htaccess file (around line 81), or add it if it's missing:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


How to Clone a production site locally for testing? Ok so I am kinda new to drupal (I've only been working with it for a few months at work) and I just got my first freelance client who has a drupal site that he wants to modify its layout.

I am now stuck at trying to duplicate the website and set it up on my machine and I don't want to do changes to the production environment directly.
Here's what I did so far:

I got access to the webhost server and downloaded the site's drupal root directory
I exported the site's database and stored it on my machine
Used Acquia Dev Desktop 2 to import a local site -> chose the downloaded drupal site root -> selected the sq database dump file that I exported earlier

When I try to open the site on my local server it runs the drupal installation but when I choose a profile and press "Save and continue" it shows me the following message:

  "Drupal already installed. To start over, you must empty your existing
  database. To install to a different database, edit the appropriate
  settings.php file in the sites folder."

Now I know that drupal is already installed probably because I cloned the website codebase and database exactly as they are from the webhost server, and I did not change any of the settings.php files.
How exactly do I run the website l locally through Acquia Dev Desktop and then push my changes to the host?

Any tips, best practices comments, and advice is highly appreciated!

Most probably the problem is in your settings.php, what you can do:

Open your settings.php files and search for the folowing code:

$databases = array
'default' =>
array (
'default' =>
array (
'database' => 'your-db-name',
'username' => 'your-db-user',
'password' => 'your-db-user-password',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
),
),
);
If you are not sure if you have the correct code for your database, please post your code back in here and i will take a look on it
Last thing, if all you need is making changes to your website using a test website and then push all changes back to the production website, my suggestion is to create a subdomain on your webshost (Ex: dev.yourdomainname.com) and completely clone your entire website from dev.yourdomainname.com so you can work on your dev website without touching your production one.

I can help you with that also but first tell me what your need and answer the following:

_ You have access to Drush console ?
_ You have access to the webhost server ?

waiting your response...

Update # 1: Clone your production website for testing purposes on your webhost

1) Create a subdomain for your domain name (ex: dev.yourdomain.com)

2) From your cpanel, create a new empty database (don't forget to prefix your db name at end by _test to distinguish it from the original one) (Ex: db_name_test)

write down the name of the database

3) create a new user for your test database and also (don't forget to prefix your user name at end by _test to distinguish it from the original one)

Write down the name of the user & password

4) Grant the test user all privileges for the new database.

5) goto your production site and do the following manually or by using the drush command:

Clear all caches. (drush cc all)
Disable clean URLs. (/admin/config/search/clean-urls)(drush vset clean_url 0 --yes)
Disable cron job. (/admin/config/system/cron)
Put site in maintenance mode. (drush vset maintenance_mode 1 --yes)

6) Copy the entire site's drupal root directory to the new test website root directory and make sure the settings.php file is copied as well.

Manually:
Click on the site root directory and choose copy and type the destination path.

drush command:

cp -rp /home/cpanel-user/public_html/your-original-site-root-directory /home/cpanel-user/public_html/your-dev-site-root-directory

7) Goto your phpMyAdmin, Select your original database, Choose operations, under the copy database to section, write down your test database name as it is, make sure the structure and data is selected, and uncheck create database before copying, leave everything else as it is, click Go and wait for the confirmation message.

8) Make sure the permission given to the deb-site root directory is: 0755

9) navigate to your new test website directory, edit settings.php and edit the database settings to fit the new database name, new database user & new user password

10) open new tab browser and navigate to: dev.yourdomain.com

11) Voila, all should be good.

12) goto your dev site and do the following manually or by using the drush command:

Clear all caches. (drush cc all)
Enable clean URLs. (/admin/config/search/clean-urls)(drush vset clean_url 1 --yes)
Enable cron job. (/admin/config/system/cron)
Don't remove the site from the maintenance mode since it is a test website.

Note, you can do the exact steps above to have a copy of your website locally, but i will just stick with this method since it is more reliable. easier and faster.

If you insist of cloning your website locally to acquia dev desktop:

1) Get a fresh copy of your prod-site database and file, manually or using drush

drush ard --destination=/home/cpanel-user/create-a-directory-for-backup/choose-a-name.tar.gz

The above command using drush 7, will get you a copy of your database and your files/folders.

2) Download the archive backup folder to your desktop and unzip.

3) Goto Acquia dev desktop, click on + and import local drupal site

4) Choose the local codebase folder from the unzipped folder you just downloaded.

5) choose a local site.

6) leave the create a new database and give it a new name of your choice.

7) when finish importing, visit your website and complete a new fresh installation from your website.

8) when all go good and you will have a fresh new Drupal website up and running, goto your local database (phpMyAdmin), click on Structure, Scroll down to the button, Check all tables, with selected choose drop, make sure there is no any left tables in the database.

9) Goto import, select you .sql database, leave everything as it is, click Go

10) no need to change anything inside the settings.php, just visit your site and voila.


How to limit number of points that user can add through Geofield widget to Openlayers maps? Im using the modules stuck very similar to one described here (
Need a simple Google Maps solution; lost in the labyrinth of modules).

Geofield, Openlayers, Drupal 7

The difference is that I dont use Address field for auto detecting the lat/lang from address. The Geofield field widget type is set to "Openlayers map" so the points can be manually added by user to the map when the node is being edited.

Is there any way to limit the maximum number of points that user can mark on map? (to 1)

In the settings of the GeoField you'd like to limit the entry for, set Storage Options to 'Store each simple feature as a separate field.'
Then in Location field settings, you can set the limit to one.

Number 1 is important, as it will make sure that clicking on the map a second time, moves the point around, instead of creating new points.


How to get View display label for field? I'm trying to enable grouping for the Views Datasource module. I'm looping through the $rows array, which is where output is stored by the module before it's formatted into JSON. Problem is, the grouping field is stored in $options as its machine name, but $rows uses the user-defined label for field names. Basically, I just need a function to take the machine name for a field and return the display-set label for it.

I already tried field_views_field_label, but it returns an array of the labels for fields defined in the content type, where I need the label defined in the view display.

$group = $options["grouping"][0]["field"];
// Get grouping field as defined by the field options in the view display
$root = $options["root_object"];
$top_child = $options["top_child_object"];
if ($group) {
  $grouped = array();
    foreach ($rows[$root] as $key => $array) { // Values are numeric
      // Grab the grouping field value from inside the 3rd-level array.
      // Creating a label for grouping field will break everything
      $groupnode = $array[$top_child][$group];
      foreach ($array[$top_child] as $prop => $value) {
        if ($prop != $group) { // Ignore grouped field
          $grouped[$root][$groupnode][$prop][$key] = $value;
        }
      }
    }
  $rows = $grouped;
}

I recommend to take a look at this answer which provides lots of information on how to change the output produced by Views Datasource. This should give you a starter.


How to sort the query results? In my task I need to display the results based on "the newest first". I perform a query:

$query = \Drupal::database()->select('node_field_data', 'node');
$query->innerJoin('node__field_ils_apps', 'app', 'app.entity_id = node.nid AND app.field_ils_apps_target_id = '.$node->id());
$query->addField('app', 'entity_id', 'nid');
$query->groupBy('app.entity_id');

$query->orderBy('created', 'DESC');
$query->execute();

But it returns me an error:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column

Could you please tell me what I do wrong?

Try this out

use Drupal\Core\Database\Database;

$connection = Database::getConnection();
  //- Step one get all referenced nids
  $query = $connection->select('node_field_data', 'nfd')
    ->fields('nfd', ['nid', 'created']);
   $query->innerJoin('node__field_ils_apps', 'app', 'nfd.nid = app.entity_id');
  $query->orderBy('created', 'DESC');
  $result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);


how to display/hide block on homepage depending the value in user profile field? I'm currently displaying a block on my D7 site' homepage.

Now I've a requirement to display that block only if the logged in user has a specific value in their profile.

I know it can be done using php evaluation by navigating to the bottom of the block and then click (Pages > Pages on which this PHP code returns TRUE ) but have no experience in writing php scripts.

global $user;

If($user->your_profile_field_value == 'requiredvalue')
{
// display the block
// display the block only on 'homepage' }
Else { // don't display the block }

I'm new to php can someone please help me fill in the blanks in above code snippet.

thanks

I would use the PHP visibility settings to display the block if user has requiredvalue. Once you've created the block that you want to display (or not display) add the following code to the "Page specific visibility settings" in the block configuration menu:

 <?php
    global $user;

    If($user->your_profile_field_value == 'requiredvalue' && drupal_is_front_page()) {
    return TRUE;
    }

    return FALSE;

    ?>


Easy content management for a Views powered site I'm building sites using Views and Panels, as you do. When handing over to the client/content editor, I want to make things as user-friendly as possible. Ideally this means they don't need to get their heads around View settings, but sometimes it seems unavoidable even for the simplest things? Or maybe I'm not designing the IA the best way...

Example: a movie review site, where each review is a node. On the homepage, we have a 'featured reviews' display with preview images for 3 movies. So I make a View that selects the 3 most recent reviews, and use some nice imageslider display or whatever. Nice.

Then the client asks if he can manually override this, and manually choose which 3 reviews to feature. He expects to just go into 'homepage settings' or something and select from a list.

So what to do... introduce him to Views filters and selecting node IDs...? Not good :(

So I resort to adding a 'featured' checkbox to the review content type, and filtering the view that way. Now this is easier for him, but still means ticking boxes on and off in various nodes. And it means I'm using content fields for something that isn't really content.

I run into this kind of situation very often, so wondered what other developers do?

For that particular use case, I'd suggest using the Nodequeue module. You could set up the nodequeue to contain 3 items and then users with the correct privileges would have the ability to add new items to the queue by clicking on a link on the node they want to add. In addition, users with permission to the administrative side of the Nodequeue module can also control the sorting of the items in the queue.


Change layout of views page based on taxonomy term field I have a taxonomy term page being displayed via a Views 'page' display. I need to change a value in the header of the site (above the level of the view) based on the value of one of the fields in the taxonomy term.

The problem is that I can't find the right hook for this. If I hook into hook_preprocess_views_view, it's too late. The wrapper that includes the site header has already fired. If I try to run hook_preprocess_page, there isn't yet any information in the $variables arg to give me the taxonomy ID so I can look up the field value. Unless there is are variables available to the hook in addition those that are passed into function as args, I don't see how I can get the requisite information. Are there other variables I could use that are undocumented or global variables available that just aren't passed to the function/hook?

What you can do is in the hook_preprocess_page use the following code :

$arg = arg();
if (count($arg) == 3 && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2])) {
  $term = taxonomy_term_load($arg[2]);
  if ($term->vid == $my_vocab_id) {
    # code...
  }
}

Then change the value of the header as you want in the # code... part.

Basically you check if the URL is a taxonomy term page and then  you can check that the term vid correspond to its proper vocabulary id.

Hope that will help you.


Allows authenticated users to tag content Administrator can add tags/Term reference to any content types.
How can I give permission to authenticated users so that they can tag on any content type where they have access for editing/adding?

Check for field permission. If authenticated user has permission to add/edit the node then user should be able to tag it. You Just need to verify your permission settings.


How to redirect to a edit node page with RedirectResponse? From a hook (not form_alter), I want redirect the user to a node edit page (like mywebsite/node/[nid]/edit)
How can I do that with the RedirectResponse class?

After searches, I found the following code.

new RedirectResponse(\Drupal::url('route.name'));

How can I get/find the route.name for a node edit page?

Update :

According the cilefen's answer =)
From my entity_insert hook :

function article_entity_insert(EntityInterface $entity) {
  if ($entity->bundle() == "article"){
    Url::fromRoute('entity.node.edit_form',['node', $entity->id()]); //But when I create a new node, the "view" page is loaded and not the edit page
    dpm($entity->id()); //show the node id
  }
}

Update 2 :

The command

dpm(Url::fromRoute('entity.node.edit_form',['node', $entity->id()]));

return

Drupal\Core\Url Object
(
    [urlGenerator:protected] =>
    [urlAssembler:protected] =>
    [accessManager:protected] =>
    [routeName:protected] => entity.node.edit_form
    [routeParameters:protected] => Array
        (
            [0] => node
            [1] => 31
        )

    [options:protected] => Array
        (
        )

    [external:protected] =>
    [unrouted:protected] =>
    [uri:protected] =>
    [internalPath:protected] =>
    [_serviceIds:protected] => Array
        (
        )

)

But the command

dpm(Url::fromRoute('entity.node.edit_form',['node', $entity->id()])->toString());

Return this error :

  [Mon Feb 15 01:38:30.081002 2016] [:error] [pid 10219] [client
  192.168.1.48:49246] Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Some mandatory
  parameters are missing ("node") to generate a URL for route
  "entity.node.edit_form"." at
  /var/www/system/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php
  line 757, referer: http://192.168.1.44/system/node/add/article

Note that \Drupal::url() is deprecated. You should use the static methods of the Url class to create URLs from routes.

To find the route names, use the Drupal console drupal router:debug. From that I found:

 entity.node.edit_form  /node/{node}/edit

I think what you need is Url::fromRoute('entity.node.edit_form', ['node' => 1]) where 1 is the node ID to be edited.


How to make textfield with ['#ajax']['keypressed'] = TRUE trigger only on click and not on blur? When I specify ['#ajax']['keypressed'] = TRUE for textfield, trigger runs not only when I click ENTER (as it is mentioned in documentation), but also when textfield loses focus (must be blur event in JavaScript). So how can I avoid this?

Maybe too late but for the others :

['#ajax']['event'] = 'none'


path_to_theme() return "modules/system" I am trying to render the theme logo as a block.

When I call path_to_theme() in page.tpl.php, it returns a true path, but when I call it in modulename.module, it returns "modules/system".

Whenever I'm stuck in a module, or a context that path_to_theme() doesn't return what I'd like - I use the following to access the current globally selected theme.

global $theme;
$path_to_theme = drupal_get_path('theme',$theme);

For instance if I am in a subtheme, or a slighly different flavour (mobile vs. desktop) of my theme, I use $theme that to get my active theme.


Core overlay on path defined in views Anyone know how to render a path defined in a view in the core overlay.

hook_admin_paths_alter() does not work in that instance. I can only think that it has to do with the execution pipeline.

overlay_paths module also does not work.

First you have to Change the overlay permissions and make the overlay view accessed by Visitors and users

lets Implement Hook_admin_path_alter in your custom module...

function YOURMODULENAME_admin_paths_alter(&$path) {
  $path['VIEWPATH'] = TRUE;
}

Clear Drupal Cache..


Drupal 6 - Get 5 newest nodes of a certain type I have a content type called "announcements". They each have a title and field for the announcement. I'd like to be able to, in my .module, get the last five announcements and print out their contents to the page. How can I do this?


Using module_invoke for Menu causes Undefined index notice I'm displaying a multi-level menu in the footer of my site using:

$block = module_invoke('menu', 'block_view', 'main-menu');
          print render($block['content']);

Which is displaying correctly, however I am receiving this warning message:

  Notice: Undefined index: main-menu in menu_block_view() (line 486 of /****/modules/menu/menu.module).

Any suggestions on how to suppress this message?

It is caused from the following line, executed from menu_block_view().

$data['subject'] = check_plain($menus[$delta]);

$delta is the value you pass as last argument to module_invoke().

It means there isn't any menu with that ID, or you misspelled the menu ID. Try with main_menu, for example.


How can I add an argument in the URL that link from a content I have been searching for the answer for so long but still none of the solution that I can finish my goal...
my content structure is as following:

I have Content-type that keep a list of Quotes - I named it [A]
I have Content-type that keep a list of Titles - I named it [B]
In a 'Quote', I have a field that refer to which 'Title' that it is referring.

EXAMPLE   (not codes)

Quote-1 have a field referring to Title-1
Quote-2 have a field referring to Title-1
Quote-3 have a field referring to Title-2
Quote-4 have a field referring to Title-3
Quote-5 have a field referring to Title-1
(multiple Quotes can referring to the same Title)

So...I used Views(block) to display this Quotes[A] in a page and...HERE is what I want...
I want each 'Quote' to link into another page which require 2 parameters...

node ID  (which is already sent by default Drupal (q=...))

Title ID (that is referring in a field of the Quote)
by default, the Drupal have value of 'q' sent to another page but ...

How can I add Title ID parameter into each 'Quote' link?

You could add the Title ID field to your view, exclude it from display, move it above the link, enable rewriting on the link field and write the link format you want, including the Title id.

Edit following the follow-up question:
Well, in my opinion, you shouldn't have to put the Title id in the URL at all. What I wrote above solves your specific problem but, really, I think you should do things differently and thus wouldn't have this problem or the follow-up one.

Link to node/quoteid and load the Title node by looking at field_title_id (replace by the actual field name). You can do that loading in hook_preprocess_node by calling node_load($node->field_title_id[LANGUAGE_NONE][0]['nid']) from there you can either render the whole title node (node_view) or just get one field and send it to your template.

Basically, the Quote->Title relation is in the database, there's no reason you should have to express it in the form of a URL. The reverse would make sense, if you had a Title page where you want to show a single quote.

Second edit following the second follow-up question:

To display all other Quotes linked to the same title you could create a view with Title ID as a contextual filter. You can render the view manually in your template, passing it the Title ID. That'll display all quotes, including the main one displayed in that page. You probably want to filter that one out one way or another.


How to manually create a menu item for a taxonomy term? We need to create menu items out of some taxonomy terms in D7.  Currently we do this manually by switching between taxonomy and menu administration pages.  That is, we:

In the vocabulary administration page, create a term.  Set the term's path.
In the menu administration page, create a menu item pointing to the path of the above term.

This can get quite tedious.  There are some ways to automate this but we still want to create menu items manually for the sake of flexibility.  For example, we need to create several menu trees from a single vocabulary.  Also, the terms that would get a menu item are more or less hand-picked in our case, so they may not be easily selected with a view.  Ideally we just need some way to simplify managing the menu item of a term.
It would be great if there is a "menu settings" tab when editing a term, just like the same tab you get when editing a node.  That way we could have a single interface to manage the term and the menu item it created.

I am wondering if there is already a module for this.

I don't know if there is a module for this, but what you can do is to create it via views. There are two ways I can see:

Install Entityqueue.

  The Entityqueue module allows users to create queues of any entity
  type. Each queue is implemented as an Entityreference field, that can
  hold a single entity type.

  For instance you can create a queue of:

  Nodes
  Users
  Taxonomy Terms

Install Flag and Views Bulk Operations, then add a bulk operation on the flag in the specific view's UI.

Make sure to cache your views for better performance.


Blocking access to taxonomy pages I'd like to block access to all taxonomy pages for anonymous users.

For example I don't want them to be able to view http://website.org/category/year/2525 or http://website.org/taxonomy/term/42.

Is there even some built-in functionality to achieve that? I'm using Drupal 6.

while category/year/2525 is an alias for taxonomy/term/xxx you should restrict access to taxonomy/term/* for all anonymous users.

if you want do this via simple module:

function mymodule_init(){
  global $user;
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && !$user->uid) {
     drupal_access_denied();
     exit;
  }
}


Why am I getting a 403 error with this route? I'd like to apply the admin (or other) theme to user /user/login page. Since ThemeKey isn't available I'm attempting to implement via routes. "View admin theme" permission is granted to anonymous.

Using this route:

my_module_name.user_login:
  path: '/user/login'
  options:
    _custom_theme: 'my_custom_theme'

gives the correct theme, but a 403 response on the /user/login page. Why am I getting a 403 response (with the anticipated theme) instead of the standard login page?

Because you don't have any access checks.

If anyone is allowed to access it, you must specify so explicitly with _access: 'true' in an access section.