Problem with theming form for my module setting page I am trying to theming my module setting page.

My environment
version Drupal  7
module name: actionadscatalog
filesystem:
actionadscatalog
      - actionadscatalog.info
      - actionadscatalog.module
      - actionadscatalog.admin.inc
      - templates
          -   admin
             - actionadscatalog-admin_run_import.tpl.php

actionadscatalog.admin.inc

function actionadscatalog_admin_settings_runImport() {
$form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
);

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

}

actionadscatalog.module

function actionadscatalog_theme() {
$path = drupal_get_path('module', 'actionadscatalog') . '/templates/admin';
return array(
    'actionadscatalog_admin_settings_runImport' => array(
        'render element' => 'form',
        'template' => 'actionadscatalog-admin_run_import',
        'path' => $path,
    ),
);

}

function theme_form_style(&$variables){
$variables['adsru_action_in_load'] = 'hello theme';

}

actionadscatalog-admin_run_import.tpl.php

echo $variables['adsru_action_in_load'];

But I only see the form with user_name field.
The file actionadscatalog-admin_run_import.tpl.php is not run.
What have i missed?

Thanks for any help.

It's because you haven't defined a theme registry entry called form_style, but you're setting the form's theme handler to a function with that name.

You just need to change your implementation of hook_theme() to match the function name and form theme setting you've actually defined:

function actionadscatalog_theme() {
  $path = drupal_get_path('module', 'actionadscatalog') . '/templates/admin';
  return array(
    'form_style' => array(
      'render element' => 'form',
      'template' => 'actionadscatalog-admin_run_import',
      'path' => $path,
    ),
  );
}


Make URL from 1 field available to another field [Drupal 8] Drupal 8 Twig question:

I have 2 fields: textfield and a linkfield.

When the linkfield is filled, the text entered in the textfield should become the link.
I cannot edit the node.html.twig for this, I want to do this in the field--textfield.html.twig to include the URL (if it is set).

But I don't know how to make the URL from "field--linkfield.html.twig" available in "field--textfield.html.twig"

(Needed because the link module is still a little bit broken in Drupal 8 (no optional URL possible)).

If you want to get a field value from another field in a field template you have to use the parent entity (in your case a node) element['#object']:

{{ element['#object'].field_textfield.value }}

or a url from a link field:

{{ element['#object'].field_linkfield.0.url }}


Adding an OR condition to an existing query I want to be able to search additional user fields instead of just the standard username. For instance, I would like users to be able to search an attached field with the users' Real Name. The user search query can be found in user_search_execute(). I figured I would use hook_query_alter() to alter the database query generated by this function.

The problem I am running into is that if I add anything like this:

$arguments = $query->getArguments();
$query->condition('n.field_name_value',$arguments[':db_condition_placeholder_0'], 'LIKE');
$query->leftJoin('field_data_field_name', 'n', 'users.uid = n.entity_id');

Then drupal adds a "AND" to the list of conditions (instead of an OR).

I have even tried adding something like this:

$arguments = $query->getArguments();
$query->condition(db_or()->
  condition('n.field_name_value',$arguments[':db_condition_placeholder_0'], 'LIKE'));
$query->leftJoin('field_data_field_name', 'n', 'users.uid = n.entity_id');

However, this produces the same results.

thanks!

Adding new conditions to the query won't overwrite the existing ones, you need to reset the existing array of conditions, build up a new one and add it to the query:

// Get the query args and then the search term
$args = $query->getArguments();
$search = array_shift($args);

// Get a reference to the existing query conditions.
$conditions =& $query->conditions();

// Reset the condition array. It needs a default #conjunction for which AND is fine
$conditions = array('#conjunction' => 'AND');

// Build up your condition
$condition = db_or()
  ->condition('users.name', $search, 'LIKE')
  ->condition('n.field_name_value', $search, 'LIKE');

// Add the new OR condition to the query
$query->condition($condition);

// Join the relevant table
$query->leftJoin('field_data_field_name', 'n', 'users.uid = n.entity_id');

I've just tested that to work on a local installation.

There is a slight caveat...for users with the 'administer users' permission the default is to also search through users' email addresses. You can cater for this by adding the following lines immediately before $query->condition($condition);:

if (user_access('administer users')) {
  $condition->condition('mail', $search, 'LIKE');
}

It might also be wise to test the bundle and entity_type columns in the joined field table in case you ever attach the same field to another entity. This way you won't get any false results:

$join = "users.uid = n.entity_id AND n.entity_type = 'user' AND n.bundle = 'user'";
$query->leftJoin('field_data_field_name', 'n', $join);

EDIT

As per Berdir's comment, to maintain as much compatibility as possible with other modules that might also alter this query, you probably want to loop through the conditions, find the one(s) that you need to change and do so on an individual basis.

The above example is pretty rudimentary and works on a 'vanilla' Drupal install, hopefully it'll get you pointed in the right direction.


Keyword research does not find any keywords under keyword stats I've installed module SEO Tools including all its 'sub modules". One of them being they Keyword research module. Now, in order to find keywords I'm supposed to be able to the Keyword stats tab from admin/structure/kwresearch/keyword_report, enter a keyword and hit submit. I don't get any results, I just see "No keywords were found." - even when I submit a keyword like bike for example. Why is this? what am I missing?

Keyword research is because of Keyword Research Module, which might have installed as suggestion by SEOTools module.

The report you are looking for is supposed to be pull form third party tools, or to be imported from google, which basically will help you deciding what keyword to use on your site.

Watch this demo for better understanding if you have not watched it yet.
- http://getlevelten.com/tools/contentanalysis/keyword-research/drupal/screencast

Please follow the module installation instructions. Module page says

  To get full reporting with integrated keyword statistics you will need
  to connect to or import from a 3rd party data source. The module will
  work without a 3rd party data source, still providing tools for
  organizing site keywords and tagging nodes and providing links to
  external tools for assessing keyword statistics. Currently the Keyword
  Research module supports:

Wordtracker - premium keyword research service with a free demo key that provides up to 15 suggested phrases per API call.
Google Keyword Tool - a free tool but data must be imported via file download
WordStream (via WordStream module) - freemium service. Free account provides 200 API calls/mo
Scribe SEO (via Scribe SEO module) - paid service starting at just $17/mo.


How do you get field groups to render for a block_content entity loaded programmatically? I added some field groups to my display, but they don't render on my custom block_content entity.

$blocks = \Drupal::entityManager()->getStorage('block_content')->loadByProperties(['type' => 'footer_bottom']);
if (!empty($blocks)) {
  $block = array_shift($blocks);
  $render_controller = \Drupal::entityManager()->getViewBuilder('block_content');
  $footer_bottom = $render_controller->view($block);

  return $footer_bottom; // won't render field groups.

}

I see the field groups in the render array when I dump the $footer_bottom array:

  "#fieldgroups" => array:2 [▼
    "group_tricolumn" => {#5505 ▶}
    "group_subfooter" => {#5465 ▶}
  ]

Is there another step to process the field groups?

The field_group module does not currently support the block entities, see Does not work with blocks [2689501]


Trigger Event After Node Is Indexed I have a pretty basic Drupal 7 web site with Solr search (works great!).

I would now like to perform some "work" after each node is indexed with Solr.

First I tried creating a workflow rule but there is no event for "node has been indexed". Next I looked for Solr API hooks but came up empty handed.

Should I look at adding a hook somewhere in the PHP code? If so where? Or am I overlooking a more obvious solution?

Thanks

Both Solr modules provide APIs:

Apache Solr Search
Search API Solr

But neither provide an after-node-update hook. If I had to guess I'd say it's both modules send data to Solr in batches, not one node at a time.

You might get some joy with the core hook_node_update_index():

  Act on a node being indexed for searching.

  This hook is invoked during search indexing, after node_load(), and after the result of node_view() is added as $node->rendered to the node object.


How do I make an internal link with CKEditor? I am using Drupal 8.

Using the standard WYSIWYG editor, when I click on the link button, I only get the option to add a url. I would have thought there would be some capabilities to look up existing pages.

Is there some way to create an internal link?

Yes, what you're looking for is covered by the LinkIt project.

  Linkit provides an easy interface for internal and external linking
  with wysiwyg editors by using an autocomplete field. Linkit has by
  default support for nodes, users, taxonomy terms, files, comments and
  basic support for all types of entities that defines a canonical link
  template.

Once you install the module, you'll need to create a profile (under Administration > Configuration > Content authoring > Linkit) for selecting your entities. Following that, configure your text format (under Administration > Configuration > Content authoring > Text formats and editors) to use your LinkIt profile.

Once associated, you should be able to add a LinkIt button to your text format toolbar which will let you autocomplete links to your page content.


Displaying parts of main menu in separate blocks I need to display my main menu in separate blocks: the first sub-menu in one block, and the following two sub-menus in another block. I'm using Drupal's native menu module and also the nice menus module.

How can I do that?

Consider using menu_block and defining 2 blocks with the depths you desire within the main-menu for each block; and then place them in the drupal Regions you want. The menu_blocks I believe will play nicely with Nice Menus if you have "expand all child elements" of this menu option checked.


How to display all record from database in Drupal? global $user;
$nid = '650';

$query = db_select('field_data_field_batch_reference');
$query->fields('field_data_field_batch_reference', array('field_batch_reference_target_id'));
$query->condition('entity_id', $nid, '=');
$result = $query->execute()->fetchField();
drupal_set_message($result);

You should use a different method on the query object to get all results.

e.g fetchCol() to get an array when querying for a single column value (in this case field_batch_reference_target_id):

global $user;
$nid = '650';

$query = db_select('field_data_field_batch_reference');
$query->fields('field_data_field_batch_reference', array('field_batch_reference_target_id'));
$query->condition('entity_id', $nid, '=');
$target_ids = $query->execute()->fetchCol();
drupal_set_message('
' . var_export($target_ids, 1) . '
);

You could also then load those entities with something like

$entities = entity_load_multiple('entity_type', $target_ids);
drupal_set_message('
' . var_export($entities, 1) . '
);

Keep in mind that will load all results, so you may want to add a limit to your query instead, e.g:

$query->range(0, 25);


Where does the Entity Registration module store the signup data and how to delete it? I am running Drupal 7.50. I'm using the Entity Registration module, and I have set up a small classroom enrollment content that I used to test this out.

My questions:

Where does Entity Registration store the signup data?
How do I see the information collected?
How do I delete it?

Where does Entity Registration store the signup data?

Looking at the module's .install file, those data should be stored in  the table with name registration. Especially these columns of it should be close to what you're looking for:

  'count' => array(
    'description' => 'How many spaces this registration should use towards the total capacity for this event.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 1,
  ),
  'user_uid' => array(
    'description' => 'The uid of the user associated with this registration.',
    'type' => 'int',
    'not null' => FALSE,
    'default' => 0,
  ),
  'author_uid' => array(
    'description' => 'The uid of the user who created this registration.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ),
  'state' => array(
    'description' => 'The {registration_state}.name of this registration.',
    'type' => 'varchar',
    'length' => 32,
    'not null' => TRUE,
    'default' => '',
  ),
  'created' => array(
    'description' => 'The Unix timestamp when the registration was created.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ),
  'updated' => array(
    'description' => 'The Unix timestamp when the registration was most recently saved.',
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,

  How do I see the information collected?

Option 1: Just browse this table, using your preferred tool to do so.

Option 2: Use the Views module to create an appropriate view of it, as suggested also in its community documentation, i.e.: "Not happy with the default tabular list of registrations? No problem, registrations and their fields are all Views friendly. You can override the default event registrations list, create additional ones, etc". You probably want to enable its registration_views submodule for this.

  How do I delete it?

It may be straight forward to just delete the relevant rows in the "registration" table mentioned above. However because of its integration with the Rules module, I'd rather use this module, possibly combined with the Views Bulk Operations module, to perform such deletes


Drupal Views Datasource and Flag Links I want to use Views Datasource module to output JSON, i then want to construct the JSON output using REACT JS or alike. I am currently stuck on how to output the Flag Link, it just comes back with an OPS field. Ideally i want this as a plain link so I can trigger it through jquery/ajax.

UPDATE: as requested using the php field i managed to get the output i was after which is something like:

Unfortunately I couldn't get the perfect solution to this so I had to use Views PHP. Remember to add a hidden field for the nid of the node

<?php
$link = flag_create_link('MyFlagMachineName', $row->nid);
preg_match_all('/<a[^>]+href=([\'"])(.+?)\1[^>]*>/i', $link, $result);
if (!empty($result)) {
  echo $result[2][0];
}
?>


Set value on newly created node using Rules This is what I have now:
Content type 123 has a Entity Reference field referencing content type XYZ.
If new content is created of type XYZ then Rules creates new content of type 123.
So by creating 1 new node (of type XYZ) I get one extra of type 123.

This is what I'm missing:
How do I set the Entity Reference field of 123 correctly by using Rules?

In the Rules action you need to use the Set a data value action. This can be used to enter data in fields and properties. Make sure to set the value of your new 123-entity to refer to the xyz entity.

{ "rules_create_new_basic_page_after_saving_article" : {
    "LABEL" : "Create new basic page after saving article",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "page",
            "param_title" : "Basic page to go with [node:title]",
            "param_author" : [ "node:author" ]
          },
          "PROVIDE" : { "entity_created" : { "page_created" : "Created basic page" } }
        }
      },
      { "data_set" : {
          "data" : [ "page-created:field-reference-to-other-entity-" ],
          "value" : [ "node" ]
        }
      },
      { "entity_save" : { "data" : [ "page-created" ], "immediate" : "1" } }
    ]
  }
}


Commerce South African Payment method I’m busy with a Drupal 7 Commerce site, and I need a correct and working payment method to handle the payments in ZAR (South African Rand) and not in any other currency.

This answer probably is too late, but for the sake of other South African users coming across this question: I have a sandbox module for using Paygate as your payment gateway. It is developed for Drupal 7 Commerce and it's currently live on a few websites I've worked on.

You can get the module here, but you'll need to know how to use git to download it.


Allowing authenticated users to create files through Service/Restful I have setup a restful server running with the services module.  I have also enabled to file resource.  Using this setup I can successfully login from my client application, authenticate the session, upload a file using the file resource and then create a node with node resource.  This all works fine and good as long as I am authenticated with an adminstrator but if I ever try and use a standard authenticated user I get this error back in response from the file resource:

Unauthorized: Access denied for user authuser

I looked all throughout the user permissions but I did not see any permission to allow authenticated users to create files.  How would I do this?

Make sure "Save file information" is set for authenticated users


Hierarchical Taxonomy Term View I have a Taxonomy which looks like this:

Parent1
-Child1
--SubChild2
--SubChild3
-Child4
--SubChild5
--SubChild6
-Child7
Parent2
-Child8
-Child9
--SubChild10
-Child11

I have created a view to display all terms under a specified Parent by setting a context tid . Here you can find the exported view: http://pastebin.com/us7KnKsD

The Problem is that the view only shows the terms which have sub-children.

How can I also display the terms which doesn't have sub-children?
Is it possible with views? In php I would just create some recursive function...

Start your query from the Taxonomy table. Meaning select Taxonomy as your base table when creating your view. Then establish a relationship to your content from there. This will ensure your results contain all taxonomy names and then their subsequent children.


How to quick start sub-theming in Adaptive Theme? I have a question. I'm a little confused on if I should copy the entire contents of the "adaptivetheme" folder to create a sub-theme, or if only the "at_subtheme" folder should be copied.

I'm following the instructions from the project at https://drupal.org/project/adaptivetheme, which says that you need to update the theme-setting.php and template.php files, replacing "adaptivetheme_subtheme" with your new subtheme name. However, within the contents of the instructions it states to only copy the new "at_subtheme" folder, not the entire "adaptivetheme" folder, and I do not see a theme-setting.php and template.php file in the new "at_subtheme" folder. I only see theme-setting.php and template.php in the original "adaptivetheme" folder within "at_core".

Should I copy the entire original "adaptivetheme" folder?

I'm using Drupal 7.26

No, you should copy only the sub theme folder. I have just downloaded all versions of AT and both theme-settings.php and template.php files are there. You may consider deleting the existing adaptivetheme folder and downloading it again.


unset description in user_profile_form I try to remove descriptions of language, files (avatar) and timezone in user profile form:

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

if ($form_id == 'user_profile_form') {
    unset($form['account']['mail']['#description']);
    unset($form['account']['pass']['#description']);
    unset($form['account']['language']['#description']);
    unset($form['account']['files']['#description']);
    unset($form['account']['timezone']['#description']);
   }
}

This code removes mail and password descriptions but it does not removes language, files and timezone descriptions.

Please, what is wrong with this code?

Thank you

It is better to increase weight of your custom module for removing description of timezone field. Your code should be like below:

if($form_id == 'user_profile_form'){
  unset($form['account']['mail']['#description']);
  unset($form['account']['pass']['#description']);
  unset($form['locale']['language']['#description']);
  unset($form['picture']['picture_delete']['#description']);
  unset($form['picture']['picture_upload']['#description']);
  unset($form['timezone']['timezone']['#description']);
}


Shopping cart form footer I wanto to display Prices with no decimal Places, in shopping cart footer (commerce order: order total ), but in the shopping cart view i found nothing to which does this.
what shoud i do?

Editing the view could be one solution but you can also do it via jquery i.e. capture the html inside the relevant div or span , then truncate the decimal part and then resupply the altered price value to the div or span. I think that should be very easy to do.


Responsive image gallery with unique URL per image? I've been tasked to create a carousel that would have a unique URL per panel.

The panel would have to contain multiple pieces of info (each piece a link), and so would be views based.
the panels would have to be able to rotate.

Royal slider seems like it may be up to the task: http://dimsemenov.com/plugins/royal-slider/

My question is - are there any recommendations for other modules? module combos? custom script?

I'm using D7.23

Thanks!

Give a try to Flexislider module:

  Flex Slider module integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Some features of FlexSlider slideshows include:

Touch enabled nagivation
Keyboard navigation
Configurable slide animations
Multiple sliders per page

Demo available here: http://www.woothemes.com/flexslider

  Library available at: https://github.com/woothemes/FlexSlider

And as far as the unique URL per panel thing is concerned I guess that depends upon how you creating the structure for slider, i.e while creating the structure for slider you can define the unique id attribute for each li as following:

  Drupal also have the royalslider library integration which integrates the royal slider library


Attaching CSS to block doesn't work mymodule is in modules/custom directory.

$block['content']['#attached']['css'][] = drupal_get_path('module',
                                          'mymodule' . '/mymodule.css');

mymodule.css exists.

However file is not attached.

You have a typo in your statement. It should be:

$block['content']['#attached']['css'][] = drupal_get_path('module', 'mymodule') . '/mymodule.css';

Also, be sure to clear the cache after you add statements like this to your code.


Views Custom Join change the 'on' condition We are using Drupal commerce and have a report in views using commerce_line_item as the base. We need to be able to split the quantities up into multiple rows. So if a line item has a qty of 5 there should be 5 rows. I am trying to implement this:

https://stackoverflow.com/questions/22291814/mysql-return-result-by-quantity-per-row

I am adding a join in hook_views_query_alter but there does not appear to be a way of changing the join condition from = to <=.

LEFT JOIN {line_items_tally} line_items_tally ON commerce_line_item.quantity = line_items_tally.n

needs to be

LEFT JOIN {line_items_tally} line_items_tally ON commerce_line_item.quantity <= line_items_tally.n

Is there any way of doing that?

I ended up using hook_query_alter rather than hook_views_query_alter

/**
 * Implements hook_query_alter().
 */
function custom_query_alter(QueryAlterableInterface $query) {
  if ($query->hasTag('line_itmes_qty')) {
    $query->join('line_items_tally', 't', 't.n <= commerce_line_item.quantity');
  }
}


Drupal 8: Multi-sites in subdirectories not working I followed this tutorial(Drupal 7) but it not worked for me(Drupal 8):

Multi-site in subdirectories
https://www.drupal.org/docs/7/multisite-drupal/multi-site-in-subdirectories

This is my enviroment:

CentOs 7 with SELinux(mode: enforcing)
Varnish 4.0.3
Apache 2.4.23
Drupal 8.2.4

I need to create the next structure of sites:

/          <-- First site
/site2     <-- Second site
/site3     <-- Third site

In the file sites/sites.php i have:

$sites['localhost.site2'] = 'site2';
$sites['localhost.site3'] = 'site3';

In the directory sites/ i have:

default/
site2.localhost
site3.localhost

In the root of the drupal o have the next symlinks to .:

site2 -> .
site3 -> .

In my .htaccess file i have:

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} ^/site2/(.*)$
  RewriteRule ^(.*)$ /site2/index.php [L,QSA]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} ^/site3/(.*)$
  RewriteRule ^(.*)$ /site3/index.php [L,QSA]

When i tried to access to each subsite, he shows me the default. What is wrong?

Download latest  D8 version.
Extract and navigate into the
directory: /drupal/sites/
Create sites.php duplicating example.sites.php
Add the code to sites.php

$sites = array(
      'dogs.multisite.local' => 'dogs',
      'multisite.local.cats' => 'cats',
    );
Create two folders named 'cats' and 'dogs' on the sites folder.

/drupal/sites/dogs/
/drupal/sites/cats/

The /drupal/sites/default/ site will have default files we need to copy into each of our sites. Copy these files using the cp command in the sites directory:

cp default/default.settings.php dogs/settings.php
cp default/default.settings.php cats/settings.php
cp default/default.services.yml dogs/services.yml
cp default/default.services.yml cats/services.yml

Setup virtualhost

hosts

 127.0.0.1  multisite.local

httpd-vhosts.conf

<VirtualHost *:80>
ServerAdmin webmaster@multisite.local
DocumentRoot "/opt/lampp/htdocs/drupal"
ServerName multisite.local
ServerAlias    *.multisite.local multisite.local.*
ErrorLog "logs/multisite.local-error_log"
CustomLog "logs/multisite.local-access_log" common
</VirtualHost>

Once it is done, you can start the installation of your new website in a multisite context from the urls:

   http://dogs.multisite.local/
   http://multisite.local.cats/


How to add cancel button while clicking the Edit link in View? I created a content type and a view; when I click the edit link shown in the view, it redirects to the filled content type page, which contains only the Save, Preview, and  Delete buttons. I need to have a Cancel button too.

How do I add the Cancel button?

You can make use of the Content type extras module

label on manage field forms Add a 'Cancel' button to node edit forms
Ability to set node title visibility when viewing node Ability to
hide title of front page (takes precedence over content type setting)
Ability to add form submission buttons to top of 'Manage fields'

Or you could use the more buttons module

  MB provides a additional Create new action.

  This action can used as tab in addition to the node View or node Edit
  tab. This action can used as action link on the node edit forms.

MB allows to use own values for:

  Cancel button,
  Save and continue button, Save and create new button
  Create new tab


Drush 8 hangs with any command Up until recently, I've been using version 6 of drush, and it worked like a charm. Since I started delving into Drupal 8, I installed drush 7 on my Mac using the install instructions (using Composer) for global drush. Initially, it was fine, but whenever I try to run it now, it just hangs. When I run it with -d, it gets this far:

Using the Drush script found at /Users/steve/.composer/vendor/drush/drush/drush.launcher using pcntl_exec

Running which drush shows the correct path  (/Users/steve/.composer/vendor/bin/drush), but like I said, running drush by itself or with any other command, it just hangs. From what I understand, the only error logging is to the screen, but since there's nothing being displayed to the screen, I'm not sure where to look. I don't have memcache installed (unlike this guy), so I know that's not the problem. Any suggestions?

Thanks

UPDATE: I am using Drush 8 not Drush 7 (I fixed the title accordingly). After a couple days, it's back to hanging again, and even using -d shows nothing.

Only Drush 8 is compatible with Drupal 8. See http://docs.drush.org/en/master/install/#drupal-compatibility


Insert my files inside a custom table after upload? How to insert my uploaded files inside a custom table (as managed_file) after upload inside a custom form on DRupal 8 please ?

For moment, I have :

$form['images']['new']['local'] = array(
  '#title' => t('Upload Images'),
  '#type' => 'managed_file',

I need to use jquery, element_validate ? Other ?
Thanks.

Don't. It's a fundamentally bad idea to store data in custom table in Drupal 8. There are enough APIs and no support for that. Of course, hooks are still there so you can implement hook_entity_presave and then take the field data and write it out... but just say no :)


Unique IDs for nodes I would like every node created to have a unique ID. What's the best way to go about this? I know of the UUID module, but I don't really want the IDs to be formatted like a UUID. Does there exist a module that creates a unique ID that looks like (for example) an md5 hash?

The reason for doing this is that information about certain nodes has to be passed around between a few servers (in emails in some cases) and I don't wan't people to be able to have access to the drupal server's systems, I'd rather them see something like a hash as opposed to drupal's nid.

Interesting question. Here's how I'd do it.

Use Custom Tokens to create a custom token that runs the nid through md5();.
Use that custom token in Pathauto.


How to direct a dynamic url to a Drupal page I created a little web app that allows people to keep content on a page.  They can specify the url of the page.  Instead of accessing their page like this: http://example.com/stuff?page=their_url I want the url to be like this: http://example.com/stuff/their_url

But I can't figure out how to direct a dynamic url to a Drupal page.  I've even tried Apache redirects, but I can't get that working either.  I keep getting 404's.

I'm willing to use Apache rewrites to get to the right page.

I'm willing to point to a regular PHP file on the server and bootstrap Drupal, but so far I haven't been able to get that working.

I'm willing to put PHP code into a Drupal page.

I really don't want to write my own Drupal module, so if you want to offer some Drupal code, please tell me where to use it.

I'm willing to use a Drupal 7 module if you know of any.

Thanks a lot!

--
Magmatic

i think that you can use the :
function drupal_goto

but not sure if that is for your case.


Drupal Form Ajax not updating form on first click function _ajax_ticket_info($form,&$form_state)
{
    $subscriber = $form['info']['ticket']['subscribe'];
    _ticket_subscribe($subscriber['#value'],$subscriber['#name']);

    // Dunno if this is needed or not
    $form_state['rebuild'] = TRUE;

    return $form;
}
function _ticket_info($form,&$form_state,$node) {

    $is_subscribed = _ticket_is_subscribed($node->nid);
    $subscriber_count = count(_ticketsys_get_subscribers($node));

    $form = [
        '#prefix' => "
",
        '#suffix' => '
',
    ];
    // other form fields here not that important
    // just focusing on my problem
    $form['info']['ticket']['subscribe'] = [
    '#type' => 'button',
    '#value' => $is_subscribed,
    '#name' => $node->nid,
    '#id' => 'ticket-subscribe',
    '#ajax' => [
        'callback' => '_ajax_ticket_info',
        'wrapper' => 'ticket-info-form',
        'effect' => 'fade',
    ],
];
return $form;
}

So the problem is i'm using that code to update my form without reloading the page and when i do that it only executes the replacement on the second time i clicked the button $form['info']['ticket']['subscribe'] and i notice using inspect element on chrome that the form id and other form fields have --2 on their ids and increasing every time i click the Subscribe button

Any ideas whats wrong here. I really need to fix this thanks

Try changing the button type to "submit", and specifying a custom submit handler:

$form['info']['ticket']['subscribe'] = [
    '#type' => 'submit',
    '#submit' => [['ticket_submit_handler']]
    '#ajax' => [
        'callback' => 'ticket_ajax_callback',
        'wrapper' => 'ticket-info-form',
    ],

    // ...
];

In the submit handler:

Change any variables in form_state storage that need to persist.
Tell the form to rebuild itself (instead of doing a redirect after submission), in order to keep the form state.
Do other stuff.

e.g.

function ticket_submit_handler(&$form, &$form_state) {
    $form_state['storage'][] = ;
    $form_state['rebuild'] = TRUE;
    // ...
}

In the AJAX callback:

Return the part of the form that will replace the 'wrapper'. In your case, it seems to be the entire form.
Don't do anything else here.

e.g.

function ticket_ajax_callback(&$form, &$form_state) {
    return $form;
}

AFAIK, when the user clicks your AJAX button, the following functions will run, in order:

Form validation (if any).
ticket_submit_handler
Form builder, to rebuild the entire form, even if we only need a part.
ticket_ajax_callback, which returns a part of the form, which is sent to the browser.

For more information, see the example code in the Drupal 7 documentation.


Get Route Name from Path I am building a module on drupal 8 to make a redirection after a form is submitted

function form_redirect_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    $form['actions']['submit']['#submit'][] = 'ptt_contact_form_blocks_submit';
}

function ptt_contact_form_blocks_submit($form, FormStateInterface $form_state) {
    $form_state->setRedirect($route_name);
}

but for the setRedirect, it needs to have the route name. Like if i want to redirect to node/24, then how can i find the route name of the node?

Thanks!

check this one

function ptt_contact_form_blocks_submit($form, FormStateInterface $form_state) {
    $form_state->setRedirect('node/24'); // node/$node->nid
}


Contextual filter and exposed filter related I am facing a real problem and i can't manage to solve it.

I have some checkboxes in user profile based on a vocabulary.
I want to display all articles that have this tags in a view .
If user wants to see all articles he should choose on a select list what he want to display.
So i want to make a default for that page and if user wants something else to display based on a select option.

Ex: user X has checked in profile page options : management.
then he goes in news view and see all articles with tag management. If he change his mind and want to see other categories this should be done from a select.

I have done the first part that with default articles (i make a contextual field with default get ID from logged in user ->relationship from user and display content that have that terms-> this is a user entity view that displays related articles) when i put the exposed filter and select another value i get nothing. I think that view searches for that value in user checkboxes preferences in user profile.

What can i do to achive my goal?
Thank you

Probably I misunderstood your problem, but I put my solution anyway.

OK I have a view with entities of content type Foo and exposed filters as block, which appears on all pages.
I am storing filter values in user entity (same fields as in Foo - taxonomy term reference fields).

When URL has not exposed filters parameters (exposed filters form hasn't submitted) I try to set filters default values from user entity fields:

    /**
     * Implements hook_form_FORM_ID_alter
     */
    function mymod_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
     if (! _mymod_isFormSubmit()) {
     //exposed filters form hasn't submitted so I am using values from user entity
     global $user;
     $wrapper = entity_metadata_wrapper('user', $user);
     foreach(_mymod_getFiltersMapping() as $filterName => $fieldName ) {
      $tids = array();
      foreach($wrapper->{$fieldName}->value() as $term) {
        $tids[] = $term->tid;
     }
     $form_state['input'][$filterName] = empty($tids) ? 'All' : reset($tids);
    }
  }
}

It isn't working for me yet, I am getting always random values, maybe because usage of Better Exposed Filters form.


How do I make custom entity create new revision by default? I made a custom entity that extends RevisionableContentEntityBase. I can use the web interface to create entities. If I edit an entity and check the box Create new revision then a new revision will be created. There is no configuration form available to set the default for Create new revision.

The custom entity is quite simple. It has a few base fields and was built using drush generate module-content-entity.

How do I make my custom entity create a new revision by default?

Normally the default value is stored in bundle configurations. If you have no bundles then override getNewRevisionDefault() of your content entity form:

class MyEntityForm extends ContentEntityForm {

  protected function getNewRevisionDefault() {
    return TRUE;
  }

}

This class should already exist when you've generated the entity with Drush/Console. Check in the entity annotations that the class is used as form handler.


Display image from Webform submission using views I have created webform with title, description and upload file fields. And I have created views to display submission data in a grid view.

For images, it just giving me the image name with URL to image but it is not displaying as an image. I tried everything, but didn't find any solution. Please give me solution for displaying images in views.

This can not be done with webform module alone.
All you need to do is get help of 2 extra modules.

File Entity
Views Field View

Further you need to do following things.

Download and enable both of the modules and clear the cache.
Webform is storing file, not only image. I am assuming here you are only uploading image files, you can further get idea to show any type of file there. So go to Image File Type Display: admin/structure/file-types/manage/image/file-display and set the preview/image style. Or if you do not want to change settings for default view mode of the file, download another module Entity View Mode. Go to it's configuration and create specific display and set image style accordingly in file display settings.
Create a view of files, it should be a block. and there add contextual filter for the fid and add field "File: Rendered". You can set file view mode by this field. For your convenience I'm exporting the view below, you just need to import this.

    $view = new view();
    $view->name = 'file_view';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'file_managed';
    $view->human_name = 'File view';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'File view';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'perm';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'some';
    $handler->display->display_options['pager']['options']['items_per_page'] = '5';
    $handler->display->display_options['style_plugin'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Field: File: Name */
    $handler->display->display_options['fields']['filename']['id'] = 'filename';
    $handler->display->display_options['fields']['filename']['table'] = 'file_managed';
    $handler->display->display_options['fields']['filename']['field'] = 'filename';
    $handler->display->display_options['fields']['filename']['label'] = '';
    $handler->display->display_options['fields']['filename']['alter']['word_boundary'] = FALSE;
    $handler->display->display_options['fields']['filename']['alter']['ellipsis'] = FALSE;
    /* Field: File: Rendered */
    $handler->display->display_options['fields']['rendered']['id'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['table'] = 'file_managed';
    $handler->display->display_options['fields']['rendered']['field'] = 'rendered';
    $handler->display->display_options['fields']['rendered']['label'] = '';
    $handler->display->display_options['fields']['rendered']['element_label_colon'] = FALSE;
    /* Contextual filter: File: File ID */
    $handler->display->display_options['arguments']['fid']['id'] = 'fid';
    $handler->display->display_options['arguments']['fid']['table'] = 'file_managed';
    $handler->display->display_options['arguments']['fid']['field'] = 'fid';
    $handler->display->display_options['arguments']['fid']['default_action'] = 'default';
    $handler->display->display_options['arguments']['fid']['default_argument_type'] = 'node';
    $handler->display->display_options['arguments']['fid']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['fid']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['fid']['summary_options']['items_per_page'] = '25';

    /* Display: Single File View */
    $handler = $view->new_display('block', 'Single File View', 'block');

Now in your main view (where you are showing submissions). Add a new relationship for Webform submissions: Data. You'll need to set the nid for the webform here and select the image component.
Add new field to the view submission data: Value (raw). This will give you the file_id for the associated file. Exclude it from display.
Add another field Global: View. Select the view you imported and the block display. In contextual filter set [!data] from replacement patterns. It was the raw value of the field which you excluded from the display. And Here you go, save the view and rock :). Thanks for asking such good question. Still if you face any problem during this tutorial, ask me.


D7: Newsletter type project.The articles are grouped in a set (newsletter) published on a regular basis My project is as follows:

News will be published like printed news letters meaning that no ongoing updating&publishing but clear intervals (in other words the articles need to be grouped together on the criteria of issue..issue January, issue February etc... At the moment plan is that publishing interval would be a few months.

What modules and approach would you choose for this? I know prosepoint can do this...but is no longer free and I need to make it in Drupal.

I need to dismiss the confusion with simplenews module. The newsletter doesn't need to be delivered by email (tough this would be one functionality) but displayed on the website.

Regards

IMHO if your newsletter isn't meant to be emailed, the easier solution is using views with a filter on the date of nodes + a module that gives you the pdf display, like Views_PDF.

Then if you want to send your issues by mail, you may extend with Views pdf mime mail to attach the exact pdf to your mails, but it's still under development and I'm not sure if it works.
Please consider than whenever you talk about email newsletters, probably the most complete solution is still Simplenews and its submodules. If I were you, I would use Simplenews Scheduler + Insert view, like I did in a similar situation [D6].

Hope it helps


Get field widget settings In Drupal 7 they can be found in object that is returned by field_info_instance().
Is there a way to get widget settings for certain field name and bundle in Drupal 8?

I found the way :-)

$settings = entity_get_form_display('node', 'article', 'default')
  ->getComponent('field_image')['settings'];


How can I translate the particular field or content in english to german language? As I want to convert the particular field or content from drupal to german language.Is any other way to do this .Also i tried the entity translation to convert the german language But Its convert all the content in my site to german I need only convert the particular field to german language Is it possible to do this in drupal .

Any one Much appreciated.

It's very easy, you need to install the Internationalization module where you find  some sub-module to do that .
Youn need to install the Localization Update module it's very helpful .


How to add a div wrapper around a zone? I'm using the Omega theme and have a zone that I need a div around for a certain content type. Trying to figure out the best way to do it. Was thinking a preprocess, but no clue which. Fairly new to Drupal so bare with me.

Adding something like this to the template.php of your subtheme should get you in the right direction.

function MYTHEME_alpha_preprocess_region(&$vars) {
  $menu_object = menu_get_object();
  if (isset($menu_object->type) && $vars['region'] == 'content') {
    $vars['theme_hook_suggestions'][] = 'region__content__'.$menu_object->type;
    $vars['attributes_array']['class'][] = 'region-content-'.$menu_object->type;
  }
}

Then you just need to create .tpl files for them in the same way you would for other content type based tpl files (example: region--menu--page.tpl.php)


Can't translate pager labels in View I have a view to show post teasers. Inside the view I go to 'translate view' and change the values for tags, date, etc. accordingly. Everything translates fine except the text for 'first' and 'last', which stay in the default language (Spanish) no matter if I switch to English (they stay as 'primera' and 'última'). Every other label works so I'm at a loss here.

Can someone point out if I'm doing something wrong? Maybe I should enable another module but I don't think so. Every other node, block, page and menu works fine in both languages. The problem is just with the mentioned labels.

I'd appreciate any pointers.

This seems to be solved by drupal community:
https://drupal.org/node/2112281#comment-7971057


User error: "attributes" is an invalid render array key when rendering image I'm seeing the following error on my Drupal 8.4.3 site:

  User error: "attributes" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

It happens when rendering a Paragraph that has a multi-value field in it, which uses the Responsive Image formatter.

The Twig template looks like this:

...
{% for item in items %}
  {% set original_image = item.content['#item'].getValue()['original_url'] %}
  <a href="#" target="_blank" rel="nofollow">
    {{ item }}
  </a>
{% endfor %}
....

The problem is on that middle line {{ item }}. It prints the error message once per item in the "items" array. According to the Twig debug output in the HTML source, the next inner Twig template should be core/themes/stable/templates/field/responsive-image-formatter.html.twig. For fun, I went into that template and deleted every line, leaving an empty file. And the error is still there. So it's happening somewhere between the outer template and the inner template.

When I put a step debugger on line 97, I see a variable $elements with the following structure:

[
'content' => ... render array stuff in here ...,
'attributes' => Drupal\Core\Template\Attribute[ storage => [] ],  // <-- what's this?
'#printed' => false,
'#cache' => ...,
'#attached' => []
]

It seems that the problem is that Drupal wants anything not starting with # to be a valid render array. Which the 'attributes' element isn't. But I can't figure out how that got in there. I don't think any of my custom code could generate something like "'storage' => []". I've been poring over the stack trace for hours and I can't tell where it's coming from.

Anyone know of a contribibuted or core module that could generate this? I would love to file an issue in the Drupal issue queue, but I can't even figure out which module is causing this.

System specs:

Drupal 8.4.3
Paragraphs 8.x-1.2 (the field in question is inside a Paragraph entity)
Multiversion 8.x-1.0-beta7 (in case that matters; it does change entity structure somewhat)
Image Lazyloader 8.x-1.0-alpha2 (I've seen this in the stack trace a few times)
PHP 7.0.26
Ubuntu 16.04

Yes, it seems like you are not supposed to render item in a field template. Render item.attributes and item.content separately:

{{ item.content }}

Or the attributes in a  if the
 doesn't work with your layout and you need the attributes:

{{ item.content }}

BTW storage' => [] is part of the Attribute object any code can store attributes on its way until it reaches your template. So it's a good idea to print the attributes, even if they are now empty, because you don't know which extension you might want to install in the future and debugging will then be some fun until you'll find out that one of the field templates is not fully working.


Migration only doing one row at a time? I have a migration class set up that takes from an XML source ID list that points to individual XML files with data which is then imported into nodes.  The migration works but only one at a time.  There are no errors in the messages for migration, apache error log, syslog, and doing drupal_debug in all steps of the migration only shows that the migration goes through one row then stops.

Is there any common issue that might be causing this behavior?

The issue was a standard PHP issue in a function that was being called during the batch operation.  In this case, the error does not matter, what matters is that I could not see anywhere that the error was happening.

Running migrations via the Migrate UI will not show errors, in some cases, anywhere.  To better troubleshoot it is recommended that migrations are run via Drush.  Running my migration through Drush I was able to see where the import was failing and why.


custom entityreference widget not saving field I am trying to create a custom widget for the entity reference field type which will be a hidden field with its value set to the current page's node id. This is my code:

function my_example_field_widget_info() {
  return array(
    'my_example_hidden_nid' => array(
      'label' => t('Hidden nid field'),
      'field types' => array('entityreference'),
    )
  );
}

/* implements hook_field_widget_form*/
function my_example_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element['hidden_nid'] = array(
    '#type'=>'textfield',
    '#description'=>t('The nid of the Photo node which product line item refers to'),
    '#default_value'=>arg(1),
  );
  return $element;
}

I first tried this as a textfield, and saw that the form field was being properly populated.

This field is attached to a Drupal Commerce Line Item, to produce some custom functionality. However, when I clicked Add to Cart, and the Line Item was saved, this entityreference field was not saved into the database.
(Since I am adding a widget to a previously defined field type, I did not use any hook_field_schema()'s)

How can I fix this?

For one, in your hook_field_widget_form, the $element should be built with a Union (like $element += array(...)) and not replaced. Refer this example at the api page.


How to get all field name of field type? I want get all the field names for the fields whose field type is image, by code. How can do that?

You are looking for EntityFieldManager::getFieldMapByFieldType():

\Drupal::service('entity_field.manager')->getFieldMapByFieldType('image');


Is there any convention about the form IDs? Is there a convention for the form IDs?

I see that core sometimes uses module_name.form_name and sometimes module_name_form_name.
In my case, I'm using module_name.form_name.

Drupal core doesn't use the dot in the form IDs because, as the documentation for FormInterface::getFormId() says, the form ID should be a unique string that can be a valid PHP function name, since it's used in hook implementation names such as hook_form_FORM_ID_alter().

The form IDs Drupal core uses follow the <module name>_<form name> schema, so you will find form IDs like the following.

user_admin_settings
action_admin_manage
layout_builder_add_block

As long as the form ID is unique, any scheme would work. The convention to prefix an ID with the module name (i.e. the module machine name) has been used from Drupal since many years.


Content profile image (CCK imagefield) instead of default drupal picture tried what igorik said on drupal.org == http://drupal.org/node/609454#comment-2172258
Placed user-picture.tpl.php in my theme directory and replaced code inside it:

<div class="picture">
<?php print $picture; ?>
</div>

to:

<?php
$img_url = $content_profile->get_variable('profile', 'field_photo');
print l(theme('imagecache', 'msg_profile_pic', $img_url), 'user/' . $account->uid );
?>

but all what im getting after these actions is WSOD... set to display errors true in index.php, but still can't see any errors. Help me guys! Thanks

To find out errors in WSOD you can look at you Apache Error Log, in Ubuntu you can execute tail -f /var/log/apache2/error.log and you will see the php error.

It's pretty sure the problem come from $content_profile which doesn't seem to be instanciated and thus don't carry the whole content profile object. You can load it using content_profile_load.


How do i override a View attachment glossary fields link or url Is there a way of overriding an attachment views field's url link that is in glossary mode?

I've tried altering the url and link property of the field in the pre-render and post render theme functions, and I can alter their values but it never sticks. I've tried the .tpl.php file but then the html tags.

I need to make them links to anchor links show.

So i dont have a definitive yes or no, but if i was to wager a bet i would say... No. There is no way of overriding the glossary mode's url link and make it link to content on the current page. I saw someone else ask this question better than I did back in 2012 and no one answered him, which pushed me to do this in the old way, by building a custom html table and doing the leg work there. So the answer is no need to, just do it in the .tpl.php file.


How to define an optional argument to Route callback I want define a simple controller action, which receive optional argument:

<?php

namespace Drupal\hello\Controller;

class SimpleCallback extends ControllerBase
{
    public function sayHiAction($name = 'there')
    {
        return new Response('Hi ' . $name, 200);
    }
}
?>

If I define the routing like this

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
  requirements:
      _permission: 'access content'

GET /hello just gives me 404 response.

Follow official documentation, I updated my route:

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    custom_arg: 'there'
  requirements:
      _permission: 'access content'

But nothing changed.

The docs you link to say:

  Finally, if any static arguments should be passed to the controller, provide those in the defaults array as well. Name them to match the arguments of your controller method. See below.

Emphasis mine.

So your code should be:

# file @hello.routing.yml
hello.sayHi:
  path: '/hello/{name}'
  defaults:
    _title: 'Say Hi'
    _content: 'Drupal\hello\Controller\SimpleCallback::sayHiAction'
    name: 'there'
  requirements:
      _permission: 'access content'

See also Required and Optional Placeholders in the Symfony routing docs.


Fetching Views 3 implementation from code I am using Drupal 7. What I want to do is to fetch the View 3 implementation from code, rather than from database, so that I can export my view, and put it in a function that would be available to all my team members w/o the need of importing the database script.

There are quite some different ways to achieve this

Use the ctools bulk export module, this will provide you some example code to use
use the features module, which gives you a full module


Why can't I modify my comment form using hook_form_alter I have enabled comments for a custom node type.

I am trying to theme that comment form using hook_form_alter(&$form, &$form_state) (For example, I'd like to remove the label of the comment_body form field)

To do that, I use the following function:

function MYTHEME_form_comment_form_alter(&$form, &$form_state) {
    $form['comment_body']['und']['#title'][0] = '';
}

However in the output the title of the form field is still there:

Here's the markup:

The value of $form does not correspond to what I am used to see. Here's a screenshot from my debugger:

It looks like the label "Comment*" is not from comment_body container wrapper, then again comment_body shouldnt be of type container.

Most likely the actual comment field is somewhere not visible of your debug screenshot. This is because drupal core comment module form doesnt use normal form api structure where containers only reference children and reverse. Instead the actual field is placed directly to container. Luckily drupal_render has no problem with neither structure.

Removing the label should not require specifying language on the actual field. It should be as easy as

$form['comment_body']['#title']='';

Instead with funky comment form render array you need to specify language of the containers sub items, hence the path transforms to

$form['comment_body'][LANGUAGE_NONE][0]['#title']=''


How to use field value as class? Drupal 7 Not sure that is the best title...

I want add a field to a content type eg. Priority. My preference would be to make this a taxonomy reference (with Autocomplete term widget (tagging)).

Then probably through a preprocess I would like to add any terms entered as classes to the node (in particular when a teaser but that's not important).

I am not the world's greatest php coder and apologise if this doesn't make a great deal of sense. I have been banging my head against the wall for three days now and any help would be greatly appreciated :)

I gather it has something to do with MYTHEME_preprocess_node and $variables['classes_array'][], but I don't seem to be able to put my finger on it.

This should be a start.

function mytheme_preprocess_node (&$variables)
{
  $node = $variables["node"];

  if (isset($node->field_foo["und"][0]["taxonomy_term"])) {
    foreach ($node->field_foo["und"] as $foo) {
      $term = $foo["taxonomy_term"];
      $variables["classes_array"][] = "term-" . str_replace(" ", "-", strtolower($term->name));
    }
  }
}

Note, this is barely tested  and your exact situation may vary.  It assumes field_foo is the machine name for your taxonomy reference, and your theme is flattening $variables["classes_array"] for use in node.tpl.php.


How add a custom page template for an article node Hi I want to create an article then define a alias path for it then change template of that page. For example I add an article with title "categories" and no other content like body or image. Then I define "categories" alias for it. Now when I add "page--categories.tpl.php" in my theme template folder nothing happened to page
    http://example.com/categories
and I just see a white page in content region.

Refer this url http://drupalknowledge.blogspot.in/2012/01/different-page-template-for-different.html

You can print  $vars['node'] variable and get the particular node path to give different template.

I hope this will help you.


How to replace url of taxonomy label link? I want to alter url of a field and his display.
The field is a taxonomy label with link to the entity.
The default url is : taxonomy/term/{tid}

I wanto to chage with : my_specific_page?technologie={tid} (used to prepopulate exposed filter)

I tried with :

function MYTHEME_preprocess_field__field_technologie(&$variables, $hook){
  $element = $variables['element'];

  foreach ($variables['items'] as $item) {

    $route_name = 'entity.node.canonical';
    $params     = 39;

    $options = [
      'query' => ['technologie' => 27],
    ];
    $url = Url::fromRoute($route_name, array('node' => $params), $options);

    $item['content']['#url'] = $url;
  }
}

I think i need to replace routeName attribut, but how ?

Content type : "manage field"

Content type : "manage display"

Kint result $variables['element']
[]3

I found solution :

function MYTHEME_preprocess_field__field_technologie(&$variables, $hook){
  $element = $variables['element'];

  foreach ($variables['items'] as $index => $item) {

    $route_name = 'entity.node.canonical';
    $params     = 39;
    $tid = $item['content']['#options']['entity']->id();

    $options = [
      'query' => ['technologie' => $tid],
    ];

    $url = Url::fromRoute($route_name, array('node' => $params), $options);
    $variables['items'][$index]['content']['#url'] = $url;
  }
}


How do I nest two field in my node.tpl.php? I have two fields of multiple values. When I print render($content['field_photo']) and render($content['field_photo_caption']) I get:

caption

caption

caption

How do I nest the values to get:

caption

caption

caption

Here is the code to solve problem

  $image = field_get_items('node', $node, 'field_text_multiple');
  $text = field_get_items('node', $node, 'field_multiple_second');
  foreach ($text as $key => $value) {
    $second_field[] = field_view_value('node', $node, 'field_multiple_second', $text[$key]);
  }
  foreach ($image as $key => $value) {
    $output = field_view_value('node', $node, 'field_text_multiple', $image[$key]);
    print render($output);
    print "
";
    print render($second_field[$key]);
    print "
";
  }


How to get previous page title How can I get the previous viewed page title? For example, I visited node/21 then, I navigate to node/22, then in node/22 I'd like to get the node/21's title. In node/22, there's a text field where the default value is the node/21's title. Is there any function I can use for this? Please help as I badly needed this. Thank you.

You can use $_SERVER['HTTP_REFERER'] with PHP to get the URL of the last page you were on. This is not a reliable solution because not all user agents support it. plus users can manually intervene with the previous page and mess things up.

If a client side solution is sufficient for you, you can use javascript's document.referrer.

You could use a querystring as well and append that to the URL and read it from the page you're going to.

website.com/secondPage?refer=lastPageIWasOn

// then grab the value from the second page
$last_page_value = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';

// or use drupal_get_query_parameters()

// Then do something with it

Or you could use cookie/session to do this

if (!isset($_SESSION)) {
    session_start();
}
if (!isset($_SESSION['referrer'])) {
    $_SESSION['lastpage'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
}

// second page
$referer = isset($_SESSION['lastpage']) ? $_SESSION['lastpage'] : '';

This is a very common use case and StackOverflow has several questions on it with PHP. I suggest googling it. Translating it to drupal will depend on what you're doing with it.


EntityFieldQuery order by title I'm getting an error when using this entity field query, the error says that that the field title cannot be found but I'm only querying the basic node table.

$product_query->entityCondition('entity_type', 'node')->entityCondition('bundle', 'product')->fieldCondition('field_line', 'tid', $selected)->fieldOrderBy('title', 'DESC');

The node title is a property, not a field:

$product_query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'product')
  ->fieldCondition('field_line', 'tid', $selected)
  ->propertyOrderBy('title', 'DESC');


Print current base language in tpl.php I statically linked an anchor to my /cart page on page.tpl.php, but since it's a multi language website, when I'm on http://localhost/fr it still goes to http://localhost/cart instead of http://localhost/fr/cart

I'd like to know how to print the current base language path or base_url and concatenate it with /cart

thanks.

If you want to display the cart link in template you better do it with l or url function, example:

in page.tpl.php file:

<?php print l(t('Cart', 'cart')) ?>
 // first way

<a href="<?php print url('cart') ?>">Cart
 // the second way


Exporting Blocks from Drupal 6 to 7 Can anyone tell me the best way to export blocks from Drupal 6 to 7?

Boxes? Features? A Straight field for filed export?

Assuming they are straight up Blocks with body content (not View blocks or other contrib generated blocks), I would create a module that scripts and creates them on install. If you have many blocks, do them in small batches (breaking them up across update_n hooks).

That way you can also test them in small batches and get it right. Once up, you can disable the module and remove it.

See:

https://drupal.stackexchange.com/a/72946/57
https://www.drupal.org/node/1709954#comment-8592077


Drupal views - 2 latest reports and related content My Drupal site contains a certain type of report, and these reports sometimes have 1 or more amendments, which will have field_related_content pointing to the report they're amending.

I'm trying to set up a view that will display the latest two reports, plus any amendments to those reports, but I haven't been able to figure out how to do it.

Can Views filters refer to results from other filters?

You can create view in a view using View Field View (https://drupal.org/project/views_field_view):

Create a view of reports
Create a view of amendments which takes a contextual filter of node id and filters amendments which have a field reference with that node id value
Put the view amendments view in a view of reports as a field (using above mentioned module - see it's documentation for more specific info if necessary)

Btw. just a thought - isn't it possible for you to switch the architecture and have the node reference field in the document content type, referencing the amendments? - this way you wouldn't need a view in a view and it would be easier to display it.


hook_breadcrumb() doesn't show breadcrumb Hello Drupal community,

I am trying to alter the breadcrumb in my site with the hook_breadcrumb($variables). I've used drupal_set_breadcrumb() function without any result. Here's my function in template.php :

/**
 * implements theme_breadcrumbs
 * @param unknown $variables
 */
function MYFUNCTION_breadcrumb($variables) {
  // On récupère les items de la page s'ils existent
  dpm($variables['breadcrumb']);
    if ($item = menu_get_item ()) {
      if (isset ( $item ['page_arguments'] )) {
        foreach ( $item ['page_arguments'] as $argument ) {
          // Keeping the name of the taxonomy in $field_name
          if (isset ( $argument->field_article_type )) {
            $field_name = "field_article_type";
          } elseif (isset ( $argument->field_type_remontee_document )) {
            $field_name = "field_type_remontee_document";
          } elseif (isset ( $argument->field_lien_type )) {
            $field_name = "field_lien_type";
          } elseif (isset ( $argument->field_type_de_contenu )) {
            $field_name = "field_type_de_contenu";
          } else {
            $field_name = "  ";
          }
          // retrieving the field and then the link to the taxoomy in the form term/taxonomy/%
          if ($field = field_get_items ( 'node', $argument, $field_name )) {
            foreach ( $field as $taxonomy ) {
              $taxo = taxonomy_term_load($taxonomy['tid']);
              $nom_taxo = $taxo->name;
              foreach ( $taxo->field_taxo_list as $taxo_link ) {
                foreach ( $taxo_link as $link ) {
                  $lien_taxo = $link ['value'];
                  $title = $item ['title'];
                  $crumbs = array ();
                  $crumbs [] = l ( t ( 'Accueil' ), '<front>' );
                  $crumbs [] = l ( $nom_taxo, $lien_taxo );
                  $crumbs [] = l ( $title );
                  dpm($crumbs);
                  drupal_set_breadcrumb ( $crumbs );
                }
              }
            }
          }
        }
      }
    }
}

Can anyone help ?

Thank you,

I finally figured out how to alter the breadcrumb. The function needed to return a string

  function MYFUNCTION_breadcrumb($variables) {
    // On récupère les items de la page s'ils existent
    if (drupal_is_front_page ()) {
      return '';
    }
    if ($item = menu_get_item ()) {
      $title = (isset ( $item ['title'] ) ? $item ['title'] : false);
      $last = '
';
      $separator = '' . $variables ['crumbs_separator'] . ' ';
      $first_crumb = '
Accueil' . $separator;
      $key = count ( $variables ['breadcrumb'] ) - 2;
      $final_temp = ($variables ['breadcrumb'] [$key]);
      $final_crumb = ((isset ( $title ) && $title != "") ? ('' . $title . '') : ($final_temp));
      if (isset ( $item ['page_arguments'] )) {
        foreach ( $item ['page_arguments'] as $argument ) {
          // Keeping the name of the taxonomy in $field_name
          if (isset ( $argument->field_article_type )) {
            $field_name = "field_article_type";
          } elseif (isset ( $argument->field_type_remontee_document )) {
            $field_name = "field_type_remontee_document";
          } elseif (isset ( $argument->field_lien_type )) {
            $field_name = "field_lien_type";
          } elseif (isset ( $argument->field_type_de_contenu )) {
            $field_name = "field_type_de_contenu";
          } else {
            $middle_crumb = "";
          }
          // retrieving the field and then the link to the taxoomy in the form term/taxonomy/%
          if (isset ( $field_name ) && $field = field_get_items ( 'node', $argument, $field_name )) {
            foreach ( $field as $taxonomy ) {
              $taxo = taxonomy_term_load ( $taxonomy ['tid'] );
              $nom_taxo = $taxo->name;
              foreach ( $taxo->field_taxo_list as $taxo_link ) {
                foreach ( $taxo_link as $link ) {
                  $lien_taxo = $link ['value'];
                  $lien_taxo = (substr ( $lien_taxo, 0, 1 ) == "/") ? substr ( $lien_taxo, 1 ) : $lien_taxo;
                  $middle_crumb = '' . $nom_taxo . '' . $separator;
                }
              }
            }
          }

          $crumbs = isset ( $final_crumb ) ? $first_crumb . $middle_crumb . $final_crumb . $last : '';
          // And here is returned a string
          return $crumbs;
        }
      }
    }
  }


Custom theme function and template suggestion I'm trying to create a theme function, with a template:

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
    ),
  );
}

The my-template.tpl.php file is in the module directory and it works, I have added this to my page.tpl.php:

<?php print theme('custom_function', array()); ?>

I've tried to copy that template on my theme, but it doesn't work, Drupal always reads the module template, not the theme.

Have I forgotten something?

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
      'path' => path_to_theme(),
    ),
  );
}

OR for the my-template.tpl.php file is in the module directory

/**
 * Implements hook_theme().
 */
function mycustomtheme_theme($existing, $type, $theme, $path) {
  return array(
    'custom_function' => array(
      'template' => 'my-template',
      'path' => drupal_get_path('module', 'mycustomtheme'),
    ),
  );
}


How to keep track of days online? I'd like to display the total number of days that users were online in a View on their profile pages.

How can I do this?

You can use Visitors module.
It will give you the following reports:

View pages that have recently been visited.
View pages that have been hit frequently.
View pages count per month.
View pages count per day of month.
View pages count per day of week.
View pages count per hour.
View pages count per host.
View access log.
View user activity report (hits, nodes, comments).
View referer list.

and many more things.
Maybe for your requirement you need some customization.


Working with template suggestions on Drupal 8 I need Drupal to use a custom page template if the URL contains a particular _GET parameter.

In D7 I would do something like this in the theme's template.php:

function mytheme_preprocess_page(&$variables) {
      if($_GET['isCustomTpl'] == true)
        $variables['theme_hook_suggestions'][] =  'page__myCustomTpl';
}

It doesn't work in D8 though (I would have been surprised by the opposite, considering all the architectural changes in the theme layer).

Any ideas?

Bonus question: is it possible to define such a function in a module, so that i can release it publicly without having the users to edit their themes?

You can implement the new hook_theme_suggestions_HOOK_alter() hook.

  Alters named suggestions for a specific theme hook.

  This hook allows any module or theme to provide altenative theme function or template name suggestions and reorder or remove suggestions provided by hook_theme_suggestions_HOOK() or by earlier invocations of this hook.

You can use it like so

function MYMODULE_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if (\Drupal::request()->query->get('foo') == 'bar') {
    $suggestions[] = 'page__myCustomTpl';
  }
}

You can implement it in either a module or theme


Putting headings between content fields I am creating content and in fields i want to categorize fields, like a heading and then its related fields.For eg this is html field i m converting into drupal 7.

Now how can i get this heading project report information and construction details in creating or viewing content

Here is an example of putting heading (fieldset) on a comment form that I found a while back: click here.

Basically you need to do a hook_form_alter().

Start by creating a field set:

fucntion HOOK_form_FORM_ID_alter() {

$form['project_report_information'] = array(
    '#type' => 'fieldset',
    '#title' => t('Project Report Information'),
    '#collapsible' => FALSE,
  );

Next, add your fields to the field set and remove the field outside the fieldset:

$form['project_report_information']['subject'] = $form['your_field'];  //add to field set
unset($form['your_field']);                                            //remove field outside
$form['project_report_information']['your_field']['#weight'] = -10;    //of fieldset

Now repeat this for all fields and fieldsets you want.

Look over the link for a more detailed example of someone doing this. What you want is about half way down the page.


Strict warning: Only variables should be passed by reference in Open Restaurant I installed Open Restaurant based on Drupal 7.x.

As soon as I insert any menu item into create categories, I get this warning:

  Strict warning: Only variables should be passed by reference in sizzle_preprocess_views_view__content__menus__all_menus() (line 69 of /web/htdocs/xxxxxxxxxxx/home/profiles/restaurant/themes/sizzle/includes/menu.inc).

I checked the line and I got this code:

// Render the category and add it to template.
$variables['term'] = drupal_render(taxonomy_term_view($term, $view_mode));

I don't know how to improve this, in order to solve the issue.
Writing to the group that made Open Restaurant I didn't got any answer. Hence my post here.

drupal_render takes reference. taxonomy_term_view($term, $view_mode) is not a variable, so you shouldn't use it in places where reference is needed - because if something takes reference, it will try to update what it got, and it's impossible with a function. So to fix this, you need to create variable, then store result of taxonomy_term_view in it, and pass that variable to drupal_render.

Then, create patch file nd post it in their issue queue for everybody to see.


Relation with one content type to other How can I give relation once content type to other. Eg If I have a product and the product sub items. I need to make a product content and a product_sub_item content type. Also need to select the product while creating the sub item. How to achieve this relation

Check out the module "References". It allows you to create a field where you can reference on other content types and nodes.


Drush remote with switching shell users (sudo) Problem: I have a remote server with SSH access where the Drupal site can only be accessed as another user (www-data). My own shell user is not able to use drush directly for security reasons.

So how can I run all drush remote commands as www-data? I have sudo priviledged to execute commands as root.

My aliases.drushrc.php:

<?php

$aliases['accounting-phd'] = array(
  'root' => '/var/www/example/docroot',
  'uri' => 'example.com',
  'remote-host' => 'server.example.com',
  'ssh-options' => '-t',
  'path-aliases' => array(
    '%drush-script' => '/home/klausi/drush-remote.sh',
  ),
);

And in drush-remote.sh on the server:

#!/bin/bash
sudo su www-data -c "drush $@"

This prompts me for my password successfully, but then fails with

su: unrecognized option '--root=/var/www/example/docroot'
Usage: su [options] [LOGIN]

How can I separate the options from the su command?

Set 'remote-user' => 'www-data' in your site alias, and Drush will exec the remote Drush as the www-data user.  ssh-copy-id www-data@server.example.com, and you'll be all ready to go.


Database system table problem I read this article.
Where is the location of "system" table.

Is the image "system" table?

phpMyAdmin

To disable a module via phpMyAdmin you must login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save.

Yes, that is the system table, which stores details about available modules, themes and theme engines.

For more information about the system table schema, refer to the technical documentation at:

system_schema

from:

 $schema['system'] = array(
    'description' => "A list of all modules, themes, and theme engines that are or have been installed in Drupal's file system.",

and also, it's usage by:

system_list

  Builds a list of bootstrap modules and enabled modules and themes.


Profile2 Template for edit page i already searched all relevant drupal sites - but without success.
I have to create a own template file for the "edit user profile" site of the module Profile2.

As far as i know, i have to hook the new templatefile in the template.php of my theme - but what keywords and syntax do i need to accomplish that?

Every hint would be great!
Thanks.

I did this way to create my own "edit user profile" for profiles of profile2 module.

function customtheme_theme() {
    $items = array();
    $items['user_profile_form'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'customtheme') . '/templates',
        'template' => 'user-profile-form',
        'preprocess functions' => array(
             'customtheme_preprocess_user_profile_form'
        ),
    );
    return $items;
}

I put customtheme_theme() function into my template.php file of customtheme theme. (a custom theme that i used for my website)
After that i created the template file user-profile-form.tpl.php and placed in the templates folder of my theme.
The customtheme_preprocess_user_profile_form function you can use that for changing some variables before render the profile form or if you dont need any changes you can remove the preprocess_functions.
After add the customtheme_theme(), create user-profile-form.tpl.php template. You have to clear cache and you can see the layout change for user-profile-form.


Function to list all the blocks I am searching for a function that list all the blocks that are enabled in a theme. Is there any function for this purpose?

The function block_admin_display_prepare_blocks() is the function used in the block module admin page for this purpose, but it's not part of the documented API, so you cannot absolutely rely on it. You would need code along the following lines:

module_load_include('inc', 'block', 'block.admin');
global $theme_key;
$blocks = block_admin_display_prepare_blocks($theme_key);
...

This will return all blocks, unlike block_list() which only returns those for the current user and for the current page.


Add span inside views pager I need to add a single span inside of the list items of a views pager. This needs to be there even when the list item doesnt contain a link (when you are on the current pager's page).

I cant see any tpl files for doing this (my preferred method as im more of a themer.)

Ive looked for a theme override and ive found the following. The problem is that I cant figure where I would add the span.

function theme_views_mini_pager($vars) {
  global $pager_page_array, $pager_total;

  $tags = $vars['tags'];
  $element = $vars['element'];
  $parameters = $vars['parameters'];

  // current is the page we are currently paged to
  $pager_current = $pager_page_array[$element] + 1;
  // max is the maximum page number
  $pager_max = $pager_total[$element];
  // End of marker calculations.

  if ($pager_total[$element] > 1) {

    $li_previous = theme('pager_previous',
      array(
        'text' => (isset($tags[1]) ? $tags[1] : t('‹‹')),
        'element' => $element,
        'interval' => 1,
        'parameters' => $parameters,
      )
    );
    if (empty($li_previous)) {
      $li_previous = "&nbsp;";
    }

    $li_next = theme('pager_next',
      array(
        'text' => (isset($tags[3]) ? $tags[3] : t('››')),
        'element' => $element,
        'interval' => 1,
        'parameters' => $parameters,
      )
    );

    if (empty($li_next)) {
      $li_next = "&nbsp;";
    }

    $items[] = array(
      'class' => array('pager-previous'),
      'data' => $li_previous,
    );

    $items[] = array(
      'class' => array('pager-current'),
      'data' => t('@current of @max', array('@current' => $pager_current, '@max' => $pager_max)),
    );

    $items[] = array(
      'class' => array('pager-next'),
      'data' => $li_next,
    );
    return theme('item_list',
      array(
        'items' => $items,
        'title' => NULL,
        'type' => 'ul',
        'attributes' => array('class' => array('pager')),
      )
    );
  }
}

Have a look at YOUR_SITE_ROOT/includes/pager.inc

I think you are looking for the theme_pager_previous() and theme_pager_next() functions.


Commerce checkout form all pane errors to be displayed on top of form I am using latest commerce module with D7 site. By default commerce displays form errors inside individual commerce checkout form panes. This is designed by default and every pane has it's own validation callback. So this is different from Drupal's form API error displaying.

Is it possible to display them at the top of the form, same as Drupal form API does it? Does form_set_error works well for all checkout form elements and they get error class? (it seems to not work for me).

As Ryan mentioned, it's difficult to change that behaviour server-side, however you could move the error messages to the top of the page with JavaScript instead.

e.g

style.css

/* Hide checkout messages by default to show with JS later */
body.page-checkout .messages{
  display:none;
}

script.js

Drupal.behaviors.moveCheckoutMessages = function (context) {
  $('body.page-checkout form .messages', context).each(function () {
    $('.region-content').prepend($(this));
    $(this).css({"display":"block"});
  });
}

A client-side approach like that should work.


How do I programatically create a node, add a menu item, and add a path alias? I am using Drupal 6. I have an external database that I need to somehow turn into nodes so that our Drupal site can display the content and search the content with Solr. I currently have a module which displays pages and queries the database directly each time these pages are viewed. This is not an optimal solution because these pages are not found when a user uses our search.

I know that I can iterate through the database items, create a $node object and use node_save() to create nodes.

1) Can I set a specific NID such as $node->nid = 9999999 . $some_database_key so that I know these nodes can be referenced later for updating?

I could not get this to work, but I did figure out this solution:
I created a database table for my module similar to the one in the node_example module. Using this and a custom content type, I could create nodes. I could not get it to work properly until I used

$node = node_submit($node);

prior to calling

node_save($node);

2) How do I create menu items for these new nodes?

Solution

$link = array();
$link['menu_name'] = 'custom_menu'; // Fill out your menu name or just use navigation
$link['link_title'] = 'Title Here'; // What appears in the menu link
$link['link_path'] = 'node/' . $node->nid; // Or you can use a path alias as well
$link['plid'] = 12; // Optional - if you want it to nest under an item you'll need its mlid (menu id)
menu_link_save($link);

See: http://api.drupal.org/api/drupal/includes--menu.inc/function/menu_link_save/6

3) How do I create aliases for these nodes such as node/856 goes to programs/some-program-type/some-program-title

SOLUTION
Similar to the menu solution above, you can use

path_set_alias('node/' . $node->nid, 'path/alias/here');

Thanks for any suggestions!

I understand that you have some external database, and your nodes are in relation with some entities from there. You need node 'downloading' some content from other database; for compatibility with Solr.

1) Instead 'hacking' node number, I think you should use create node type for it. Beside distinguishing downloaded nodes for others; you can create CCK field for storing external database id; and setting content edition permission that nobody can edit it.

2) In your custom module you need to implement hook_blocks to put in the menu content that you need.

3) With pathauto module you can simply create automatic path. If you create special content type out of the box pathauto functionality should be enough.


Drupal 7 custom block not showing in block list A Drupal 7 newbie here, with the following problem.

I have enabled my block with it's dependencies, but doesn't show in the block list

Can anyone spot anything I might've missed in my code?

Any help to point me in the right direction will be deeply appreciated!

Thanks in advance!

The code is the following.

.info file

name = Bloque para el buscador - INMO
description = Bloque para mostrar el buscador geográfico de InmoAnuncios.
package = Modulos de Inmo Anuncios
core = 7.x

scripts[] = bloque_buscador.js // exist in folder

dependencies[] = inmo_node_form // enabled

.module file

<?php

/**
 * @file
 * Modulo para el buscador de inmuebles
 *
 * Este modulo provee de un bloque donde se despliega un buscador de inmuebles en el sitio
 */

/**
 * Implementa el hook_block_info()
 * Este hook le dice a DRUPAL que este bloque se puede desplegar tanto en el home page como en el sidebar
 */
function bloque_buscador_block_info() {

    $blocks = array();

    $blocks['bloque_home'] = array(
        'info' => t('Inmo Buscador (home)'),
        'cache' => DRUPAL_NO_CACHE,
    );

    $blocks['bloque_sidebar'] = array(
        'info' => t('Inmo Buscador (sidebar)'),
        'cache' => DRUPAL_NO_CACHE,
    );

    return $blocks;
}

/**
 *
 * @param type $delta
 * @return type
 * Implementa el hook_block_view()
 *
 *
 */
function bloque_buscador_block_view($delta = '') {

    $estados = db_query("SELECT * FROM estados WHERE enabled = 1;");
    $inmuebles = db_query("SELECT * FROM tipo_inmueble WHERE enabled = 1;");

    $optEstados = '';

    foreach ($estados as $estado) {
        $optEstados .= "<option value=\"{$estado->id}\">{$estado->nombre}</option>\n";
    }

    $optInmuebles = '<option value=\"0\">--Todos--</option>';

    foreach ($inmuebles as $inmueble) {
        $optInmuebles.= "<option value=\"{$inmueble->tipo_inmueble}\">{$inmueble->tipo_inmueble}</option>\n";
    }

    $contenido = <<<EOSTR

Encuentra tu inmueble ideal!

          <form action="/filtro" method="GET">

                    Busco inmuebles en:

                        Venta <input type="radio" name="operacion" id="operacion" value="venta"/>
                        Renta <input type="radio" name="operacion" id="operacion" value="renta" />

                    Tipo de inmueble?
                    <select name="inmueble" id="inmueble" style="width:150px;"> $optInmuebles </select>

                    En donde?
                    <select name="estado" id="estado" style="width:150px;"> $optEstados </select>

                    <input type="submit" value="Buscar">

            </form>

EOSTR;

  $bloque = array(
    "subject" => NULL,
    "content" => $contenido
  );
  return $bloque;
}

?>

That is because your module_block_view() function is not written properly. the content is not passed into any of the blocks you defined in your module_block_info()

function bloque_buscador_block_view($delta = '')
{
        $block = array();
        switch ($delta)
       {
        case 'bloque_home':
            $block['subject'] = t('Syndicate');
            $block['content'] = YOUR CONTENT IN HERE,

        );
        break;
        case 'bloque_sidebar':
            $block['subject'] = t('Syndicate');
            $block['content'] = YOUR CONTENT IN HERE,

        );
        break;
      }
    return block;
 }


Adding Link To Drupal 6 Views Slideshow Probably a stupid question. I'm more used to Drupal 7, but I'm working on a new site today and it's Drupal 6. There is a Views Slideshow on the home page. The buttons and images automatically cycle. We want to add a link to each button/image so people can click and go to a related page.

http://simulab.com

I looked at the nodes for the content used for each image and I was surprised that there is no field to store a link--as is common in most slideshows I see now.

The Links module is installed, but again there is no Link field type in the node content used to store each image/button in the view.

Looking at the HTML, I see that there is no href for each button or img. Apparently one can hover over a button to switch visible images, but cannot -click- to go to another URL.

What's the preferred way to add a click URL to each of the images and/or buttons in the view?

TIA

Add a link field using CCK for the content type.
override the label output to include the rendered link in the View.


Change order (weight) of blocks before page load programatically Is there a way to change order of blocks before page load (according to current node id for expample)? In hook_preprocess_page or something like that? I don't want to use any modules for this.

You can use hook_block_list_alter to achieve this. Be aware that the $block->weight attribute won't be affected at this point in the proceedings, but there are solutions in the comments to this problem.


What hook should I use to define a class? If I want to define a class, like the one below, for a custom module, and make it available to all the functions in my module, which hook should I use?

class foo {
  public $bar;
  function display_bar() {
    return $this->bar;
  }
}

You wouldn't use a hook to define a class, that doesn't really make sense.

If you're talking about autoloading, you have two options:

In-built - you can add a file called, for example, foo.class.inc, in your module's root, and add the following to your module's .info file

files[] = foo.class.inc

Once you've cleared the caches, any time you request a new foo(), the appropriate file will automatically be included.

See Writing module .info files for more information.
XAutoload - PSR-0 & PSR-4 style autoloading. If you're into OO this is a much better option in my opinion.


Make a views of data entered in composed fields How to output the data entered in Composed Fields to Views?

I have used Composed fields of 3 subfields, it was OK while entering the data. But When I want to display the entered data in Views, I get only blank fields.

After digging dip into it, I tried rewrite the Result, Only in Write result I get Token like [field_field_name-composed], which outputs the serialized PHP code:

a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}

where First Subfield, Second Subfield, Third Subfield are the data I entered into 3 subfields of Composed field, and is also defined by s: before it. If it is String type and 14 Characters long, then its written as s:14:

I also see the Token like [field_field_name] but it outputs blank (NULL).

So, I planned to use Views PHP to get the data from Composed Field and use some PHP code, but in Views PHP field, I am unable to use the Token [field_field_name-composed].

I want to make a Views with 3 fields to display each Subfield in its own field, is it possible?

EDIT:

I came to know this is using PHP Serialize function, but when I tried PHP Unserialize in Views PHP, I get blank string.

EDIT2:

The result of Unserialized value of above serialized field is:

print_r(unserialize('a:3:{i:1;s:14:"First Subfield";i:2;s:15:"Second Subfield";i:3;s:14:"Third Subfield";}'));
Array
(
    [1] => First Subfield
    [2] => Second Subfield
    [3] => Third Subfield
)

Write a function in your module/theme that will accept two arguments,

1) the serialized value a:3:i:1;s:3:"First Subfield";i:2;s:4:"Second Subfield";i:3;s:7:"Third Subfield";

2) the name of the key you want to use.

Have it return the value.

Create three new columns that use PHP code in your view,  and pass the appropriate arguments to your module/theme.


how to update my custom table after execution of rules i have created a table as follow

<?php

/**
 * @file
 * Implements hook_schema
 */
function core_sms_schema() {
  $schema['core_sms_details'] = array(

    'description' => 'This table is used to keep track of sms sent/failed on specific date.',
    'fields' => array(
      'id' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'date' => array(
        'description' => 'Date',
        'mysql_type' => 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP',
        'not null' => TRUE,
      ),
      'sms_sent' => array(
        'description' => 'The SMS sent on particular date.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => '0',
      ),
      'sms_failed' => array(
        'description' => 'The SMS failed on particular date.',
        'type' => 'int',
        'not null' => TRUE,
        'default' => '0',
      ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

After a sms has been sent i have to update the columns with number and date. i already have rules also but not able to get how to update the custom table using rules.

In rules you have option to add PHP code inside the Action ->PHP-> "Execute custom PHP code " in that have a code to update the custom table.

The following variables are available and may be used by your PHP code:

Variable name Type    Description

$site   Site    Site information

$node   Content updated content

$node_unchanged Content unchanged content

you can use for updating the table if its a node

Note : here node represented as a example


Problems with a global variable I have the following code:

$a='1';

function check() {
  global $a;

  if ($a == '1') {
    return "1";
  }
  else {
    return "2";
  }

  var_dump(check());
}

When I run this code stand alone, its output is string(1) "1"; when I use the code inside page-front.tpl.php the output is string(1) "2.

Why?

When Drupal includes the template file, your declaration of $a = '1' is not in the global scope. You need to declare it as such:

global $a;
$a = '1';

Since you're diving into the realm of global variables though, I'd recommend using a more distinctive name, or figuring out how to avoid globals altogether.