Drush updates core successfully to 7.32 but is still 7.31 I'm developing a site on Drupal 7 and using drush 7.0-dev to keep the core and modules up to date. I've run drush pm-update several times successfully in the past, until Drupal core version 7.32 came out. Everything seems to go fine and drush reports no errors, but the version still stays at 7.31 after the update.

Here's the output of two consecutive runs:

me@mybox:/var/www/customer$ drush pm-update
 Name    Installed Version  Proposed version  Message
 Drupal  7.31               7.32              SECURITY UPDATE available

Update information last refreshed: Thu, 10/23/2014 - 20:21
Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications
to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.32.
Backups were saved into the directory /home/me/drush-backups/customer/20141023172524/drupal.                                                                                [ok]
No database updates required                                                                                [success]
'all' cache was cleared.                                                                                [success]
Finished performing updates.                                                                                [ok]
me@mybox:/var/www/customer$ drush pm-update
 Name    Installed Version  Proposed version  Message
 Drupal  7.31               7.32              SECURITY UPDATE available

Update information last refreshed: Thu, 10/23/2014 - 20:25
Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications
to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n):

Am I doing something wrong? Why is the core not updating? Where should I start troubleshooting? I haven't tried a manual update yet, because I'd really rather get drush working again. The server is running Debian 7 and PHP 5.4.

Try drush up drupal. That may do the trick.


How to re-use text values in a webform? I am using webform and with all the tons of modules available so far there was virtually nothing I had to compromise on.

One thing I am stuck with is re-using user text input. Is this possible without writing a custom webform module on a multi-page form:

user initially enters some text in 4 textfields
populate form checkboxes with those values?

There is the token module installed but I can't figure out a way to populate the checkboxes dynamically (coming from the user and not from a premade select list). The webform_ajax module tells me I can't use it on multi-page forms.

Any suggestions how to achieve something like this where the user enters something and this shows up later in the form?

UPDATE:

I am trying to use hook_webform_select_options_info. How can I target the specific webform, text and select field? Devel does not show any webform ID. The screenshot shows textfield and selectlist information

From the link

function hook_webform_select_options_info() {
  $items = array();
  $items['customusergroups'] = array(
 'title' => t('Your user groups'),
 'options callback' => 'webform_options_days',
 // 'file' => 'includes/webform.options.inc',
 );
 return $items;
}

There is a hook in webform called hook_webform_select_options_info, that allows you to build a dynamic list of $items[] (return $items), which will be used as the list of options for your component.  What you put into this list can obviously be anything - i.e. how you decide what to put in is up to you.

I used it recently to create a multi-route dynamic web form where the path through the webforms is determined by a decision tree.  Ever option on every question is loaded from a JSON file, and depending on the answer, the next question (which could be any one) is shown.


How to add a dynamic select field to a content type form? I would like to add a dynamic select field where options change from time to time. New options will be added along with old options in future. I know i can add form element using hook_form_alter and save values using node api in custom table created using install file of a module.

Is there any inbuilt mechanism where i can create a field and avoid dealing with schema and schema related queries ? My only concern is field should support dynamic options in future... Something like select field values will be pulled using a query.

PS: I hope above questions is not primarily opinion based. I believe many Drupalers might have faced above situation :-) Please do add a comment if form alter approach is the right one !

You can probably do that using the field API and setting an allowed_values_function for the list field.

e.g:

/**
 * Implements hook_form_alter
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id){

  if ($form_id == 'field_ui_field_settings_form') {
    // Make the allowed_values_function editable as a textfield
    // Possible to inspect $form or $form_state to vary by field
    if(isset($form['field']['settings']['allowed_values_function'])) {
      $form['field']['settings']['allowed_values_function'] = array(
        '#type' => 'textfield',
        '#title' => t('Allowed value function'),
        '#description' => t('Returns an array of allowed values'),
        '#default_value' => $form['field']['settings']['allowed_values']['#field']['allowed_values_function']
      );
    }
  }

}

The allowed_values_function then returns an array of values for the field.

e.g:

/**
 * Allowed values callback
 */
function MYMODULE_custom_field_allowed_values($field){

  if(CONDITION){
    return drupal_map_assoc(array('A1','B1','C1'));
  }elseif(OTHER_CONDITION){
    return drupal_map_assoc(array('A2','B2','C2'));
  }

}


Converting and save images as JPG in IMCE module during uploading? How to convert PNG to JPG when user upload images with IMCE ?
This is neccessary for disk space optimization. If it is possible to convert with any module or to execute Image Style tell me please.

It can be done in this way:

download ImageCache Actions module and enable Color Actions    module
create image style "Change file format Convert to: jpg"
download and install IMCE Image Style module
on the IMCE Image Style administration page select necessary style

And we need to add custom submit function

/**
 * Implements hook_form_FORM_ID_alter().
 */
 function mymodule_form_imce_upload_form_alter(&$form, &$form_state, $form_id) {
   array_unshift($form['fset_upload']['upload']['#submit'], "mymodule_upload_form_submit");
 }

/**
 * Change uploaded image extension.
 */
 function mymodule_upload_form_submit($form, &$form_state) {
   if ($_FILES['files']['type']['imce'] == 'image/png' &&    $form_state['values']['imce_image_style']['optimize_image'] != '0') {
      $_FILES['files']['name']['imce'] = str_replace('.png', '.jpg', $_FILES['files']['name']['imce']);
   }
 }


How to use the LOWER function in a Drupal query? I want the query like below:

select * from tbl where LOWER(name) = $name

My current query is:

$resultArr = db_select('adbanner', 'n')
    ->fields('n')
    ->condition(LOWER('n.blog_title'), $page, '=')
    ->execute()
    ->fetchAll();

But it doesn't work.

How should I write this type of query?

You can use LIKE instated of LOWER.

OR write something

$query->where('LOWER(n.blog_title) = :page', array(':page' => $page));

Refer Using SQL functions in conditionals in Drupal 7 db_select()


Display 2 contents types fields in 1 view I am trying out Drupal 7 - and am a complete noob, so please bear with me!

I have a content type - 'film' which displays various fields about a film and another called 'venue' which displays data about a screening of a film.

I wanted to merge the display of content types film and venue so that they display in the same screen (all the fields in one screen). Is this possible? Do I do it with views? I have heard of relations, but I'm finding it all confusing.

Thanks.

If there is a 'venue' content type linked through a node reference field, you can do it using a relation in a view.


How to avoid round problem in tax? I have to deal with order with high quantities by product.

Tax (VAT) is calculated by rule for unit price, rounded, then multiplied by quantity. With high quantity this kind of rounding cause problem.

How to deal with that?

You can specify the round mode you want in the tax type configuration page.

/admin/commerce/config/taxes/types/vat/edit

(It should be configure to no round by default)


How to upload video to Drupal using Video module? I've successfully installed the Video module and now there is no errors.

It's not clear to on Drupal website how I can start uploading videos though.

Can anyone please shed some light on this?

To start uploading a video you have to create a new content type, and add a new field and use a field type of video. You can also choose a widget type of video upload.

Upon adding the field, on the next step you can add the extensions of the kind of video files you will like to upload


What is it called when a Drupal Module installs with several modules? I looked up submodule, but that seems to be a Git thing. So, when a Drupal module installs with a whole group of things that show up in the dashboard, what is each piece called? For example, there are about 8 items that show up in Modules -> Chaos Tool Suite. If they show up in one group, does that mean they are all written by the same entity?

what is each piece called?

I don't have an official reference, but "submodules" or "sub-modules" is by far the most common phrase I've seen used for modules included in a main module to complement/extend its functionality. Prominent members of the Drupal community seem comfortable with referring to them as such.

  If they show up in one group, does that mean they are all written by the same entity?

It can in some cases, but there's nothing to guarantee it. Any module can list itself under any of those groups by setting the package key in its .info file. A lot of modules that provide field types list themselves under the generic "Fields" group, for example.


How to put pager between multiple views? I am finding the way to combine more than one views through pager, I would like to connect them using the pager. And I would like to provide the pager like what is on drupal site(documentation part) as shown in following image. So they show previous and next node. I am searching but did not find the way to combine multiple views. The views default pager is for its own content and can not apply to the direct to other views. Thanks

IMHO, you might have to rethink your content architecture. The type of pager your are looking for ideally applies to content and not views.
drupal.org uses the book navigation that comes from the book module in Drupal 7 core.

If you do not want to use the book module, you could also go with the Nodequeue module, which provides a similar pager (except the middle link Up).

If you still really need to add such pager to connect the views, you can do it by adding the markup to the view footer to link to other views (and theme it as per the design). Or to make it dynamic, implement hook_views_pre_view (or any similar hook) and change the link from from the footer. Note: This however, is very hard to maintain and not recommended.


Infinit loop when I submit a form and redirect to this form with an additionnal parameter I created a form. When the form is submitted, I want redirect to the form page and pass an additional parameter.

I do this :

public function buildForm(array $form, FormStateInterface $form_state, $results = null)
{
  if ($results) {
    customlog($results, "RESULTS !!!"); // write in a log file
  }
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Submit'),
  ];
  return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state){}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $results = array();
  // do some work ...
  // ...
  // $results is a simple associative array
  customlog("I pass here !", __FUNCTION__); // write in a log file
  return \Drupal::formBuilder()->getForm('Drupal\mycustommodule\Form\MyCustomForm', $results);
}

My issue is when I submit this form, the page indefinitely load. When I check my log file, I realize that the "I pass here !" log is repeated indefinitely.

Where is my mistake ? When the form is submitted, how can I redirect to the same form with an additional parameter without this infinit loop ?

Thank you :)

If you want to redirect to the form page you need to do something like this in your submit handler:

$form_state->setRedirect('NAME_OF_THE_ROUTE_OF_YOUR_FORM', $route_paramters, $options);

Maybe you can insert your results by query parameters?! Or save them in a session so that they can be used again. But the $form_state->setRebuild seems to be smarter to me.


Are 'active' and 'staging' required in config_directories? Is it OK to delete the 'active' and 'staging' entries automatically created in settings.php? I don't plan on using them, but it's not clear to me whether some process might expect them to exist.

The default.settings.php file contains the following comment:

  The staging directory is used for configuration imports; the active directory is not used by default, since the default storage for active configuration is the database rather than the file system (this can be changed; see "Active configuration settings" below).

In short:

The staging directory is used only when importing configuration from the UI
The active directory is not used by default from Drupal 8, which saves the configuration data in the database, like Drupal 7 did with the persistent variables

In both the cases, I would expect Drupal to correctly handle the case the global $config_directories is not set.


Views filter referenced content when end date is over This view is the result of a given postcode. how could I hide/filter referenced content when its end date is over? The referenced content should disappear but the non referenced content should still be displayed.

I'm not so sure this is possible through the views interface. But, you can easily do this through your theme layer.

In your view admin area, under advanced there's the page: Theming information. Clicking on that will give you a list of available tpl.php names that can be used to create your own tpl.php files that can be added to your theme. Your probably gonna wanna use a row style output. The list of those files go from general to specific, so the last time will only be applied to your view. Clicking on the link of row style will give you the content of the default file.

All you would need to do is just print the fields as normal, with the exception of the fields you want to exclude. Just use a standard if to check to make sure they're still valid, if not, don't print them.


voting in all fields before submit results I have a content type (computer) with multiple rate fields (performance, battery range, price, ...) type fivestars. By default, the module sends the results by ajax whenever you click on a star; what I need is that you vote in all fields, before the results are sent (with a button).

Is it possible to do this? And how?

The only way I can think of to do this is to override the javascript function Drupal.rateVote which is declared in the file rate.js. It would require considerable work to achieve what you want.

You can have a look at this question where someone else had to override a javascript function from a contrib module.


Same taxonomy in two content type I have two content types Blog and Stay which use the same taxonomy Location. I have two or more posts use same term Cyclades.

Is it possible when a user clicks on a Cyclades term link in a Blog post to only show posts from Blog content on the taxonomy page? Likewise, when a user clicks on Cyclades in a Stay post, to show only Stay content on the page?

I know i can create two different taxonomy for each content type, but I dont want this solution.

You can have same taxonomy being used by multiple content types.

You can achieve this by using 2 options
1. Overriding node.tpl.php for the taxonomy page. Here you can create two separate tpl files specific two different content types.
2. Create PAGE display of VIEWs and pass "type" as an argument. Based on this argument you can always display the teasers belonging only to the desited "Content Type."

Option # 2 is little easier from implementation point of view whereing Option # 1 though could little time consuming but will be better from performance perspective.


Google+ button for sharing an article (just like TweetMeme) available? I need a button to share the current node to Google+?
Is there a module to implement it?

I already have a standalone one (TweetMeme for twitter and another one for facebook )

For modules that implement the Google+

Google Plus One
Social media
Easy Social


Unsupported operand types in system.module line 2134 when trying to add product with drupal commerce I'm trying to add a product to my commerce store, and anytime I navigate to the add a product page I get hit with the following error:

Fatal error: Unsupported operand types in C:\Users\Nick\Sites\devdesktop\psr3\modules\system\system.module on line 2134

I have googles around, and this looks like a common error with contrib or custom modules.

The error happens in this if statement:

  if (!isset($item['mlid'])) {
    $item += db_query("SELECT mlid, menu_name FROM {menu_links} ml WHERE ml.router_path = :path AND module = 'system'", array(':path' => $item['path']))->fetchAssoc();
  }

My php isn't good enough to know what might be causing the error. How can I solve this?

Either $item, or the return value from the db_query() statement, are resolving as something other than an array. Drupal is expecting them both to be arrays, so you get an error when it unconditionally tries to combine them.

It's not possible to debug something like this without access to the site; I'd recommend stepping through the code with a proper debugging tool to see exactly which side of the equation is failing.

At a guess, I'd say $item is the problem. You'd expect to see more notices about undefined array indexes if it was simply that $item['path'] was missing or something like that.

One low-tech debugging approach is to temporarily disable custom/contrib modules one by one and see if you can find something responsible.


Duplicate paragraphs from node type FOO to node type BAR I have two content types: FOO and BAR. These content types have a field called "field_paragraphs" of type "paragraph". And other fields of course.

Now in a situation my user can click a button (that call one of my function defined via hook_menu) and "copy" content of type FOO to a new content of type BAR, so I need to copy, NOT CLONE, field_paragraphs from FOO to BAR: I need to create a standalone copy of "field_paragraphs"; like two different insert.

I have searched on google but all talk about "clone", but in my case I need to copy so I can not use "clone" module.

How can I do this ?

M.

EDIT: You can now find a better explanation with the code here.
I know this is old but maybe someone comes here looking for an answer like me, this is tested on Drupal 8.
I found this issue and after looking at last patch, I implemented :
$nodeDuplicate = $node->createDuplicate();

foreach($nodeDuplicate->field_paragraphs as $field){
    $field->entity = $field->entity->createDuplicate();
}

$nodeDuplicate->save();

And I got a duplicate node with duplicated paragraphs fields. If you look at the patch you will see how to add a button to Drupal etc.
Just a note field_paragraphs is the name of my field in the content type, change it with your own.
I didn't have any problem doing it this way, maybe someone has a better way but I did not find it, also at the time of writing this there is still no ported modules for cloning nodes in Drupal 8.


Send 'compare product' action to Google Analytics I am having a products page in my site. In that I have a comparison functionality.

Now I want to send data to google analytics so that Admin can later on check which products were compared. I have captured the products I.E. on which products checkbox the user clicked and store that array of products in a jquery variable.

Now I want to send this variable in ga function but I am not able to do soo. Can anybody help me out with it or some other solution?

You can use GA Push module

  GA Push offers an API to enqueue informations that are sent GA
  servers, and three submodules to track browser events (using jQuery),
  form validation errors and log exceptions.

So, you can use the API to send an event to Google Analytics when user adds a producto to the comparison.

For example, you can use the page view function and send virtual page views for each compared product:

$push = array(
  'location' => '/comparision/product/' . $nid,
  'page' => 'comparison',
  'title' => 'Product ' . $product_name . ' comparison',
);

ga_push_add_pageview($push);

This code should called when you detect that a product is being compared.

Disclaimer: I'm one of the developers of this module.


When using hook_form_alter() and additional submit functions, can one reference a php file for the submit callback? The following code works.

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

  switch ($form_id) {
    case "webform_client_form_13":
      $form['#submit'][] = 'bleh_community_submit';
      break;
  }
}

function bleh_community_submit($form, &$form_state) {
  // Do some stuff here.
}

However, is it possible to use code similar to the following one, where the form submit function calls a PHP script (e.g. bleh_community_submit.php) containing the form submission handler?

function bleh_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case "webform_client_form_13":
      $form['#submit'][] = 'bleh_community_submit.php';
      break;
  }
}

// Separate .php file in the module directory with the
   additional bleh_community_submit function

function bleh_community_submit($form, &$form_state) {
  // Do some stuff here.
}

Why not do something like

require_once('bleh_community_submit.php');

then call the callback function as per normal?


Host two ready websites with different URL using same code base I’m pretty newbie to drupal and deploying stuffs. I’ve two separate drupal websites ready.

www.example.com
www.example.org

My directory structures on local machine for both websites are

wamp/www/example.com/sites/’all & default ‘ folder
wamp/www/example.org/sites/’all & default ‘ folder

These websites have complete different theme and database from each other. Now I want to go live for these two websites. But the problem is on hosting server they will provide me only 1 drupal installation. I need both URL’s working. (There is a setting for URL redirection on hosting).  But on hosting server, redirection via .htaccess is not running. (They said !!!). So my question is how to host two complete different websites on server with two complete different URLs using same drupal code base? I’m using drupal 7. Any help or suggestion will be appreciated.

Thanks in advance…

It looks like you are looking for Multisite approach. It's pretty easy to set up and to keep sites separate, but if one day you'll need to share anything between sites, you'll regret not using Domain Access.

If you are sure there will be no need to share data, in <drupal root>/sites create 2 subdirectories, like example.org and example.com, and put site-specific files (modules, themes, libraries and settings.php) into them. Point both domains to your Drupal (your provider should be able to help with that) and Drupal will take care to recognize what site is accessed.

It might be worth to consider Domain Access module.

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.


Avoid the preprocess/hook function defined from the Zen theme is called for its sub-theme We are using a theme that inherits from the Zen theme. the Zen theme implements zen_process_html_tag() and zen_html_head_alter(), and we want these functions not to be called; we tried to override these functions in our theme, but then Drupal call zen's functions first, then the functions in our theme.

How can I avoid this happens?

Those are part of HTML5 support bundled with Zen 7.x-5.x. Your options are either downgrading to Zen 7.x-3.x or patching Zen. Please open an issue at Zen's issue queue asking to provide an option to turn on or off the header manipulation.


X-Drupal-Cache http header Examining for http headers, I mentioned the header "X-Drupal-Cache HIT".
I use varnish reverse proxy.

Is it necessary for this header to appear? Can I make it be ommited? If yes, how? Would that have negative implications?

To change drupal http-header information check out drupal_set_header() (D6) or
drupal_add_http_header() (D7).

Looking at the documentation for _drupal_bootstrap_page_cache, it seems the header shows 'HIT' if the page is displayed from cache, and 'MISS' in the case it is not.

Check out Set X-Drupal-Cache header during page_cache_fastpath and Implement better cache headers for reverse proxies for more information about the X-Drupal-Cache header. It seems to be a Drupal 7 or Pressflow only thing.


How to check another user is logged in? There is a lot of questions how to check the current user is logged in, but I need to check another users (by uid for example).
Is there any easy way to do it?

There aren't any functions in Drupal that I am aware of. You'll need to query the database.

$time_active = db_query("SELECT timestamp FROM {sessions} WHERE uid = :uid ORDER BY timestamp DESC LIMIT 1", array(":uid" => $uid))->fetchField();

That will fetch the last time that the user was active if they have a current session open.


Converting a helper class into an Entity I am working on a Drupal 8 module, and a separate module of examples, on how to use the first module. In my example module, I have a function in my controller that looks like this:

public function basicUsage() {
  // Basic line chart.
  $series[] = [
    'data' => [[0, 3], [4, 8], [8, 5], [9, 13]],
  ];
  $params = [
    "data" => $series,
    "theme" => "flot_examples_basic_usage",
  ];
  $flot = new FlotD8($params);
  $output[] = $flot->outputPlot();
  return $output;
}

I would like to use the standard entity notation if possible to simplify things, and make it look like this:

public function basicUsage() {
  // Basic line chart.
  $series[] = [
    'data' => [[0, 3], [4, 8], [8, 5], [9, 13]],
  ];
  $output["flot_d8"] = [  //maybe name needs to be FlotD8?
    "#data" => $series,
    "#theme" => "flot_examples_basic_usage",
  ];

  return $output;
}

Here is the code for my class. What do I need to do or change to give it the behavior I'm looking for? Is it just a matter of extending a certain Core Entity class? I do not need any schema or database functionality.

<?php
namespace Drupal\flot_d8\Entity;
class FlotD8 {
  protected $id;
  protected $theme;
  protected $data;
  protected $options;

  function __construct($params){
    $this->id = isset($params['id']) ? $params['id'] : 'placeholder';
    $this->theme = isset($params['theme']) ? $params['theme'] : 'flot_d8_my_template';
    $this->data = $params['data'];
    $this->options = isset($params['options']) ? $params['options'] : NULL;
  }

  /*
   * Create the theme output.
   */
  function outputPlot (){
    $drupalsettings['flot_d8'][$this->id] = ['data' => $this->data, 'options' => $this->options];
    $output = [
      '#attached' => [
        'drupalSettings' => $drupalsettings,
      ],
      '#theme' => $this->theme,
      '#options' => $this->options,
      '#data' => $this->data,
    ];
    return $output;
  }
}

Why exactly do you want to use an entity?

Entities are about CRUD. Saving, loading and deleting data in the database or somewhere else.

From looking at your code, that doesn't really seem to be what you're after, you just have an API to display some data. That's not what entities are about at all.

You could make a service of your class but that doesn't really seem to match either.

I guess the only thing that would make sense is to define it as a render element. See RenderElement and Render API overview.

So you'd define your class with @RenderElement in an Element namespace, see Link for an example. You give it a name in the annotation, like yourmodule_plot and in your render array, reference it as #type => 'yourmodule_plot' and pass the data to it like that.

A render element class basically consists of a getInfo() method that defines some default properties. In your case, that would be #theme, #attached and so on. if you need to dynamically process your data, you can add a #pre_render callback like shown in the Link example that can then process the merged array of your defaults + data you specify in the controller.


HTML corrector doesn't close quotation marks in teaser In Drupal6, I have a WYSIWYG input filter with the HTML Corrector filter enabled. When the body is automatically truncated for use in the teaser, sometimes the break occurs in the middle of an attribute value in an HTML tag (e.g. in the middle of the url in an anchor's href), resulting in an unclosed quotation mark. The HTML corrector appears to balance the unclosed tags appropriate, but it doesn't close the quotation mark.

For example, if my content body is the following one:

google.com

The teaser breaks in the middle of the URL:

<a href="http://goog

Then the tags are closed but no closing quote or the end of the opening tag:

<a href="http://goog

The result is a broken theme. Am I doing anything wrong? Is there anything that is mis-configured?

Doesn't look like it's a problem on your side. You can try the following:

drush php-eval '$text = "
<a href=\"http://goo"; print $text . "\n"; print _filter_htmlcorrector($text) . "\n";'

And for me the results are:

<a href="http://goo

<a href="http://goo

(The second line is the output of _filter_htmlcorrector().)

It would be worth seeing if there's an issue for this already, and if not creating one. I find the built-in HTML corrector too limiting anyway (it always strips styles for example IIRC), and use htmLawed. With that you get:

drush php-eval '$text = "
<a href=\"http://goo"; print $text . "\n"; print htmLawed_filter('process', 0, -1, $text) . "\n";'

Results:

<a href="http://goo

(Again, second line is the cleaned output - it's simply stripped the incomplete tag.)


How to Add Previous/Next Navigation on Teaser based on Views? I have created a teaser based on views but don't know how to add a previous/next navigation. I have tried Views Navigation but it is for node only. The one that I am looking for is similar to the previous/next navigation with numbers in the front page.

Any help is greatly appreciated.

I think you're looking for a Pager, there are standard paging options in Views or you might need something more complicated like Pagerer or perhaps Views Simple Pager


User Profile Image not showing correctly I want to show the profile and few content fields for a user profile. For this, I have used views module. Now the problem is that when I select imagecache preset to profile image(which I have defined as 150x200), the output is pathetic. It shows the profile images of around 63x63 size. I thought that the imagecache module might not be working. So I uninstalled and reinstalled the image and imagecache modules, but all in vain. Then I thought of checking into the imagecache folder whether the images are being resized, and to my amazement , the images inside sites/default/files/imagecache/profile_image/pictures/ folder were all of the dimension defined by me for profile image i.e 150x200 . So the problem seems to be only while these images are shown on the frontend.

Any idea about this?

Go to this link
 your_url/admin/config/people/accounts

here you will see
 field
 "Picture upload dimensions"
  do not write any dimension in this field , save it and then add profile picture for user

this works in Drupal 7


Why my first tab is missing for local menu tasks defined by hook_menu()? I am learning how to use hook_menu(). I am at a point where I have a question and not figure it out. I have a local task button inline with View and Edit and I want 4 sub-local_task buttons. See chart below.

View | Edit | **Outcomes** |

*Outcomes Viewer* | Add New User | Add Bulk Ghost | Registration Report

However, the first button(Outcomes Viewer) is missing and I cannot figure out how to get it to show up. Below is the menu code within the function. The Outcomes Viewer is a view. I am mixing this with some custom code and views as well.
(*Drupal 7, Views 3)

$items['node/%node/ecg-outcomes'] = array(
    'title' => 'Outcomes',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 50,
  );
  $items['node/%node/ecg-outcomes/'] = array(
    'title' => 'Outcomes Viewer',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => -10,
  );
  $items['node/%node/ecg-outcomes/add-bulk-ghost'] = array(
    'title' => 'Add Bulk Ghost',
    'page callback' => 'entity_ghost_participant_report',
    'page arguments' => array(1),
    'access callback' => 'entity_ghost_participant_access_report_tab',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'file' => 'entity_ghost_participant.reports.inc',
    'weight' => 11,
  );
  $items['node/%node/ecg-outcomes/add-new-user'] = array(
    'title' => 'Add New User',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 14,
  );

You need 3 menu items and 2 view pages. The parent menu and the default menu will share some configuration.

  $items['node/%node/ecg-outcomes/add-new-user'] = array(
    'title' => 'Add New User',
    'page callback' => 'SOME CALLBACK',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
  );
  $items['node/%node/ecg-outcomes/add-bulk-ghost'] = array(
    'title' => 'Add bulk',
    'page callback' => 'SOME CALLBACK',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK ,
    'weight' => -8,
  );
  $items['node/%node/ecg-outcomes/registration-report'] = array(
    'title' => 'Registration Report',
    'page callback' => 'SOME CALLBACK',
    'access arguments' => array(1),
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK ,
    'weight' => -7,
  );

  return $items;

As the outcome-viewer is set up as a view and you want it as the default menu tab, you need to set up two almost identical pages in your view as follows:

View Page 1:

Path: node/%/ecg-outcomes
Menu: Type : Menu tab, Title : Outcomes, weight : 50

View Page 2:

Path: node/%/ecg-outcomes/outcomes-viewer
Menu: Type : Default menu tab, Title : Outcomes Viewer, weight : -10

METHOD 2
I think it can also be done with 4 menu items and 1 view page, in which case you only define view page 1, and include this menu item:

$items['node/%node/ecg-outcomes/outcomes-viewer'] = array(
    'title' => 'Add New User', // NO page callback and access callback necessary
    'type' => MENU_LOCAL_TASK,
    'weight' => -9,
);


my base_path is empty do I need to set this manually or is something else wrong? I've tried putting in these values in my return:

base_path();

global $base_path;
$base_path;

$GLOBALS['base_path'];

They all end up returning nothing, while an appended string shows up just fine:

return '<div>' . base_path() . drupal_get_path('module','bannert') . "banner.html" . '</div>';

You haven't printed/returned any of your examples. It should be

print base_path();

global $base_path;
print $base_path;

print $GLOBALS['base_path'];

or

return base_path();

global $base_path;
return $base_path;

return $GLOBALS['base_path'];

Depending on the context.

A line with just a variable on it is valid PHP, but it won't do anything with the variable unless you tell it to.

EDIT

It's also worth considering what exactly you're expecting base_path() or $base_path to contain. The docs say this:

  Returns the base URL path (i.e., directory) of the Drupal installation.

  base_path() adds a "/" to the beginning and end of the returned path if the path is not empty. At the very least, this will return "/".

Unless you have your Drupal installation in a sub-folder of the web root (e.g. http://localhost/drupal/), this function/variable will always give you the value '/'.


How can the divs added by default by Views be removed? In Views module, if I don't use any classes, even not the default, it still insists of wrapping the field contents into divs. I have had to use views-view-fields--VIEW-ID.tpl.php to theme the content, when it would had been very easy to tell Drupal not to warp with divs. Surely I am doing something wrong in the UI of Views, but I cannot identify what: in each field, the Style Settings has every checkbox unchecked, even the "Add default classes" checkbox.

On the contrary, you NEED to select the boxes for field, label and wrapper, and select None in the drop down menu. This will get rid of the <div>.

The Add default classes has nothing to do with the HTML elements - only with the css classes it adds to the tag.

Additionally you can deselect Provide default field wrappers under Format > Settings

EDIT: So, testing confirms that there are NO divs for fields anymore if you uncheck Provide default field wrappers. See image. Why modify a tpl file if you can do this with the interface? The only divs you see in the image are the ones that separate rows in the Unformatted list output. "See, mom, no divs!"


Reading a file uploade in my module without saving it I'm creating an module and there I want to read a text file.

I don't want to save the file.

In my my_module.module file I have

function my_module_upload_form($form, &$form_state) {
    $form['upload'] = array(
        '#type' => 'file',
    );

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

    return $form;
}
function my_module_upload_form_submit($form, &$form_state) {
    $file = file_load($form_state['values']['upload']);
    $url = file_create_url($file->uri);
}

I get the error "Trying to get property of non-object" at

$url = file_create_url($file->uri);

Can someone point me how to read the file correctly (without saving it)?

Ok I figured it out myself!

function my_module_upload_form_submit($form, &$form_state) {
    //saved the file into a tmp folder (location to save not set)
    //this will also add a pointer in the database
    $file = file_save_upload('upload', array(
        'file_validate_extensions' => array('txt'),
    ));

    //get the content in the file
    $content = file_get_contents($file->uri);

    //remove the file in temp and the pointer in the database
    file_delete($file);
}


Services REST API and special characters I'm using REST Services to communicate between two websites.

Once a node is updated on the website 1, part of the information is sent to the website 2. This works without any problems.

However, all special characters, e.g. apostrophes, are received escaped.

For example: "It's a sample page", will be received as "It\'s a sample page".

Here is the code I'm using:

// $data is just an example. It's more complex and the only relevant part is the
// way node title is passed.
$data = array('title' => $node->title);

$curl = curl_init('http://example.com/rest/node/1');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

How can I avoid this? Is there any encoding/decoding I need to do prior to building HTTP query?

Thanks!

It looks as though your PHP install might be configured with the deprecated Magic Quotes

  When on, all ' (single-quote), " (double quote), \ (backslash) and
  NULL characters are escaped with a backslash automatically.

More info: Disabling Magic Quotes


How do I get the fivestar module's vote on a review node to count towards a product node? Should be simple.
I have a content type called Product.
I have another content type called Review.

I want people to vote when they create the Review content type and have the vote count towards the Product.
When I display the Product, I want the average of the votes to appear with the product.
Problem: When I add the fivestar field to the Review content type I DO NOT see an option to set a target node.

Note: I am not using comments as reviews, I am using another content type.

I have tried to find a solution in other postings and I have no problem with a programmatic solution but I have not found anything clear.

The problem was that I had just switched the links between my Reviews -> Products to use entity relationships (instead of node links) and Fivestar does not support that.

A patch that seems to work was posted two days ago.  As soon as I applied the patch, the "target node" field appeared.  http://drupal.org/node/1488914

In addition, the product's Fivestar field had to be set to "rate while viewing" and the Review's Fivestar field had to be set to edit while eediting.


Programatically render block with contextual links (in php) I'm trying to find a solution to embed a drupal custom block using PHP. I found this snippet that works :

<?php
$block = \Drupal\block\Entity\Block::load('your_block_id');
$render = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
print render($render);
?>

The problem is that this code directly render the block content, I don't have any contextual links for that block. My question is, how to render the whole block (including contextual links), exactly like if I added it in a region using the UI.

Thank you

You can use the Twig Tweak module to insert the 'local tasks' menu in your template file:

{{ drupal_entity('block', 'THEME_local_tasks', check_access=true) }}


Change the the title on the `?q=user` page I want to change the the title on the ?q=user page to something generic e.g. "My Home", and not user name.

So far, I have tried using the string override module with little success. Is it possible to do this with a custom module that I can just drop into the page with some PHP code? If not, how can it be done?

There are a number of ways you can do this:

Create a template file for user pages in your theme that renders the title differently
Create a custom module that alters the title using hook_menu_alter
Use Page Manager (part of ctools) and Panels to customise the layout of the user page
Likely other ways I don't know about

Number 1 is probably the most common, 2 is only really okay if you're already writing a custom module that changes user page behaviour, 3 is a more advanced method that basically lets you pull apart the page and put it back together how you want.

The simplest version of #3 would be to create a new variant of the user/%uid path with exactly the same content, and just set the title in the page manager UI using tokens.

Searching for keywords from the various options should provide you with plenty of tutorial material.


How to render HTML output in hook_ENTITY_TYPE_presave() Upon node save, I want to take the value of a text field that uses a custom input filter and save the HTML-ified final version (what the input filter renders) in a second field.

I have two text fields:

Field text_main (which is never actually displayed, avoiding the performance penalty of rendering the field)
Field text_main_display (which is displayed publicly)

The field text_main uses a custom input filter that is very slow to run.  So, I want to get the rendered output of the field after running the input filter and save it to the field text_main_display.

/**
 * Implements hook_ENTITY_TYPE_presave()
 */
function MYMODULE_node_presave(NodeInterface $entity) {
  switch ($entity->getType()) {
    case 'custom_page':
      $processedResult = $entity->get('field_text_main')->view('custom_display');
      // $processedResult is now a render array. How do I render this to HTML?
      $entity->set('field_text_main_display', $processedResult);
      break;
  }
}

Reference: This post on how to render Drupal 8 fields

In hooks which are not executed in a render context use renderPlain(), see Cron error: LogicException : Render context is empty

$html = \Drupal::service('renderer')->renderPlain($processedResult);

Caveat: Text filters can bubble up metadata which you ignore by storing only the HTML. For a custom text filter this might be OK when you know it doesn't depend on cache metadata and attachments, but don't use this as a general approach. This can have security implications, like revealing data to non-authorized users.


hook_editor_js_settings_alter() I am using hook_editor_js_settings_alter() to disallow HTML tags in Ckeditor. It is only working in node edit form, and Ckeditor is in edit mode. Wen I preview the published page it allows the tags in my disallow custom hook.

The following code was a test to disallow <h1> tags with the class name myHeader2. If I change the class name to myheader, it work in edit mode and published mode. Is the class name the problem?

use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;

function mymodule_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats']['rich_text']['editorSettings']['disallowedContent'] = 'h1(myHeader2)';
  }
}

Navigate to /admin/config/content/formats. For each text format, you can enable the Limit allowed HTML tags and correct faulty HTML filter, which is configurable with the Allowed HTML tags text box at the bottom of the configuration form.

This is how input formats are supposed to be changed.


Migrate module showing 0 processed on production server We intend to run regular migrates to update content and the initial migrate was on my local machine.  Now that its up on production I changed the connection strings to the database and its showing 0 processed.  This is the same database structure except one is local and the other is on production.

How can I get migrate module to recognize the production database with these nodes already processed?  I would just reimport them but the problem is that there are other nodes that reference these already and it will mess up a lot of structure.

I guess I didn't take as much time to look into this and then had a light bulb moment.  Migrate actually creates a table in the database of the one it is importing from (probably skimmed over this in the docs).  So I need to do a sync of those tables from my local to production.


I18N site: welcome page with links to translated pages, or translatable content type? I need to create a small web site with a single page that has to be translated into multiple languages. My site is I18N, and Locale + Locale updates enabled.

The page manager allows one to create a landing page and set it as the default page. However, I am not really clear how I could automate the translation of that page. I am considering creating a neutral page with links to translated pages. Something tells me this is not the right way to do it in Drupal.

On the other side, I know I could create a "Welcome" content type, with translation attributes/fields. But then, how do I make sure it would be displayed as the landing page with the correct language? Should I create a landing page with one instance of this content type and translate it?

I am still new to i18n in Drupal.

Not sure what you mean by "automate" the translation page but I think you're on the right track for what I think you're trying to accomplish.

First make sure you have at least the Multilingual content module enabled.
You likely want to also go to admin/config/regional/i18n/strings
        and make sure that Filtered HTML is translatable
Then go to admin/structure/types/manage/page and then Publishing options and choose Enabled, with translation under the Multilingual support option.

You should now have a basic page that is translatable. There will be a Translate option next to the Edit option on the node that should allow you to do the translation. Enabling the Language switcher as well as translating menus and paths is also recommended.


What's a good balance between reusing fields versus creating new ones in the context of fields scalability? I've read the following phrase on a website:

  Instead of adding new fields to a content type, adding existing fields is a better option to reduce the system’s complexity and to improve scalability.

And some doubts arise.

In the system we are developing, we have the possibility to reuse a field across 3 or 4 content types but instead of improving scalability as the quoted phrase says, I'm afraid it will diminish it, because the field's table would faster become a bottleneck (at least that's my reasoning in this case, as all values of that field together, would be a couple millions per year and that would make the table too big). Do you agree?

How many rows would be a sensible maximum to aim for when architecting? That way we could decide when to reuse fields and when to create new ones (even though the chance to reuse is there).

The amount of data in a field usually isn't a problem. If you're worried about that, look into alternative field storage plugins or write your own. For example MongoDB, which can deal with pretty much anything you put into it. It is for example used on http://examiner.com.

A real problem however is the number of fields you have. Because currently in Drupal 7, the complete field configuration of all fields, no matter if they're loaded or not, is fetched from the cache on every single request.

I've seen sites with 250+ fields, where loading and unserializing the field configuration takes 13MB+ memory.

Edit: The field info cache has been improved (see http://drupal.org/node/1040790 for details) with Drupal 7.22, only the fields of bundles that are displayed on a certain page are loaded from the cache and they're separate cache entries. That only works if there are no wrong API calls that request instances across multiple bundles.


Overriding migration source URL with hook_migration_plugins_alter In D8, using Migrate Plus (8.x-4.0-beta3), i am pulling in xml records from an external, non-Drupal API. I have an unwieldy source URL that needs to be passed dynamically to the migrate_plus migration YML file. That doesn't seem possible, but I have read in comments that you can alter the source URL of a migration  with hook_migrations_plugins_alter. However when i do something like below, the URL does not change.

function my_module_migration_plugins_alter(array &$migrations){

  foreach ($migrations as $id => $migration) {
    if ($migration['id'] == 'my_migrate_id'){
      unset($migrations['source']['urls']);
      $migration['source']['urls'] = 'http://example_api';
    }
  }
}

I realize I may need to override the source plugin; if this is true what method do i use to alter the source url?

If you don't want the overridden config to be saved to the database you can override it on the fly with ConfigFactoryOverrideInterface. I'm storing the file path in State API storage via a custom file upload form.

my_module.services.yml

services:
  my_module.overrider:
    class: \Drupal\my_module\MyModuleOverrides
    tags:
      - {name: config.factory.override, priority: 5}

src/MyModuleOverrides.php

<?php

namespace Drupal\my_module;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryOverrideInterface;
use Drupal\Core\Config\StorageInterface;

/**
 * Overrides migration configuration.
 */
class MyModuleOverrides implements ConfigFactoryOverrideInterface {

  /**
   * {@inheritdoc}
   */
  public function loadOverrides($names) {
    $overrides = array();
    $state = \Drupal::state();
    $overrides['migrate_plus.migration.my_migration']['source']['path'] = $state->get('my_module.my_migration_source_uri');
    return $overrides;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheSuffix() {
    return 'MyModuleOverrider';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($name) {
    return new CacheableMetadata();
  }

  /**
   * {@inheritdoc}
   */
  public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
    return NULL;
  }

}


How to create a page on which users can upload files? Maybe it's a question of logic. I'm new to Drupal.

Drupal 7: I want to have a page 'upload' which should be displayed in the main menu, on that page users should be able to upload files (pdf etc), which afterwards will be listed on a second page 'downloads'.

I created a content type 'uploads' with all the fields I need (title, description, file, tags). How do I get that content type inside a static page? Until now I can only access that uploading process when I hit 'add new content' on the home page.

To create page 'downloads' you can use Views module and create page that contain listing of nodes of your content type.

To create 'Upload page' you can just add link to node/add/YOUR-CONTENT-TYPE to main menu.


Getting a blank screen after copying project in my server I am fairly new to Drupal.

I just got an already existing Drupal project and want to install it.

I copied it to: /var/www/html/myprojects/mydrupalproject

Then I got this error in my error.log from apache2:

  [Thu May 03 17:55:41.603774 2018] [php7:notice] [pid 11604] [client
  127.0.0.1:41930] PHP Notice:  Constant DATE_RFC7231 already defined in /var/www/html/myprojects/mydrupalproject/includes/bootstrap.inc on
  line 258, referer: http://127.0.0.1/myprojects/

  [Thu May 03 17:55:41.604601 2018] [php7:error] [pid 11604] [client
  127.0.0.1:41930] PHP Fatal error:  require_once(): Failed opening required
  '/var/www/html/myprojects/mydrupalproject/profiles/clusters_public/modules/contrib/apc/drupal_apc_cache.inc'
  (include_path='.:/usr/share/php') in
  /var/www/html/myprojects/mydrupalproject/includes/bootstrap.inc on
  line 2632, referer: http://127.0.0.1/myprojects/

So I tried to use the original .htaccess info in case it was the problem but I still get exactly the same error in the log. Any help?

Few things to check
1- Check what PHP version on your server, you will need PHP 5 not PHP 7.

2- Make sure you update the $base_url in you settings.php file, assuming you copied that from your local


How do we configure SElinux to not break Drupal? I've installed Drupal on Red Hat 7 in Amazon Web Services, using a database on a separate RDS instance.

My original problem was that I couldn't make the Drupal installer recognize the /sites/default/ or /sites/default/files directories as writable, even after I confirmed they were writable by the ''apache'' user or temporarily set the permissions to writable by all. (This year-old issue may be similar.) When I filled in settings.php myself, then Drupal gave this connection error:

  PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server on
  'my-database-endpoint.rds.amazonaws.com' (13) in
  lock_may_be_available() (line 167 of /var/www/html/includes/lock.inc).

Disabling SElinux allows the installer to finish and allows Drupal to work. Re-enabling SElinux ('''setenforce 1''') stopped the installer; re-enabling SElinux after installation breaks Drupal, resulting in the same connection error given above. Drupal.org mentions the problem, but doesn't give a specific solution for this case.

I figure many other people must have run into the same problem when installing Drupal.

Obviously I have to re-enable SElinux, so does anyone already know how to modify SElinux configurations to enable Drupal to work properly (and not degrade security)?

Looks like you are connecting to a remote host. You may need to allow httpd to make remote connections. Run these commands as root to set the SELinux variables.

setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1

http://alexbilbie.com/2013/02/selinux-php-mysql/


Module to Create Historic Timeline Snapshots of Drupal Sites? I'm looking for a module to create a functionality where it will take snapshots of the entire site and then replicate it to another domain/sub-domain every X number of days or weeks. I want to do this so I can go visit a previous version of the site in the past to see what was changed. I know you can do this with the module "demo", but that just takes a snapshot of the DB and you would have to revert back to that time overwriting what you currently have. Yes I can create a staging server for this, but I want to be able to have it done automatically where I have the following sub-domains where i can go back to:

1day-ago.foo.com
2day-ago.foo.com
1week-ago.foo.com
1month-ago.foo.com
2month-ago.foo.com
3month-ago.foo.com

How would this be done? Or is there a module for something like this?

You should take a look at Aegir. Although it is more than a module, it has the functionality you describe. Basically what Aegir can do for you is create a complete copy (database, codebase and files) of your Drupal website. The catch here is that your Drupal site should be managed by Aegir as well.

On the more technical side, if you take a look at what Aegir does, you will notice that creating a copy of your website is performed by a number of drush scripts. These scripts could of course be used/modified to make your snapshots.


insert read-only multilingual text to user registration form I've added a 'Term of use' read-only description into the Drupal user registration form, but I would like to make it multilingual.
The corresponding code is in the begin of template.php (responsive is the theme name):

function responsive_form_alter(&$form, &$form_state, $form_id){
switch($form_id) {
case 'user_register_form': // the value we stole from the rendered form
$multi_regform = array(
'#type' => 'checkbox',
'#title' => t("Elfogadom a moderálási elveket"),
'#description' => t("A Magyar Térinformatikai Társaság (HUNAGI) hivatalos honlapján való publikálás és kommentelés lehetőségét a HUNAGI regisztrált tagjai ..... A közzététellel a regisztrált felhasználó lemond a bejegyzés feletti rendelkezés jogáról, későbbiekben anyagi vagy más jellegű követeléseket ezekre alapozva nem támaszthat. - A HUNAGI vezetősége - "),
'#required' => TRUE,
'#localize' => TRUE, // Does not function...
'#weight' => 1, // Adjust so that you can place it whereever
);
$form['terms_of_use'] = $multi_regform;
break;
}
}

You can check it here: http://hunagi.hu/hu/user/register

Now the text is Hungarian, can I add an English one someway?

ps: I've already tried this by Field addition by Field Group, Field Permissions modules, that did not work.

You should be able to translate your strings at admin/config/regional/translate/translate, just search a word contained in the two hungarian strings (case sensitive!), click on the edit link of the relevant string and you should be done.


How to get content type stats into view Hi I am a new drupal coder working a project and making fairly good progress with views an such but i am having a hard time with a specific request.

I need to build a block to display a list of stats in various locations

number of registered users

number of tags uses on a certain content type

number of posts of a certain content type

number of comments contained on all posts of a certain content type

number  of revisions on all a certain content type

I am not sure how to get the above data into views.

I would greatly appreciate if somebody could point me in the right direction.

It's hard to know from your question, which part you're having a hard time with exactly, so I'll just be general in my response:

Typically, when you set up a view, you're getting either users, or content, or terms, or comments -- those are very different types of data.  Typically, a view will not give you all those things together in one display.

So my suggestion would be to try to get each of the different stat types in separate views, and then you can always combine multiple views in one page or block for display purposes at the end...

So, when you start creating a new view, select the correct type of content to show on the first view setup screen (I'm assuming you're using Drupal 7 - it's always useful to specify in your question or via a tag). In Drupal 7, that first view setup screen will prompt you for the type of data you're going to be displaying, so select 'Content' for the revisions stat view or 'Taxonomy term' for the tagging stat view or 'Users' for the user stat view, etc.

Then go from there... just try to do these separately and that would be easiest!!


Get taxonomy term ID from standard URL and then pass it to a View as a contextual filter is a simple question, I whant get the term ID (tid) from standard drupal taxonomy url taxonomy/term/167 ou 167 is my tid and use as argument on views.

I found this code to get the tid:

$term_path=drupal_get_normal_path('position/'.arg(1));
$tid = basename($term_url);
$$here_is_my_tid = taxonomy_term_load($tid);

How to get taxonomy by URL alias?

I try also :

$here_is_my_tid = drupal_lookup_path('source', 'taxonomy/term/'.$tid);

$here_is_my_tid = drupal_get_path_alias('taxonomy/term/' . $tid);

But I try many combination without success.

Here is my views with the tid from url I try to pass "$here_is_my_tid"

$view1 = views_embed_view('mavue','page',$here_is_my_tid);

 if(arg(0) == 'taxonomy' && arg(1) == 'term') {
            $tid = (int)arg(2);
            $term = taxonomy_term_load($tid);

      }
    $view1 = views_embed_view('mavue','page',$term);

By advance thanks

You do not have to write any code to achieve that.

Just go to the views edit page, add a contextual filter named as Has taxonomy term ID and select Provide default value, see screenshot for more options

However, you can also do it pragmatically

function HOOK_views_query_alter($view, $query) {
   $term = menu_get_object('taxonomy_term', 2);
   if ($term && $term->vocabulary_machine_name == 'VOCABULARY_NAME') {
     if ($view->name=='VIEWS_MACHINE_NAME') {
       $view->query->where['0']['conditions']['0']['value']= $term->tid;
     }
   }
}

I hope it helps.


Create a view from specific Node ID's I want to create a view with specific nodes. How can I tell views specific node ID's in a list to display?

So for example, I want an unformatted list with node id's 33, 30, and 15.

I tried using the Filter Criteria: Content:NodeID. The problem is that it only allows for numeric value evaluation. It works when i specify using ONE node id. If I add another, it doesn't display anything. If I add another filter using Content:NodeID and specify another node. It also doesn't do anything.

It allows for a regex, but I'm not sure that even with a regex it would allow me to drop in a list of NID's.

If specific means fixed, you can use fixed value for context filter.

Add contextual filter Content: Nid.
Allow multiple values for this filter in More fieldset.
Input your NIDs as a default value, where + means OR:

In some cases Nodequeue can be useful.


Sort view items by field collection's field value I added a field collection to Basic page that contains:

box title
box image
box position on page

You can add 0 or more field collection's items to every basic page. Every node may contain 0 or more boxes. They will be used instead of default teasers. Here is an example:

Node 1:

field collection item: [Title 1, image1.png, 3]
field collection item: [Title 2, image2.png, 1]

Node 2:

field collection item: [Title 3, image3.png, 2]

Taxonomy Term View is configured as below:

Format: unformatted list
Show: Fields

FIELDS

Field: The field collection

FILTER CRITERIA

Content: Published or admin

SORT CRITERIA

Field: box position on page (asc)
Content: Post date (desc)

CONTEXTUAL FILTERS

Content: Has taxonomy term ID (with depth)
Content: Has taxonomy term ID depth modifier

However, items are sorted only by post date and "box position on page" field has no impact on sorting. I expect boxes to be sorted in this order:

field collection item: [Title 2, image2.png, 1]
field collection item: [Title 3, image3.png, 2]
field collection item: [Title 1, image1.png, 3]

Note that 2nd box leads to Node 2 and the remaining to Node 1.

How to sort boxes by "box position on page" field that is part of field collection?

You can use field_collection_views module which it creates a default View of field collection type. Its address is /admin/structure/views/view/field_collection_view and I recommend you clone this View and configure the rest of the options. The Fields section contains a few items that are very helpful, like Host Entity ID, Host Entity Type and ... .


How can I prevent "zend_mm_heap corrupted" when adding Views programmatically? I have created a module that has 150 views added to mymodule.views_default.inc.

At first I could not get this to load as I was running out of memory. After increasing my memory to a sufficient limit, I now always get the error:

zend_mm_heap corrupted

Has anyone encountered this before while adding views to their modules?

There are several bugs reported to php.net about this error (search "drupal zend_mm_heap corrupted). Indeed it turned out to be a PHP bug with php 5.3.

I upgraded to php 5.4 and the error goes away.

The issue is not necessarily Drupal related. However, it does seem to be related to how php includes and processes large files. In that respect, since Drupal can end up dealing with massive amounts of files and php data, this is probably the reason that many of the reported PHP bugs involved Drupal sites.

So, if you are getting this error, quite possibly you need to upgrade your PHP to 5.4


How to configure a module after installation In my Drupal 6 website there are a bunch of modules. What is the simplest way to configure these modules? Also I am not sure of where their settings are? If there is a simple link that can be invoked to configure them , that will be awesome. In this case its the ctools module.
I am not looking for http://www.sitename.com/admin/by-module neither the Site building has the module.

Thanks

It's up to the module itself to present configuration options, and in Drupal 6 these can be a bit harder to find. I definitely recommend installing the admin_menu module (http://drupal.org/project/admin_menu), which can provide expanding drop-down menus to easily browse through all of the admin-side links.

With cTools specifically, the base 'Chaos tools' module won't do anything on its own, though it can be required by other contrib modules. If you're looking to use one of the bundled modules such as Stylizer or Page Manager, you'll need to enable and configure those modules separately.


Capturing Data on Multistep form to send to an API I am connecting to an API that returns some data based on a user's zipcode.  This data needs to be included in the payload of a second call to the API along with sone other form values.

I wanted to build the webform as a multistep, the first page collects the zip code and after the Next Page is clicked, do an API call to send the zipcode and save the response from that call, so that on the second page the Submit sends via another API call that response data plus all of the form values.

This Get the draft data in the webform hook_form_FORM_ID_alter() seems to be the answer but not quite.

You should write a custom WebformHandler that adds the return API data to $form_state and then alters the form elements as needed. There are some blog post available about writing webform handlers.

Here is how to get the current page from the $form_state.

/** @var \Drupal\webform\WebformSubmissionForm $form_object */
$form_object = $form_state->getFormObject();
$current_page = $form_state->get('current_page');


display content type in view I have 2 content types courses and courses_type, I added courses_types as node reference in courses.

when going to build view to dispaly all courses with thier courses_type the courses_type column is empty. what i am doing wrong?

For Drupal 7, use the Entity and Entity Reference modules. This is just a simple view. You don't need to create any relationship. Just add course type in Fields.


always include language code in url For SEO reason I need my site to always use language code in the URL. At the moment mysite.com/en/news is also accessible through mysite.com/news, according to my SEO contact, mysite.com/news should return content.

How do I achieve this behavior?

Using the Global Redirect module with the default options. You can redirects all URLs without a language prefix to the correct URL with the default language prefix contained.


Select List, 'Other" option text field, any text written in textfield 'Illegal Value' error is given In one of my content types, I have an option for a select list with pre-defined values. I have the 'other' field configured, so when selected a text field displays to enter the 'other' information.

However whenever a user enters information into the text field and attempts to save the form, an "Illegal Value" error is displayed.

I went in and looked at the configuration and could not see anything wrong. Any ideas?

Are you using http://drupal.org/project/select_or_other ?

Is the field set as required? Take a screen pic of the config for the field.


Background Image on pages I want to display the content of a page in the manner as present in the image below:

Are any module present for this?

As said in other answers you can do that by theming. If you want to go for modules. Then these are for you.
Background Images

Background images is a collection of modules that allows users to add background images to html elements on pages of the site

Background Images Formatter

This module provides an image formatter who allows you to set an image
in background of a div. The images are from a field of an entity and
not from a configuration page or sth else, so it's very easy to setup
and manage.
Use cases

You want to display a image on the back of a div when viewing a
particular node.
You want to display a random image on the back of a div on the
frontpage only. This can be done using Views. Create a block, select
the "Background Image" formatter for your image field, save, place
the block, boom, you're done.


Add custom validation on views exposed filter block form I have one content type called Address. It has title, body, etc.. fields.
Initially Created view for Address.

Later client wants to add search field for this view.
So created exposed filter block for body field.

Now search block with results working fine.

But challenge is, we need MINLENGTH validation to that search field.

Added $form['#validate'][] = _custom_validate; in form_alter.

if ($my_field_length < 4) {
  form_set_error('my_field', t('Please enter minimum 3 characters.'));
}

First Question: This validation is happening on each page load but it is not triggering when we submit form (This is ajax form).
Second question: Is that any possible to stop validation or auto submit on intial page load?

There are many issues reported for this behavior on Drupal.org and Drupal Answers.

As a work around, you can try HTML5 pattern attribute to add minimum length validation, check example here.

Or add a small JS snippet to validate input field on blur event.


Get Views object from entity template I have a Views, that renders nodes as "Rendered entity" with custom display mode - "cover". In template (or preprocess function) for this specific theming case, I need to get the Views object, that calls this render process, especially its arguments. How can I do this?

The "Rendered entity" row type comes from the Entity API module.
When using the node view row type the views module adds the view object to the node in views_plugin_row_node_view::render(), however the entity module doesn't do anything similar for its row type, so there is no easy way to get the view object when themeing the entity.
If your view is using a page display you can use views_get_page_view() but this doesn't work with other display types, like block views for example.
Note that there is a feature request for the entity module to add the view object to the entity but it is still in development and the module maintainer wants to use a different approach.
So you could use that patch and then when a newer patch comes along you will likely need to make some minor tweaks to your custom themeing code, or you could make a new version of that patch as per the maintainers comments and then use that and possibly avoid having to change your custom code in future.
If you are comfortable updating the patch I would recommend that approach, otherwise I would recommend using the current patch and updating your custom code in future.


source code shows proper img tag from $row output, but no actual image in browser In my tpl file that has custom code for a block view, I have an object $perfomer which I use to display it's picture with custom code. So I've written code as follows:

    <?php $picture = file_load($performer->field_performer_foto['und'][0]['fid']);  ?>
    <?php $realpicture = file_create_url($picture->uri); ?>
 <?php  print ''; ?>

So like the title of my question says, in my source code I get a proper img tag that looks like this:

To test this, I pasted this html into a Page, and the picture showed just fine on that page. However, in the block view for which the mentioned tpl file is coded, there is no picture shown in the browser, only a square box of 120px by 120px with the alt value inside of it.

Ok creds to clive. See syntax error in comments.

For those who need the actual code in the answer:
<img scr should be <img src :)


Map or Edit Query String Values in Views? As part of a port of a non-Drupal site to Drupal, I need to map a url query string to filters.

For example, if I have this query string and slect filter selected on Site A (Non-Drupal)

Site A

Value 1 | Value 1

Value 2 | Value 2

Value 3 | Value 3

www.sitea.com/?value=value%1

Site B:

Value 1 |1

Value 2 |2

Value 3 |3

www.sitea.com/?value=1

Site A cannot be edited. Is it possible to either edit the values in Site B to match that of site A (within views only, not actual field data) or map the query string, so that Views will see  "www.sitea.com/?value=value%1" and display "www.sitea.com/?value=1"

I know I can change the Filter identifier (i.e. ?value)  on the filter settings tab but how can I changed the values themselves?

In reality, they are far more complex than this so I'd like to avoid HTACESS.

You can use the hook_views_pre_view function in your custom module to change the query parameters using PHP, so a rough untested example of the code could look something like:

function MODULE_views_pre_view(&$view) {
  switch ($view->name) {
    case 'YOUR_VIEW_NAME': {
      // change your query strings to
      if ($_GET['value']) {
        $value = $_GET['value'];
        $new_value = substr($value, 0 , 6); // remove the 'value%' from Site A querystring
        $_GET['value'] = $new_value;
      }
      break;
    }
  }
}


How to recover content/configuration from a hacked site I have a situation where I am faced with two sites which were vulnerable to the Drupageddon SQL injection exploit.  I am looking at what is the best strategy for recovering these websites.  Given that the sites were not patched within the alloted window of time, I am forced to assume they have been compromised.

There is a lot of information on what to do after one's Drupal site has been hacked; but one question that is not really addressed is the workflow for recovering content from the compromised site.

In the case of one site, no pre-exploit database backup is available. For the other website, there is a pre-exploit database backup; however, there is a large amount of post exploit content which has been created/updated.

What would be the workflow for recovering content (other than recreating everything by hand).  Issues I can think of are:

How to clean up existing content?
What tools to use to achieve this?
How to get the content out of the old site and into the rebuilt one?
If site is being rebuild from previous DB backup does it make sense to try to only import content which has changed or been added since previous backup? or does it make more sense just to re-import everything?
How to recover site configuration? Would it be possible to create features and then 'clean' them before installing into rebuilt site?

I have never used this module, but it might be worth researching and using on a COPY of your site - Drupalgeddon module.

The first step to recovering from a hacked site is to do an audit of the activity that has taken place. If you have HTTP server logs (apache access logs, etc) you can review the various attack vectors (e.g. POST /node/add, POST /node/3/edit) to identify areas that were compromised. Based on this activity you can formulate a time window when the attacks occurred and search for content edits within that (e.g. checking the "changed" date on the node table). I do know Drupalgeddon does modify records in the users table, so definitely check that.

Either way I think a full audit of the entire database and file-system (pretty sure Drupalgeddon does write to your docroot; hope you have version control to see changes?).


How to safely remove fields from create content - project I am customizing the Project Management (pm) module. When I create a new Project content type I do not need some of the fields such as price and currency for my particular application. I am concerned that if I use the Fields UI to delete them that when a new version of pm is release that I'll have problems installing it. I also worry that I might mess up the database.

I have made these fields hidden, but they still appear on the create new Project content page.

Are my worries baseless?

Normally I would suggest just hiding the unwanted field via a hook_form_alter, either by setting $form['unwanted_field']['#access'] = FALSE, or by using the hide() on that element. If the field is a required field, you'll want to alter that property as well, or set a value before hiding it or setting '#access' to false.

if you want to actually delete the field, you can use drush to run field_delete_field(). For example, drush eval 'field_delete_field("unwanted_field")' should work (untested).


Hook_node_grants: how do I access a user account field? Here is my implementation of hook_node_grants:

/**
 * Implements hook_node_grants().
 */
function gcac_node_grants($account, $op) {

    // Declare $user as having global scope.
    global $user;

    // Permit a user to view the node if the node and user are assigned the same
    // group.
    ** if ($user->field_group[LANGUAGE_NONE][0]['value'] == $node->group && $op == 'view') {
        $grants['gcac_view'] = GCAC_ALLOW;
    }

    // Permit the user to edit the node if the node and user are assigned the same
    // group, and the user is the author.
    ** if ($user->field_group[LANGUAGE_NONE][0]['value'] == $node->group && $user->uid == $node->uid && ($op == 'update' || $op == 'delete')) {
        $grants['gcac_edit'] = GCAC_ALLOW;
    }
    return $grants;
}

I have added a field to my user accounts called 'Group' and populated it with a value for several accounts. Yet, here is the error that is being thrown:

  Notice: Undefined property: stdClass::$field_group in
  gcac_node_grants() (line 21 of
  /homepages/99/d99999999/htdocs/node-access2/sites/all/modules/gcac/gcac.module).

As you can see I'm trying to access the 'Group' of the current user so that I can compare it  to the 'Group' assigned no a node. I just want to access the value. Originally, I tried accessing $account->field_group[LANGUAGE_NONE][0]['value'], but I got the same error.

I can go grab it from the database, if I have to because I know I can access $user->uid, but surely the user module is providing my the field for me use? Thanks.

As per your error statement, field_group does not exist in $user object. The global $user object does not load the fields which are attached to user profile. if you want to load the complete user profile with attached fields, you need to use function "user_load" in your code.

global $user;

$account = user_load($user->uid);
if ($account->field_group[LANGUAGE_NONE][0]['value'] == $node->group && $op == 'view') {
  //Do the needful
}


How can i edit a content types taxonomy terms trough the front end I have put the taxonomy terms on the top of the page and i want to add a little cross on each tag to delete that tag (by the users) and also a 'add' button that lets people quickly add a tag to that page.

Does anybody know in which direction i should look? I'm willing to program is but i don't know which hooks i should use or where to put them. I've found pieces of code i could use but nobody ever mentions where to put it.

You could take a look at the flag module (not ready for D8 yet)

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

https://www.drupal.org/project/issues/search/flag?project_issue_followers=&status%5B%5D=Open&issue_tags_op=%3D&issue_tags=beta+blocker


Translate an SQL update query into Drupal language I need to convert the following query that works against a database table

"UPDATE MYTABLE SET field_temp= %s", UNIX_TIMESTAMP(field);

into Drupal language

db_update('MYTABLE')
      ->fields(array(
          'field_temp' => UNIX_TIMESTAMP('field'), //or strtotime()
         ))
        ->execute();

seems to be not working.

UPDATE

db_update('MYTABLE')
        ->expression('field_temp',  "UNIX_TIMESTAMP('field')"),
        ->execute();

will run into:

PDOException: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:

Some more details:

'field' is datetime format type, field_type is 'int' format type
I am running this script through a hook_update_N
I am debugging it by running update.php

You need to add an expression():

db_update('MYTABLE')
  ->expression('field_temp', "UNIX_TIMESTAMP(field)")
  ->execute();


General error: 2006 MySQL server has gone away This is the error I am suddenly getting.

Additional uncaught exception thrown while handling exception.

Original
PDOException: SQLSTATE[70100]: Unknown error: 1317 Query execution was interrupted...my query

Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away...my query

After doing some research it sounds like a custom module, which I have made, is attempting a query which is too big. A solution that seems to work for a lot of people is this:

Open my.ini
Change "max_allowed_packet" from "1m" to "16m" (or larger)
Save my.ini and restart MySQL

However, I am on a shared server, so I cannot edit my.ini, and although my provider has confirmed to me that the value is set to 1M, they won't increase it.

I also tried adding this: ini_set('mysqli.reconnect', 'on'); to settings.php. It didn't solve the problem.

Does anyone know of a another solution, or work around?

Thanks.

Shared hosting companies do not give away the SUPER privilege. If you have it, you can easily set max_allowed_packet  to 512M by just running this :

mysql> SET GLOBAL max_allowed_packet = 1024 * 1024 * 512;

No restart is required. Then, all incoming connections thereafter can have a 512M packet.

You cannot do this:

mysql> SET max_allowed_packet = 1024 * 1024 * 512;

because you get

ERROR 1621 (HY000): SESSION variable 'max_allowed_packet' is read-only. Use SET GLOBAL to assign the value

The only alternative I can think of is to switch to Amazon EC2 and install MySQL there. That way, you can have free rein to edit my.cnf/my.ini and have the SUPER privilege.


$form_state['values'] empty in form _submit hook I have an issue with a form I built in a custom module using drupal_get_form() on a menu callback.

My form callback function is _foo_form($form, $form_state) and my submit function _foo_form_submit($form, $form_state).

When I submit the form, $form_state['values'] contains the value in the form callback, but in the submission handler $form_state['values'] is empty.

Here is my module code:

function configurator_menu() {
  $items = array();
  $items['node/%/configurator/items'] = array(
    'title' => 'Steps & items',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('_configurator_node_edit_item', 'list', 1, ''),
    'access arguments' => array('administrer configurator'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
}

function _configurator_node_edit_item($form_state, $op, $nid, $iid) {
  $form = array();
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid
  );
  $form['title'] = array(
    '#title' => 'Step label',
    '#type' => 'textfield',
    '#value' => '',
    '#size' => 30
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
  );

  return $form;
}

function _configurator_node_edit_item_submit($form, $form_state) {
  dpm($form_state['values']); // devel function to print variable in drupal messages
  // returns an empty array
}

Do you have any idea?

Change property '#value' to '#default_value'.


Use computed field to calculate Field collection I have a field collection named values. It contains the fields:

Amount
Price
Total

The "Total" field calculates the Price*Amount.

Now I created a new field outside the field collection called "Subtotal".

How do I sum all the values of the "Total" field in a node to populate "Subtotal"?
I tried a lot of code which I found but none seem to work.

I tried this code but it gives as a warning: undefined index at line 5

$field_items = field_get_items($entity_type, $entity, 'field_values');
$total = 0;
foreach ($field_items as $item)
{
  $total += $item['field_total']['und'][0]['value'];
}
$entity_field[0]['value'] = $total;

Thank you in advance!

I've got it! After a lot of tries I found a solution:
This works for a computed field outside the collection.

$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach($wrapper->field_values as $collection) {
   $sum += $collection->field_total->value();
}
$entity_field[0]['value'] = $sum;


Features confilict with content types I have 3 different environments such as Dev, Test and Stage. I'm currently facing an issue when trying to propagate my changes from Dev into Test and Stage envs. In order to propagate the changes i use the Features module. Within features i export all my Content Types. Some of them (e.g. Basic Page) are already exist into Test and Stage environments. When i'm trying to install the feature export from Dev into the other environments, the Basic Page content type of Test and Stage actually seems to be overridden. This means that the predefined fields that already has are not erased by the feature but it just adds the new created fields. How can i solve this issue. The desired functionality is to have the same fields after importing the future to all environments.

If I'm not mistaken, Features doesn't delete fields it only synchronizes the configuration and creates new fields if they are not present. So, deleting obsolete fields is one of the processes you have to do by hand (or write an update function in a custom module).

Features is a handy tool, but certainly has some limits (for instance when you want to synchronize blocks).


Migration doesn't work when executed with cron I've set up a migration between 2 Drupal sites hosted on the same server (Drupal 8 -> Drupal 9). I'm using migration support recently added to drush to run these commands. I've created a helper bash script, which contains:
#!/bin/bash
sites=(<mysite>)
for site in "${sites[@]}"; do
  drush -r /var/www/drupal -l $site mim <migration_id> --update --execute-dependencies >> /home/<myuser>/migration.log
done

This works fine, when I execute this script manually. However, it doesn't work (content isn't migrated), when it's executed by cron, defined like this:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /home/<myuser>/<myscript>.sh >> /home/<myuser>/migration.log

There's no output in the log and no errors in /var/log/syslog, where can I only see output like this every 5 minutes:
Feb 16 15:35:01 <hostname> CRON[22314]: (<myuser>) CMD (/home/<myuser>/<myscript>.sh >> /home/<myuser>/migration.log)

What can I do to debug this issue and resolve it?

It seems that the path to drush was wrong when the script was running by cron. Lesson learned - I should be using full paths when working with cron.


Drupal database loading slow I'm making a website (don't open in IE) where I use Ajax to load a view. I now want to use BOOST to cache the view as HTML.

These pages should be "BOOSTED":

http://www.spanjevakantiewinkel.nl/regio/ajax/8
http://www.spanjevakantiewinkel.nl/regio/ajax/9
...

Should I use JSON instead of my way to load the view? Any idea how?

The ID (8,9,...) is given by hovering a small image beneath the large header image. Then the view will be loaded, but always within the database, I want HTML pages made with BOOST.

function dynamic_regio_menu() {
  $items = array();

  $items['regio/ajax'] = array(
    'title' => 'Dynamic Regio',
    'page callback' => 'dynamic_regio_get_by_category_id',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function dynamic_regio_get_by_category_id($cat_id){
    $viewName = 'regio_submenu'; // The name of the view we are going to load

    $args = array($cat_id);  // Array of arguments we set for the view.
    $displayId = 'block'; // The display id of for the view.

    // Call the views_embed_view function to returned themed view output
    $html = views_embed_view($viewName, $displayId, $args);
    echo $html;
}

xhr = $.ajax({
  type: 'POST',
  url: '/regio/ajax/' + this.parentNode.getAttribute('tid'),
  success: updateData, dataType: 'html',
});

I think the problem is how your views are cached - if you say it is sometimes slow, it is most probably because those times the cache is beeing saved.
If the content doesnt change often, you might just prolongue the interval. Another option is to use Views content cache.
But basically if you have enough visitors (and enough people hovering the images :), they will only wait from time to time ...


Redirect to another form on login I have created a test site using drupal 7.

My requirement is to do an additional operation on user login.
I need to redirect the users to another form when the user clicks on login button.

In this form there will be a question and 2 buttons 'update' and 'no'.

If the user chooses update a DB update will happen and also default login action.

But if the user chooses 'no' ,login should not happen.

I have already tried user_login alter, multi-step forms and confirm_form. But nothing seems to be working. Can anyone help.?

You can make your own login form (or alter default login form, i think) with two submit buttons calling different callback functions:

function xxx_login_form($form, &$state) {

  // .. usename and password fields here

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

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

  return $form;

}

function xxx_login_submit_update($form, &$state) {

      if(user_authenticate($state['values']['username'], $state['values']['password'])) {
        // log in user
        $user_obj = user_load_by_name($username);
        $form_state = array();
        $form_state['uid'] = $user_obj->uid;
        user_login_submit(array(), $form_state);

        // .. do some updates

        return true;
      } else {
        return false;
      }

}

function xxx_login_submit_no($form, &$state) {

   // do what you need but do not log user in.

}

You can of course add custom validate functions, messages or what you need. If you want redirect to another page after button is pressed, you can use

'#action' => 'some/page/1'

for the buttons.


Move fields from additional settings to field_group on node edit forms I try to move some settings, for example the comment or menu settings, from the "additional settings" to my own field group created with the Field Group module.

As there is no way to access the fields under additional settings via the gui I thought about moving them via a form_alter hook, but with no success.

Update

Here is the code i used in a custom module to (unsuccessfully) move a field:

function form_tweaks_form_alter(&$form, &$form_state, $form_id) {
  if(isset($form['#node_edit_form']) && $form['#node_edit_form']) {
    // Adding the comment settings to my field group
    $form['#group_children']['comment_settings'] = 'group_sidebar_tab4';

My module's weight is lower then the weight of the field group module and when I use the above code on other fields added to the content type, for example an image field, it works just fine.

Update 2

Just to make sure, I am talking about node forms. I want to move certain elements that resist in the "additional settings" vertical-tab-group to other groups.

Display Suite

-module which changes the manage display page to allow exactly for that and moving title, links, comments and way more useful features like changing/resetting field and views templates, linking between displays, dynamic & block fields, moving fields to a block just to name a few. It could replace views in those cases where you mainly use views to have more control over the output.
Thank You.


Views UI broken after site migration Ive migrated my site and now my View UI is broken. My relationship 'Relationship: Entity Reference: Referencing entity' works the opposite way round to the way it should. This has been confirmed by a colleague who uses Drupal.

Also fields that ive added to my content type are not available as fields in views, and sometimes the body field is missing too.

Does anyone have any ideas as to how I would start to go about fixing this? My Drupal status report doesn't return any errors.

Disabling a custom module has fixed this.


Taxonomy Term View - how to display parent View term info when child terms exist? I have two views set up: one that displays the image field, title, and description for each taxonomy terms in a vocabulary, and one that displays a grid of photos/nodes that are tagged with a taxonomy term. What I want is to always display the parent term image/description in the first View so that users can drill down to the children terms, and then ultimately click into the second view of photos/nodes.

For instance, the first View is made up of taxonomy terms associated with the taxonomy vocabulary "Gallery". Under gallery, I have the terms "Parties" and "Games". Parties has no children terms, but "Games" has "Sports" and "Other Games" as children terms.

I would like the Gallery View page content to be displayed this way:

[parties]  [games]

Clicking "Parties" would bring you to a view page (the second View) that shows all of the photos/nodes tagged with that term. Clicking "Games" would take you to a View similar to the first View that shows the taxonomy fields for the child category, like so:

[sports]  [other games]

Clicking on "Sports" or "Other Games" would take you to a view page that shows all of the photos/nodes tagged with that term, like the "Parties" page operates in the example above.

Make sense? Hoping someone here can point me in the right direction.

Thanks!

What you would probably want to do is create a view of the taxonomy terms that lists Parties, Sports, etc.  On the fields to display, re-write the output to a link to categories/%1, which will take the term being listed as an argument, and make sure to un-check link to taxonomy page.  For this view you should make the link something like "categories".  Then, in the second view (or maybe just another page in the same view), make the link something like "categories/%"  The % wildcard will take in the value of the taxonomy term form the page before.  So when you click the link from the first page it will link you to the second view, where you can make a contextual filter that takes the taxonomy term given via the URL from the one clicked on the first page and have it list the terms based on that with a relationship.