How to display all records by default on a view with exposed filters I've managed (after a lot of struggle) to create a view with four exposed filters (all filters are taxonomy fields). My problem is that now by default no data is presented to the user whene the page loads and data appears only when a filter term is chosen. I'm trying to achieve the exact opposite: have all data presented and then filter it accordingly. how can i do it?

When editing the filter, you can choose to require it if it's a select type of filter, you can also provide a default filtering that's used (before the user inputs). My guess is that you need to tweak these settings. to make sure that the default view filter settings display all or a selection of your choosing.


hook_scheme doesn't work Possible Duplicate:
  hook_schema is not creating database table

I am developing a module in Drupal 7. It is called scorm. I created scorm.install file, where I wanted to create the necessary tables, when the module is being installed. For testing I used book module: I installed it and 'book' table was created.

So I took the code from book.install, renamed all the functions prefixes from 'book_' to 'scorm_' and tried to install my module. I added this code to scorm_schema function:

function scorm_schema() {
    print 123;exit;

And 123 was printed when installing. So I removed this test code, being sure, that the hook is called.

But the book table was not created! How can I debug and find out the cause of problem?

hook_schema() should return an array that defines a database schema.


Generate js variable before javascript loaded I have a block with invocation code inside(it invokes js code from OpenX ads server), my site is responsive and this block get cloned(with jquery .clone() function) on ipad or iphone version of the site. So to avoid calling the invocation js code 2 times i need to set js variable (like this - > window.isScriptLoaded = FALSE) and then inside my block i can easy do next thing:

if (window.isScriptLoaded == FALSE) {
    window.isScriptLoaded = TRUE;
    //invocation code...
}

in this case all working fine, i can easy add this variable to any js file in drupal.

But in my case admin can add new block and insert new invocation code - SO I need to generate window.isScriptLoaded2 and output this variable BEFORE code in block is loaded

i tried next thing

function HOOK_page_alter(&$page) {
  //get all the variables
  //i generate my variables in database
  $var = db_query("SELECT * FROM {banners}")->fetchAll();
     $full_array = array();
     foreach($var as $object) {
         //for example Anyvariable = FALSE;
         $array[$object->name] = $object->value;
     }
      drupal_add_js(array('common' => array(
    'vars' => $array,
    )), 'setting');

}

this works but, code in block is loaded before drupal.settings.vars.Anyvariable is loaded.
So my variables is always false

It is also hard to say if this will work without seeing exactly what you need to do, but you may want to play with the scope, group, and weight options for drupal_add_js().  These may help you get the order that you need.  From the docs

  The exact ordering of JavaScript is as follows:

  First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by
  the theme.
  Then by group.
  Then by the 'every_page' flag, with TRUE coming before FALSE.
  Then by weight.
  Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js()
  that happened later in the page request gets added to the page after
  one for which drupal_add_js() happened earlier in the page request.

When I have been in similar situations, I implement a template_preprocess_html(), create some markup, stuff it into $variables, and then output this before the print $scripts in html.tpl.php  I have to use this in some very specific situations where I need to output JS very early in the <head> before CSS and JS is loaded.


Imported site doesn't displays CSS styles I imported a site from pantheon to my localhost to work on it. The site pulls up just fine, however, it has no CSS styles at all. Its plain HTML through and through. Also i'm getting 30+ of these type of errors:

Warning: file_put_contents(temporary://fil739F.tmp): failed to open stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in file_unmanaged_save_data() (line 1940 of C:\wamp\vhosts\cbirc\includes\file.inc).
The file could not be created.

How do I get the styling added back to the site?

Make sure you've properly configured Temporary Directory inside Admin => Configuration => Media => File System, and check if "Public File System" and "Temporary Directory" have valid permissions to them. Once confirmed, clear site cache.

If not required you can also disable CSS Compression by navigating to "Admin => Configuration => Performance". So they will be accessed directly for there original location.


Custom field placement I have a custom field that is an unordered list that I want to be placed under a static title and to the left of an advertisement. I only want this to show on article pages, but right  now I can't seem to figure out how to place the custom field where I want it to be placed. I know a module is required, but what I am asking is if anyone can give me the correct hooks or whatever to retrieve the custom field information, so I can place it where needed.

Copy node.tpl.php of your theme and name it node--article.tpl.php. In this file create the html structure you like. In this file you have access to the individual fields.

<?php print render($content['field_customfieldname']); ?>

will print out content of your custom field. Wrap this filed with html id or class and style it with css.
(I am assuming you are working with a non core theme)


How do I calculate the resource requirements for using Solr? I want to use Apache Solr for faceted navigation of my D6 site(s), but I'm unsure of the resource requirements for it. How do I check if my VPS can cope with implementing it?

This is not the most complete answer but no one else has stepped up so hopefully this can be somewhat helpful.

I would say that the biggest potential issues on a box that size would be running out of memory and disk space. You can allocate memory to your java vm to mitigate potential memory issues. Solr is under load when indexing and retrieving search results (obviously). You can mitigate the indexing load by indexing in small batches. Though in terms of memory footprint if you are substituting solr with normal Drupal search your load on apache/mysql will be greatly reduced.

I would say that I've run multiple solr instances with a higher load than you are describing on a 1GB VPS.

You may get a more detailed answer if you go to ServerFault or the Solr mailing list and share the solrconfig.xml and schema.xml files from the ApacheSolr module.


Error on views page. Any idea what this means? Uncaught exception thrown in session handler.

  PDOException: SQLSTATE[08S01]: Communication link failure: 1153 Got a
  packet bigger than 'max_allowed_packet' bytes: UPDATE
  {sessions} SET uid=:db_update_placeholder_0,
  cache=:db_update_placeholder_1, hostname=:db_update_placeholder_2,
  session=:db_update_placeholder_3, timestamp=:db_update_placeholder_4
  WHERE ( (sid = :db_condition_placeholder_0) AND (ssid =
  :db_condition_placeholder_1) ); Array ( [:db_update_placeholder_0]
  => 1 [:db_update_placeholder_1] => 0 [:db_update_placeholder_2] => 173.8.158.117 [:db_update_placeholder_3] => Wpw4khR1syd0trFnNVSUxDsOs_MtPQ

That gibberish at the end beginning with =&gt; goes on for dozens of pages dumped directly onto the page. Any idea what to look into?

You likely need to bump up max_allowed_packet in your MySQL instance.  That query is likey trying to store a large amount of data.  I have never seen this at runtime, though.  I have only had problems with this variable when trying to restore backups.


Get menu item of a content type Is it possible to get the menu item of a certain content type through the API?

The idea is to improve Markus Orenstrat solution to set the active trail based on the content type. As it stands it requires hardcoding the menu_tree id in the service.

 if ($bundle == 'blog') {
   $plugin_id = 'menu_link_content:a00a209d-075e-46a2-b200-e2d439d92228b';
 }

I figured this could be avoided since the administration area allows to assign a menu item to a content type.

That's stored in the third party settings of the node type.

$type = NodeType::load('article');
$type->getThirdPartySetting('menu_ui', 'parent')

See also menu_ui_get_menu_link_defaults().


What are the different ways I can export permissions from a preconfigured Drupal site I have a site that I need to export permissions from and import into version-controlled code. We aren't using feature, strongarm etc, so although I know a  lot of people will say these are the go to  solutions, I need to look at alternatives. Are permissions stored as variables in the site or otherwise? I would I export and import variables into an install profile or in a module?

This module(Export roles and permissions) allows you to exports roles and permission by generating a hook_install implementation

  This module allows you to generate a hook_install() implementation
  that creates the chosen roles with their associated permissions. The
  main purpose for creating this module was to transfer roles from a
  local dev machine to a remote stage/live server.


Remove default tab from login page ( Simple Fb Connect) I am using Simple FB Connect module for Facebook login in my site. It adds a tab for facebook login, by default in my Login page. I want this tab to be removed and add a button instead. How can I remove this?

Create a hook_menu_alter function like this in a module:

function my_module_menu_alter(&$items) {
  unset($items['user/simple-fb-connect']);
}


Permanently disable Auto Preview in views? Is it possible to make views stop defaulting to Auto Preview on? It's really slowing down my workflow.

As seems to always be the case, I stumbled upon the views settings page after posting the question: On admin/structure/views/settings unselect "Automatically update preview on changes."


How can I create a "show full article" button that bypasses smart paging? I am using smart paging currently but would like to create a button above my articles that would show the entire article on a single page (canonical link) that would also have no pagination (bypass smart paging entirely for that link). I'm not finding any solutions on how to do this. Is it even possible? These links are for search engine indexing so that the non paginated version would serve as a landing page for search results traffic.

I have never used smart paging, but from looking at the docs and the code I would say this is currently not possible. My suggestion in this case would be to create a feature request in the modules issue queue.


List registered users who are currently viewing a page I'm looking for a module that, given a page URL, returns the list of users who are currently viewing it. The list should be dynamically refreshing to show page view activity in real-time.

Is there a module for that?

Check the viewers module. Here is an excerpt from ots project page:

Viewers is a small module, which builds a block showing which other users are viewing the same page as the current user. The 'other' users are logged in users or anonymous users or both users. You can set for how long you want a user appear on the viewers list of each page. And finally you can choose the position of the block from the admin/build/block page.

As stated it won't provide you the functionality of dynamically refreshing to show page view activity in real-time, but you can modify it through the custom code by refreshing the block after a required interval of time. Or you can try the Block Refresh module. Here is an excerpt from ots project page:

Block Refresh allows an administrator to configure a block to refresh it's content via 3 different methods: automatically via a timer (eg every 30 seconds) , manually via a 'refresh' link, and once on page load.
Block Refresh uses jQuery/AJAX so the refresh happens "behind-the-scenes".
Block refresh can be handy to serve fresh content in certain blocks on otherwise cached pages. You can opt to bypass drupal's cache for the refresh callbacks for each block.


create a custom field which is allowing multiple values using custom module I created custom content type and one custom field(text) successfully. But my requirement is, my custom field should allow to add multiple values.

for unlimited set the cardinality to -1  'cardinality' => -1

example:

function _namecards_namecard_installed_fields() {
  $t = get_t();
  return array(
    'namecards_namecard_phone' => array(
      'field_name' => 'namecards_namecard_phone',
      'label' => $t('Phone'),
      'type' => 'text',
      'cardinality' => -1,
    ),
    'namecards_namecard_fax' => array(
      'field_name' => 'namecards_namecard_fax',
      'label' => $t('Fax'),
      'type' => 'text',
      'cardinality' => -1,
    ),
  );

}


Change the content of a node programmatically with hook_node_view I need to append some text programmatically before the text on the home page. But when I use hook_node_view(), I can't seem to do this with the following:

function general_node_view(&$node, $view_mode, $langcode) {
    if ($node->nid == 1) {
      //echo '<pre>' . print_r($node->body['und'][0]['value'],1) . '</pre>';
      $node->body['und'][0]['value'] = 'fdsf' .  $node->body['und'][0]['value'];
   }
 }

Am I going about this the wrong way?

If you are trying for home page then your node should be set as front page content. Otherwise this hook would not do any thing for your home page.

However any node view can be expanded by this hook:

$node->content['additional-text'] = array(
   '#markup' => 'TEXT TO GO BEFORE NODE VIEW',
   '#weight' => -10, // Set as lower as to bring this markup upper
);


Module for requiring some authors' texts to be approved by admin I am developing a site for a client that wishes to have two levels of content administrators, editor and admin. The editor is supposed to be able to edit their own content but an admin has to approve it before it is published. All content is versioned on the site so one version would be displayed to the site visitor while a newer version is in review mode. Once it is approved by an admin it can be published.

Is there any module available for this kind of setup?

I suggest the Workbench module. You will need to dig deeper to have a revision show up while the next one is being moderated, but I'm sure it can be done with hook_menu_alter.


Is it necessary to use "Correct faulty and chopped off HTML" I'm allowing the users of the site to add comments in "filtered html" form.
And the input is in NicEdit though Wysiwyg.

Currently I'm using "Correct faulty and chopped off HTML" option in admin/config/content/formats/filtered_html

Is it still necessary for my site?

I feel it's an overhead!

It is not required when you are using the NicEdit though Wysiwyg.  Because, you are not using any tags in them. I you are concern to use the tags. Then, It is better to use this option. It will auto-complete and correct the faulty tags.

for example : if you forget to use the closing tags. It will add those tags.


How to remove CSS files if the page being rendered is a front page in a theme? I want to remove default Drupal CSS files if it is a front page in Drupal 7 theme.

Following is the code (got from http://www.grahamgilchrist.com/blog/25) that I am trying to put in the template.php for barktik1 theme. How do I check if rendering page is a front page or not? Only $css variable is passed as an argument to the theme_css_alter() function while for other process functions $variables is passed from which it is easy to determine if it is a front page or not.

function bartik1_css_alter(&$css) {

//do something to check if it is a front page
if ($is_front){
    //make a list of module css to remove
    $css_to_remove = array();
    $css_to_remove[] = drupal_get_path('module','system').'/system.base.css';
    $css_to_remove[] = drupal_get_path('module','system').'/system.menus.css';

    // now we can remove the contribs from the array
    foreach ($css_to_remove as $index => $css_file) {
      unset($css[$css_file]);
    }
    }
}

Thanks!

The function you're looking for is drupal_is_front_page().


what is use of $title_prefix and $title_suffix variable inside drupal theme system i am intermediate in php.i start learning drupal 7 theme system. i need to know what is role of  $title_prefix and $title_suffix variable inside .tpl.php files. what happen if we not include these variable inside .tpl.php files. i also read documentation for those variable at drupal.org but documentation is not enough to make it crystal clear.can anybody explain its use in simple words.

I'm not sure how it could be any clearer than on the docs page, but here goes;

$title_prefix is for content that should be displayed directly before the title in a template file (node.tpl.php, block.tpl.php, etc).
$title_suffix is for content that should be displayed directly after the title in a template file.

There really is nothing more to it than that. If you choose not to include these variables in your template file then they simply won't be rendered.

Since any module/theme in the system has the chance to populate/change the values that are in either of these variables it's impossible to say exactly what will not be rendered in your particular case if you choose not to display them.

As an example, (and if I remember rightly), contextual links for blocks/nodes are contained in the $title_prefix variable. So if you don't print $title_prefix in your template, you won't get contextual links for that item.


Display "uncaught exception" page as content-type text/html When there is an uncaught exception, Drupal 8 displays a simple dump of the exception.

I find that the page is served as 'Content-Type' = 'text/plain', yet it contains HTML:

It looks better to me when I change the code to serve as 'text/html':

I already found the code to change - it's in FinalExceptionSubscriber.php, which outputs

</br></br>
SafeMarkup::format(...) which is documented as

  Formats a string for HTML display by replacing variable placeholders.

My question is:

Does anyone know a reason why the error page is text/plain given that it contains HTML.
Shall I raise an issue and patch?

Thanks @4k4, so it seems that this is a minor bug, but the obvious fix would revert the "Standardize handling" issue.

I have raised this issue and linked it to the other issue.  I don't really understand the code here and would welcome any help to improve the issue text.


Use Privatemsg admin form in theme (Missing functions!) I've exposed the privatemsg_list_view() form in my site theme with a bit of work and it's displaying well. However, updating message statuses or trying to delete bulk messages results in a sad error:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /system/ajax
StatusText: OK
ResponseText: Fatal error: Call to undefined function privatemsg_list_submit() in [...]/includes/form.inc on line 1464

Now I know that privatemsg_list_submit() is indeed set as the form #submit handler and I know that it does exist, over in modules/privatemsg/privatemsg.pages.inc. Obviously there is a disjoint between /system/ajax and my template.

What needs to happen to make this work? Do I just have to attach the .inc file to the form handler somehow? I've tried playing with module_load_include() to no avail.

Suggestions?

Update: The only place I have tried adding the module_load_include() function is directly before the function call in /includes/form.inc - that would have been somewhere just before line 1464. Obviously that was just a hack for troubleshooting purposes... should the module_load_include() function be placed somewhere else?

For reference: Call to undefined function privatemsg_list_submit()

Update 2: I have also tried inserting module_load_include() in a custom module_init() function as well as inside the theme hook_form_alter() - no luck.

Update 3: Manually including the file within a module_init() hook makes it work. Here's what it looks like:

function MYMODULE_init(){
    if($_GET['q'] == 'system/ajax'){
        if ( preg_match('/privatemsg_list/', $_POST['form_id'])) {
            include('/great/big/system/path/web/sites/all/modules/privatemsg/privatemsg.pages.inc');
        }
    }
}

While this appears to work on the surface, I'm sure it's not the right method. Is there a better function hook to use to include this file?

Though I suspect that this is an improper workaround, the solution was to hook a custom module's hook_init() function, watch for a system/ajax path and include the file if needed:

function MYMODULE_init(){
    if($_GET['q'] == 'system/ajax'){
        if ( preg_match('/privatemsg_list/', $_POST['form_id'])) {
            include('/great/big/system/path/web/sites/all/modules/privatemsg/privatemsg.pages.inc');
        }
    }
}

UPDATE: Answer is available at https://drupal.org/node/1961776! In short: use form_load_include() instead of module_load_include().


how can I set #attributes for each item of selectlist I know I can set style for form items with #attributes  but I want set background for select list (drop down) items, how can set #attributes for each item of select list(dropdown) in form_alter ?

function MYTHEME_select($vars) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '<select' . drupal_attributes($element['#attributes']) . '>' . MYTHEME_form_select_options($element) . '</select>';
}

function MYTHEME_form_select_options($element) {
  // Build up your own version of form_select_options here
  // that takes into account your extra attribute needs.
  // This will probably involve inspecting your custom FAPI property,
  // which we'll call #extra_option_attributes
}

And your code in the form would be something like:

$form['select'] = array(
  '#type' => 'select',
  '#options' => array(1 => 'One', 2 => 'Two'),
  '#extra_option_attributes' => array(
    1 => array('title' => 'Test title'), // Attributes for option with key "1",
    2 => array('title' => 'Test title'), // Attributes for option with key "2",
  )
);

In MYTHEME_form_select_options() you can then inspect the element's #extra_option_attributes key (if one exists) to see if you need to physically add any more attributes in the HTML you create.

Credit to @Clive for this post : https://stackoverflow.com/questions/9261224/adding-attribute-to-option-element-using-forms-api-drupal-7/9264589#9264589 .. Cross posting here in Drupal Q & A


Change the input format for 3000+ nodes I have a lot of nodes that need to get their input format changed - I could do that by hand, but then I won't be done before Christmas 2014.

Where is Drupal storing that information? How can I change the input format in a split second, with an SQL query?

I'm going to preface this answer by saying doing this en-masse presents a potential security risk, especially if you are changing the format to a more lenient set of filters. Text formats modify field output during display, not during save. So for example, any previously-escaped HTML or PHP submitted to a field will straight up render/run if you accidentally or intentionally set the filter to Full HTML or PHP code.

It's for this reason that Drupal doesn't automatically update all existing nodes when you change a text format. The behavior of text formats in similar scenarios is still an open issue.

So again: beware, there be dragons.

With that said, each field stores the text as a column named field_foo_format, where field_foo is the machine name of the field. You'll need to update that column on the tables field_revision_field_foo and field_data_field_foo.

The value for the column is a machine name defined as the column format in the filter_format table. So, updating all the fields would be a matter of a query like:

UPDATE field_revision_foo SET field_foo_format = 'new_format';
UPDATE field_data_foo SET field_foo_format = 'new_format';

for each field that needs changing.

You can determine new_format value here: http://YOURSITE.com/admin/config/content/formats - configure link - number or string in URL is your new_format. Clear cache after updating.


Get a configuration option from node type structure I'm working on a module and was wondering how to get a node type setting (that was set when creating the node type at: admin/structure/types/manage/YOUR-TYPE) inside a node creating/editing page.

I added a node structure setting with the hook: mymodule_form_node_type_form_alter() and now I want to check if this option is active when creating/editing a node, hook: mymodule_form_node_form_alter()

Node type forms save their data in variable table prefixed with form field name and suffix will be node type.

If field was $form['MY_SETTING']=array(...); you can get the value with variable_get('MY_SETTING_' . $node->type, '');


Exporting large data using cron I am working on a website which has around 150k users.
I have to create a csv file which contains the details of user (drupal fields and profile2 fields ) and export the csv to another server daily.

I have implemented by export function in a hook_cron and in the function i do a user_load function call and two profile2_load_by_user and some other custom mysql queries.

The problem which i have is that my export_function does not seem to terminate, it may be a timeout or a memory problem.

I have tested my function my limiting the number of users to around 1000 and it works fine.

I am wondering whether it is possible to export huge volume of data through hook_cron.

Why don't you do this in chunks.I mean schedule you cron using elysia_cron or ultimate cron at every hour or something and export chunks of users at a time,flag users you exported and at every next cron run get the new ones.

One important thing you should have crontab set on your server,do not use drupal's default poormanscron.


How can I programmatically recalculate an order total after changing the billing country I have various international tax rules in place, specifically for EU VAT at different rates. This is all working as expected.

On the checkout form, when you enter a non-EU address, like Australia, when you go to the next page in the checkout process, the UK VAT line has been totally removed from the order total, exactly as I would expect.

My client wants to update the order summary on the billing page by AJAX to avoid confusion. Australian customers still see the UK VAT rate before they submit their address.

I've got the AJAX update working fine, and can load the order, update the billing country, and save the order. When I then refresh the page the address remains as I changed it, but the order total still reflects the old country.

I have traced through the code to see how the submit handler deals with this and I can't see what I need to do.

Is there a way I can recalculate the order total in code, either in form_alter or the AJAX callback, so that the order object reflects the correct price for the billing country already set?

So, in short, if I change the billing address for an order, in code, how do I tell that order to recalculate it's totals?

I hope that makes sense and thanks for any help you can give.

This is what I'm trying, in hook_form_alter:

  if ($form_state['order'] &&
    !empty($form_state['input']['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['country'])) {

    $new_country = $form_state['input']['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['country'];
    $order = commerce_order_load($form_state['order']->order_number);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    if (!empty($order->commerce_customer_billing)) {
      if ($new_country !== $order_wrapper->commerce_customer_billing->commerce_customer_address->country->value()) {

        $order_wrapper->commerce_customer_billing->commerce_customer_address->country = $new_country;
        $order_wrapper->commerce_customer_billing->save();
        $order_wrapper->save();

        commerce_order_calculate_total($order);
        commerce_cart_order_refresh($order);
      }
    }
  }

Stepping through each call watching the commerce_order_total and the number of components never changes, no the VAT line never changes and the price never changes. When I press "Continue to next step" the VAT line changes (is either added or removed appropriately).

Very frustrating. I've looked at the submit call and tried to trace through it but can't find where the total is being changed. I'm guessing it's in rules somewhere. If it makes a difference we're using commerce_eu_vat

I've recently run into the exact same problem as you after changing the shipping address in an ajax call.

commerce_order_calculate_total() was the function that got everything working as expected for me.

You may or may not also need to use commerce_cart_order_refresh().

First try without but if you are still not seeing it updated then try both.

If possible run these functions directly before your actually sending the order total value to be rendered.


REST for nested paragraphs I need to create a rest service that delivers the current data:

getNode(nid)
-> all node fields
   -> if field is entity reference (like file, human readable urls)
       -> include subfields
   -> if field is type of paragraph, include sub fields again in human readable form

It seems that Drupal is not yet ready for Rest without having to create new requests for every peace of content that is referenced with an id.

For example I have a Pinterest wall kind of output. Each item is created by using a paragraph element (sometimes with other references like taxonomy etc)

I want a clean, json list. Structured correctly without missing nested elements like paragraphs, file or taxonomy references. In this moment I just get the id's of the referenced elements.

Do I have to call now 100+ requests to collect all data for this wall?

1) Or should I make one request for collecting the node:

2) Another request to collect all 1st level entity references. Afterwards to store them in an array.

3) Afterwards making request for 2nd level entity references.

This seems horrible to me when it comes to questions about overhead and time.

Of course I have checked out some modules that should help with this issue:

rest_export_nested module
which does not work with paragraphs entity types
rest_views
does seem to output the fields as html instead of json. There is no real solution so far.

So what to do? Another way could be to create a view of paragraphs with target id of [NODE_ID]. But this would work just for 1st level paragraphs. The problem would still exist for nested paragraphs.

Is really the only way to create a custom module that creates it's own rest service?

Is the JSON API maybe another solution I haven't looked at so far?

Any input is appreciated.
Thanks.

No. Core REST & REST Views aren't the right solution here. You don't need a custom module for this.

As you mentioned, JSON API module supports inclusion of entity references in a single resource request. Each entity requested has a property called relationships which are references to other entities that can be included with via the include parameter. References, within references (e.g. a node referencing a media entity, that references a file entity) are supported too, albeit with some work to follow references (e.g. when you a request inclusion via the include property you're given an array property, included, which you still have to sort through via id).

If you're looking for a Drupal API that follows entity references within returned entity objects, you should use the GraphQL module as it will allow you to define your own data spec that can expand entity references as you see fit.


How to convert location module data to geofield? I need to switch my mapping implementation from Gmap to OpenLayers. I have a site with 1000+ users that already have data stored with the location module, and user locations. Is there an easy way to transfer the address/location to geofield?

So, I haven't found a way to convert it, but I did do the following.

Update content with Addressfield and Geofield
Set geofield to code from addressfield
used views data export to export the data
used feeds to spit the data into addressfield.

This basically met my requirements, pretty laborious and had to do a lot of data integrity checking, but it did what I wanted it to do.

Just as a heads up, Addressfield is very specific with it's term, which are internationalized. The fields you have to map have different field names, and different requires fields for each country, so be cautious with the spelling and fulfilling all the required fields. You can use Feeds Tamper if it's all single-country data. Just for example here are a few:

Province = Administrative area
Street = Thoroughfare
City = Locality


Create taxonomy terms from content type field I'm looking to add a taxonomy term to a vocabulary upon the creation of content type.

For example I have a taxonomy vocabulary called "Widget Type".

I have a content type of Product. When I create an instance of product I would like the title (product.title_1) to be added as a taxonomy term to Widget Type.

Then every time a new product is created a term is added.
Widget Type would then contain the terms...
title_1
title_2...etc.

Does this require a custom module or is there an easier way to do this that I'm not aware of?

Thanks

You can trigger this behavior by implementing the hook_entity_presave on a custom module. Inside of this hook, you will call a function which creates each time the taxonomy term using the title of the node created. Here is my example:

File: test.module

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function test_entity_presave(EntityInterface $entity) {
   if ($entity->bundle() == 'product') {
    if ($entity->isNew()) {
      $title = $entity->get('title')->getValue();
      \Drupal\test\Test::createTerm($title[0]['value']);
    }
  }
}

Assuming you have defined the createTerm function into Class Test:

File Test.php(Include this file in src folder)

namespace Drupal\test;

/**
 * Test class.
 */
class Test {
  public static function createTerm($title) {
    $term = [
      'name'     => $title,
      'vid'      => 'widget_type',
      'langcode' => 'en',
    ];
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->create($term);
    $term->save();
  }
}


How to display a field collection as a responsive table? I'm using field collection and field collection table modules to show the data as a table, but I want that the table is be responsive.

How I do it? I don't found a good solution.

For example, for views table I use responsive_table_filter module that accomplishes this task.

Unfortunately there isn't a good solution for displaying tabular data in a responsive way. Even big organizations like Wikipedia, Google, and GitHub display tables as horizontally scrollable entities.

If you can think of a way to display tabular data legibly with variable width, be sure to publish it. :)


PHP setting of datetime field in CCK through Rules, How to stop continuous updates? Drupal 6. Using Rules and CCK

So, I have a content type that gets automatically generated with Rules. Several CCK fields get populated at creation time, including a datetime field. I want this field to get populated with the current date/time.

For some reason, the Global Token fields don't work, the interface throws an error when I try to use a token instead of a standard formatted date/time stamp.

So, I use advanced PHP code box to set the date/time value.

return array(
0 => array('value' => date("m/d/Y - H:i")),
);

This code works, but when I do it this way it seems that whenever I refresh the node page the date/time stamp in the field is updated to whatever the current time is. This is not the behavior I want. I want the date/time to get inserted at creation time, and have it remain unchanged for perpetuity.

Thoughts?

Thanks to Clive's help, I determined the problem was with the field type. There were several similar seeming Date/Time field types available to use, I was using one called "datetime". I switched to another one called "datestamp" and the datestamp field retained its original value after refreshing. I guess the "datetime" field is designed to always return the current datetime value of now(). Thanks for helping me work through this friend!


Dynamically adding fields to form I'm trying to create a form in which you can fill in user names. I want to dynamically add new textfields by pressing a button. I based my code on the following question (because it also uses Drupal 8 and supposedly should work).
However, unfortunately it doesn't add the fields. The code I'm using currently looks like this:
<?php
    /**
     * @file
     * Contains \Drupal\bulk_email\Form\EmailForm.
     */

    namespace Drupal\bulk_email\Form;
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Component\Utility\UrlHelper;

    class EmailForm extends FormBase {
        public function getFormId() {
            return "bulk_email_form";
        }

        public function buildForm(array $form, FormStateInterface $form_state) {
            $form['#tree'] = TRUE;

            $form['users'] = array(
              '#type' => 'fieldset',
              '#title' => t('Users'),
              '#prefix' => '
',
              '#suffix' => '
',
            );

            $num_users = $form_state->getValue('num_users');
            if (empty($num_users)) {
                $num_users = 1;
            }
            for ($i = 0; $i < $num_users; $i++) {
                $form['users'][$i] = array(
                    '#type'  => 'textfield',
                    '#description' => t('Select a user.'),
                );
            }

            $form['users']['users_more'] = array(
                '#type' => 'submit',
                '#value' => t('Add one'),
                '#submit' => array($this, 'bulk_email_addfieldsubmit'),
                '#ajax' => array(
                     'callback' => array($this, 'bulk_email_add_more_callback'),
                     'wrapper' => 'users-wrapper',
                ),
            );

            $form['actions'] = array('#type' => 'actions');
            $form['submit'] = array(
                '#type' => 'submit',
                '#value' => t('Send'),
            );
            return $form;
        }

        public function submitForm(array &$form, FormStateInterface $form_state) {
            // submit code
        }

        public function bulk_email_addfieldsubmit(array &$form, FormStateInterface $form_state) {
            $num_users = $form_state->get('num_users') + 1;
            $form_state->set('num_users', $num_users);
            $form_state->setRebuild(TRUE);
        }

        public function bulk_email_add_more_callback(array &$form, FormStateInterface $form_state) {
            return $form['users'];
        }
    }
?>

I'm most likely missing a small detail, but I can't seem to find it...
Any help is appreciated.

Did you check if the submit is called in your ajax request?

public function bulk_email_addfieldsubmit(array &$form, FormStateInterface $form_state) {
    $num_users = $form_state->get('num_users') + 1;
    $form_state->set('num_users', $num_users);

If not, you can put this code in buildForm(). In this case you need to check if the triggering element is the correct one.

And another small issue, this line in buildForm():

$num_users = $form_state->getValue('num_users');

Should be get('num_users'), because getValue() is for user input.


Recover content from "story" after content type was deleted accidentally in a very stupid action, I accidentally deleted the "Story" content type which had a lot of content. Just to be clear: I didn't delete the content, only the content type. When I realized what I was doing, I pressed esc, so I got a drupal message that very few content types were deleted. Still, much of the content is not in the back up. I am checking whether I can restore some of the lost content.

Apparently the titles of all stories appear normally. Unfortunately the body content is missing. I recreated the content type manually and still nothing.
But when I looked in the database, I noticed that sql tables node, field_data_body and field_revision_body actually contain the content from the nodes that were deleted.

Going further, I realized that the database entries of these sql tables have a column deleted which was set to 1 for the 'story' entries. I found an article which explains how deleted fields stay in the database and suggests to set the value of the column back to 0, if you want your deleted fields back. I did that, but still the stories display only the title and not the body.

I also looked at mysql table "node_type" and story is there. It looks exactly like page.

What can I do to convince drupal to display again the body of the stories, as it is still in these fields in the database?

I had this same situation - deleted nodes, only titles left.

With D7, I used phpmyadmin to go into the database

open the field_data_body table

Sort this by type and locate the type you deleted - there should be a "1" in the deleted column.  I did two as a test and then cleared caches and checked the node on the site - the content was back.

Then I ran this sql query, copied from the changes I did:
UPDATE  databasename.field_data_body SET  deleted =  '0' WHERE  field_data_body.entity_type =  'content type name' AND  field_data_body.deleted =1

Everything was back. Yay!

change database name to your database and content type name to the content type you deleted.

And be sure to backup your DB before doing this in case of disasters. Like deleting a node type.


How to keep  or  tags from getting in WYSIWYG editor with ckeditor? Seems simple, but I haven't been able to find any way to do it.

To be clear, I want ALL other tags for this text format, just not font or style tags.

Thanks.

Use a text filter (format) that allows all tags you want and doesn't allow font and style tags. I also recommend removing toolbar buttons that add these tags, such as font, font color, font size etc. You could add custom styles that add CSS selectors rather than inline style tags.


Where can I put helper functions for my theme? I wrote few helper functions and now I want to add these functions somewhere, so that I can call them from any template files.

Where should I put them?

Helper functions is a bit vague for a description (so there may be better places where to put this, like a custom module), but theme functions are usually put into the template.php file of your theme.

It is not generally adviced to put much php code into your templates however (save for printing variables) - best practice usually calls for the use of alter hooks or other preprocess functions. Get a (small) overview here: template.php


How to upload new versions of an image with the same access path? We have two sites, one is a static HTML site. Another is an Drupal site. For example:

www.my-html.com
www.my-drupal.com

On the my-html.com site, we have a dynamic image banner, links to a JPEG on the my-drupal.com site, which can be managed by the user using Drupal CMS, i.e.:

http://www.my-drupal.com/sites/default/files/my-html_banner.png

The users can upload new versions of the my-html_banner.png from time to time. Hopefully, when a new version of the image is uploaded on my-drupal.com, it will be refreshed on my-html.com.

However, the newer versions of the .png will end up with different filenames in sites/default/files, i.e.:

my-html_banner.png
my-html_banner_0.png
my-html_banner_1.png
...

Is there a way to use a fix path to refer to the latest version of a uploaded image? Or is it possible to config Drupal to replace existing image if the uploaded image name is identical?

You can try the Upload File Replace module, This module solves that problem by swapping the names of the older and newer file so that the newly uploaded file will retain its original name.

  This is a small utility module that automatically stops Drupal from
  renaming new files upload via filefield CCK. When 2 files with the
  same name exist, the older files will be renamed.


If I save created view and visit the view page it showing only filter field I am new to drupal and I am trying to create view for my content type, I followed the steps using a tutorial but I am not able to see the preview of the created content view if I save and visit the view page it showing only filter field. Please help me.

I have used the following method to create the view.

1) click on view and Add new name.

2) enter the name and in the show field selected the content then i specified my created content in type of field, and newest first in the sorted by field.

3) selected the table format.

4) added the fields of specified content with the help of search box where in i have given the content name so all related fields show up.

5) added the filter field from specified content.

I think you set  "age expose field  required" it cause in first load nothing show up till user enter something in filter.
try it with removing "Required" checkbox.


How can I have the language-specific 'enabled' Boolean of menu items being respected? I'm trying to translate the 'enabled' field of menu items in Drupal 8. So far I have written this code in MYMODULE.module file:

function MYMODULE_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'menu_link_content' && !empty($fields['enabled'])) {
    $fields['enabled']->setTranslatable(TRUE);
  }
  return $fields;
}

This works fine and I am able to set the enabled field differently for different languages. eg: for the same menu item, I can check the 'enabled' field for English, but uncheck the 'enabled' field for French.

But it does not work as expected. It hides the menu item for all languages. Should I use hook_preprocess() or hook_preprocess_menu() or some other hook for the menu item to show/hide based on 'enabled' field in different languages? Can someone give me some hints on this?

For what you are trying to achieve I found out you can use the Menu Manipulator module. This module initially aimed to fix [Issue] Untranslated menu items are displayed in menus.

  Notes

  This module initially aims to fix this core issue with unstranslated menu items.

Having this module installed only menu items that are available in the current language will be displayed. If there's a menu item you don't need in a certain language, remove it or remove its translation.

To make this work properly, ensure that your menu, the menu title and "Show language selector on create and edit pages" is enabled for your menu under https://example.com/admin/config/regional/content-language.

Having a menu item you want only to be shown on the French site, select French as its language, and don't translate it.
Having a menu item to be shown only on the English site, select English as its language, and don't translate it.
Having a menu item to be shown on both sites, add it in one language and simply translate it.


View output add a class to first and last rows I'm trying to output views and i'm using 960gs as well.

It possible to enable views processing so views knows if it this is the last one of the row and that way i can add a class "alpha" to the first view out put and "omega" to the 4th item and last item?

Update: Looking for primarly a php solution; not a jquery one; as it's not best practice to utilize javascript to manipulate layouts (IMHO).

The contributed Semantic Views module has the option of adding first and/or last class attributes. Pretty snazzy solution since you can also use it to specify better html elements at the same time!


When using rules to set an entity reference, do I use node or node:nid? I am using rules to create nodes.  Whenever a specific field on my target node-type is changed, a new new will be created and linked to the target node via entity reference field.  I would like to know, when setting an entity reference field using rules, should I use the data selector 'node' or the data selector 'node:nid'?

When setting an entity reference with rules, there is no need to specify the nid field. setting the value to the node itself will work.


How to bulk re-index the whole site for core search? I have a website that has about 100,000 nodes.
In the core search page (admin/config/search/settings) it shows that:

There are 80801 items left to index.

It index 100 (or at most 500) nodes per cron run but it's useless.
I want to bulk index the whole site (all nodes) for core search.
How can I do that?
The Reindex and Batch indexing modules are created for this but there are only a few users use these modules and I couldn't be sure to use them. And also there is a module called Elysia Cron for modifying the cron per job but it's still useless for me because there are thousands of nodes to index.
(Note: I want to do this for core search not for other search solutions).

You can use the following drush command.

drush search-reindex --immediate --verbose


How do you delete a content type's URL aliases in bulk? I have a content type where I want to delete all of its URL aliases in bulk. Currently the pathauto url alias page only has the option to delete all content url aliases regardless of what type it is.

How can you delete url aliases in bulk matching only a specific content type?

Also would it be okay to delete the url_aliases via phpmyadmin? I'm not sure if the url_aliases table is linked to something else.

I'd do it as an SQL query. Run as a SELECT first, to verify that all is well:

 SELECT alias FROM node n JOIN url_alias u ON CONCAT('node/', n.nid) =
 u.source WHERE n.type='my_type'

then edit it to make it a DELETE:

 DELETE u  FROM node n JOIN url_alias u ON CONCAT('node/', n.nid) =
 u.source WHERE n.type='my_type'


How to display a custom block in a view twig file? I added a custom block in the header of a view, and I am trying to get it to display. The block contains social media icons and links.
If I want to add a custom text area, I can use this code -
{{ view.header.area.options.content.value }}
In my kint I see this for the block I added -
      "header" => array:3 [▼
          "entity_block" => array:12 [▼
            "id" => "entity_block"
            "table" => "views"
            "field" => "entity_block"
            "relationship" => "none"
            "group_type" => "group"
            "admin_label" => ""
            "empty" => true
            "tokenize" => false
            "target" => "socialicons"
            "view_mode" => "default"
            "bypass_access" => false
            "plugin_id" => "entity"
          ]

So I tried to do  {{ view.header.entity_block }} but I get an error -
Exception: Object of type Drupal\views\Plugin\views\area\Entity cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 425 of core/lib/Drupal/Core/Template/TwigExtension.php).
What can I do to display the block?

You probably are confusing {{ header }} and {{ view.header }}.
The first prints the header section including the block:
views-view.html.twig
{{ header }}

The second one returns ViewExecutable::$header, an array of handler plugins you have configured in the View. You can try to extract configured string values like in the first example but in case of a block entity you probably only find the block id and you have to load and render the block yourself. It would be much easier though to print {{ header }}.


Get all databases name present in Postgres Server in Drupal 7 Form API I was currently developing a module and I want to display the names of all the databases present in my Postgres server through a query. I want also to query and list the names of schemas, tables, field and field type of each databases. How can I do that? I want to do this because I was making an interface about database connections and configuration. Is that possible?

One solution can be configurate the external database as a second database in settings.php.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'standard_db',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'postgres',
      'prefix' => '',
    ),
  ),
  'external' =>
  array (
    'default' =>
    array (
      'database' => 'external',
      'username' => 'username',
      'password' => 'password',
      'host' => 'db.external.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Then before you do your database queries you need to set the active database. In this example, to switch to external you need to execute db_set_active('external');

When you want to switch back to the default database you execute db_set_active();

Example code to switch to and query the external database:

db_set_active('external');
$result = db_query('SELECT something FROM {sometable}');
while ($row = db_fetch_array($result)) {
  drupal_set_message($row['something']);
}

db_set_active();

And here are the queries that I have used for a similar project.

Getting the Databases:

SELECT datname
FROM pg_database
WHERE datallowconn = true AND NOT datname = 'postgres' AND NOT datname = 'template1'
ORDER BY datname

Getting the Schemas:

SELECT schema_name
FROM information_schema.schemata
WHERE catalog_name = 'DATABASE_NAME' AND schema_name NOT LIKE 'pg_%' AND schema_name <> 'information_schema'
ORDER BY schema_name

Getting the Tables:

SELECT table_name
FROM information_schema.tables
WHERE table_catalog = 'DATABASE_NAME' AND table_schema NOT LIKE 'pg_%' AND table_schema <> 'information_schema' and table_type = 'BASE TABLE'

Getting Fields and Field types

SELECT ordinal_position, column_name,
CASE
WHEN character_maximum_length > 0 THEN concat(data_type, ' (',  character_maximum_length, ')')
ELSE data_type
END
AS data_type, is_nullable, column_default
FROM information_schema.columns
WHERE
table_schema = 'SCHEMA' and table_name = 'TABLE_NAME'

Reference

How to access the external database in drupal?
How to connect to multiple databases within Drupal


How to redirect custom ajax form to external url When setting the form with ajax handler like this

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

    $form['actions']['submit'] = array(
      //...
      '#ajax' => [
        'wrapper' => 'custom_form_wrapper',
        'callback' => '::ajaxCallback',
      ],
    );
  }

and trying to set the redirect on submitForm

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $url = 'https://example.com';
    $form_state->setResponse(new \Drupal\Core\Routing\TrustedRedirectResponse($url, 302));
  }

nothing happens and no error message appears but the form seems like it has finished processing.

When the ajax part is taken out the action:submit array the form redirects properly on submit.  What should be done differently ?

You can't return a redirect response, because the ajax script in the browser expects a json array with jquery commands, so you need to return a RedirectCommand from the ajax callback:

  public function ajaxCallback(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    $command = new RedirectCommand('https://example.com');

    return $response->addCommand($command);
  }

which then assigns window.location to redirect client-side.


theme('radios',$variables['element']) not working Trying to manipulate a form that can be a select / radios or text field based on the user configuration...

If the user wants to use radios for the form... then my module will render the  using standard drupal render system.

However when I use theme('radios',$variables['element']) it doesn't work at all... the output is:

However if I use: drupal_render_children($variables) it works perfectly...

Any clues on why theme('radios') behave differently as the rest of the form API items?

This is the code I'm using:

  $form['radio_test'] = array(
    '#type' => 'radios',
    '#title' => 'test',
    '#options' => array( 'a', 'b', 'c' ),
  );

  dpm(theme('radios',$form['radio_test']));

And this is the output

A radios form field uses a process function (form_process_radios()) which is the function that expand the form element, and add its child elements (the single radio elements a radios element is made of).
When you call theme(), that process function is not called, and those child elements are not added.

theme_radios($variables) executes the following code.

  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'] = 'form-radios';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';

As $element['#children'] is not set, what you get from theme('radios') is an empty <div> element with some CSS classes, and attributes.

Differently, when drupal_render() is called:

Any #pre_render, #process, #theme_wrappers, and #post_render function is called
Any child element is rendered


What is the best way to start from scratch? I have a drupal 7 instance at work, and one at home. I added content to both sites BEFORE installing the "menu breadcrumbs" module. On my Drupal instance at work the breadcrumbs don't work properly (they are skipping a level etc) while on my drupal instance at home, the same module works perfectly.

I've already tried uninstalling, and then reinstalling the module on my drupal instance at work, but didn't have luck getting it to work. Still skipping the breadcrumbs in between. What is the best way to fix this on my work instance? Should I delete all the content? If so, how? Is this likely to make any difference?

This question is difficult to answer. Check your Drupal versions first, 7.xx, etc, i.e., if you use 7.18 at your home, the same version should be used at your work.

If the versions are same and you still encounter the problem, I would do personally this by copying everything from my home instance to my work instance.

Copy the whole drupal site folder to my work PC.
Dump the database via phpMyAdmin (including DROP TABLE IF EXIST statements) and import it to my work PC. As a side note, I normally export cache tables with structure only in a separate dump file for the sake of smaller dump file.

That should be fine. This is the usual way I do for site cloning.


Possible to prepopulate an inline entity form multiple with a url parameter? Is is possible to add multiple entries into an inline entity form field with url parameters

I am able to populate almost any other field with the prepopulate module, just having difficulty with the IEF.

Scenario:

I have two content types of quote, and sales order. each of which has an entity reference of inventory (another content type) which has IEF as its widget.

I want to be able to create a sales order off of the quote, and bring over all the values of the entity reference field to the quote. The issue is i want to maintain the data on the quote, but be able to edit the "same" data on the sales order.

Please try with Entity reference autofill and Entityreference prepopulate Modules.

Add an entity reference field in your entityform.
The entity reference autofill will automatically fill reference value into field. We can load default value from URL. (?field_name = value)
Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

For more details please refer project page.

Another approach is,

  If you want to do this by coding, Just pass nid through url and use node_load() to load that node and create an entity form submission. If you want to create entity form with node creation use hook_node_insert or hook_node_presave.

Hope this will help you.


Create link to views page that preselects the filters of an entire vocabulary? I have a view that filters by different taxonomy terms, using multiple vocabularies. Im using the better exposed filter module.

I need different links to this view page which make different options pre-selected. By copying the url from when 1 term is selected I can easily make a link which works in this way:

my-site/resources?tid%5B%5D=22&keys=

I also need to make a link where all the terms from a vocabulary are selected. The client for this website will be able to add new terms to this vocabulary. If I simply copy the url with all the terms selected then this wont select a new term when its created.

How can I create a link to the view page which preselects all the terms from a vocbulary, that will still select all the terms when new ones are created?

Based on the URL provided:

function MODULE_NAME_build_taxonomy_views_link($taxonomy_tid) {
  $vocabulary = taxonomy_vocabulary_load($taxonomy_tid);
  if (!$vocabulary) {
    return;
  }
  $term_ids = array();
  foreach (taxonomy_get_tree($taxonomy_tid) as $term) {
    $term_ids['tid'][] = $term->tid;
  }

  return l($vocabulary->name, 'resources', array('query' => $term_ids));
}


How to visit a specific node using behat I am doing some work that requires customization of a breadcrumb for only one content type. I'm trying to write a behat test to verify it.

My Given is successfully creating the nodes, and I can verify that they are there if I tell behat to look at them in the admin content view:

Scenario:
  Given "partner_accomodation" content:
    |title            | body         | status|
    |Accomodation Foo | Test content | 1     |
  And I am logged in as a user with the "administrator" role
  When I go to "admin/content"
  Then I should see "Accomodation Foo"

What I can't figure out though is how to tell it visit that specific page. I would assume if I have pathauto configured correctly, that I should be able to go something like

When I go to "accomodation-foo"

Is there a way to know the node id or the URL alias of the content it created?

You can do two things in this scenario:

You can instruct it to click on "Accomodation Foo" (which should be the linked node title) on this page, to go to the node when the path is unknown.

If you have pathauto installed and configured, you can assume the path, so if it is [node:title], the path in this case is likely 'accomodation-foo'.

I use both in different cases, depending on the scenario. I keep the test node titles small and predictable so I know what the path (should) be. If the path isn't found, it is also a good way to test if Pathauto is creating the URLs you expect.

Here is an example one I wrote not too long ago:

Feature: Page Content Type (Anonymous)
  When I view the website
  As an anonymous user
  I should be able to view basic page content and its fields

  Background:
    Given "page" content:
      | title                     | status  | body             |  field_subtitle       |  field_summary            |
      | Published page            |       1 | PLACEHOLDER BODY |  This is the subtitle |  This is the page summary |
      | Unpublished page          |       0 | PLACEHOLDER BODY |  This is the subtitle |  This is the page summary |
    And I am on "published-page"

  Scenario: An anonymous user should be able access published basic page content
    Then I should not see "You are not authorized to access this page."

  Scenario: An anonymous user should be able to view the title
    Then I should see "Published page" in the summary region

  Scenario: An anonymous user should be able to view the subtitle
    Then I should see "This is the subtitle" in the summary region

  Scenario: An anonymous user should be able to view the page summary
    Then I should see "This is the page summary" in the summary region

  Scenario: An anonymous user should not be able access unpublished basic page content
    When I go to "unpublished-page"
    Then I should see "You are not authorized to access this page."


Using webform rules to create node after webform submission First of all, let me explain my project. I want users to place orders of products using webforms and then create a node with a link/reference to the submission and others custom fields.

It looks like this :

CONTENT TYPE PRODUCT :
- Field name / Field image / Field category / Field description

Webform is enabled for PRODUCT content type. So I've created products examples and each of these products have their own CUSTOM webform (all the forms are differents)

For example :

PRODUCT A (product content type)
- fields values + custom webform fields

So what I want this kind of node beeing created after webform submission :

CONTENT TYPE ORDER NODE :
- webform sid reference (linking to the submission results)
- Some fields which will be the same for every product

Do you think is possible with a custom module or should I find another way to achieve this ? (I suppose replacing webform by a content type, but the problem is webform, in my case, is very usefull)

I have to point out that I'm a beginner in Drupal module's developpment.

Thank you ;-)

You should use Rules module in the following way:

Install and enable Rules module
Install and enable Webform Rules (https://drupal.org/project/webform_rules)
Create a new rule
Choose the "After a webform has been submitted" event
Optionally set your conditions
Add a new action "Create a new entity" of type "Content"
Add the neededs action to add properties to the created entity
Add the save action

I hope this helps.


Showing form data in a block I have a multi step custom made form in Drupal 8.2.x.

Some of the user input from the form needs to be shown on a separate block.

The following code worked fine for users that are logged in:

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

But it doesn't work for anonymous users on my site.

Is there a tempstore for anonymous users that works site wide that I just haven't discovered yet?

you should use session manager for storing current sessions for anonymous users

private_tempstore gives us a temporary store that is private to the current user

refer to this link asked some days ago session storage for anonymous users


How to add frontend form using custom content type? I new to Drupal and I created a custom content type which has few fields, like donation name, value, size, etc.

I want to add these fields as a form for user which they can fill in the frontend. I want to know there are existing for this task or it can be done through core module

This is usually done by giving the user permission to add the content type and presenting them with the /node/add/{content_type} page, letting them create their own page content.


Send a mail from my custom module after custom form submit by user I have made a custom form from a custom module. I need to send an email to the admin when user clicks submit. How can I achieve this. Can I use entities here? Say like send mail to [site:mail] or something like that. Also, its pretty odd to see that Rules module does provide an event for this.

Here's my .module file:

<?php

global $user;

function my_module_help($path, $arg) {
  switch ($path) {
    case "admin/help#formtest":
      return '<p>' . t("Test form for accept challenge") . '</p>';
      break;
  }
}

function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => t('My form'),
    'page callback' => 'my_module_form',
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_form() {

 return drupal_get_form('my_module_my_form');

}

function my_module_my_form($form_state) {

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Accept Challenge',
    '#submit' => array('my_module_action'),
    );

  return $form;
}

function my_module_action($form, &$form_state) {
  drupal_set_message(t('Challenge Accepted'));
  $query = db_insert('challenges')
    ->fields(array(
    'cid' => '$node->nid',
    'uid' => '$user->uid'
    ))
    ->execute();
}

As you may have noticed there's no text field, well that is by purpose. So any suggestions would be really appreciated. One more thing, drupal_mail, or any other, say for example, mail chimp, notify etc would be of interest. What I need is just a mail to be send to admin after submit from the code itself.

Thanks

You surely can send an email on the submit.

See the code below.

function my_module_action($form, &$form_state) {
  drupal_set_message(t('Challenge Accepted'));
  $query = db_insert('challenges')
    ->fields(array(
    'cid' => '$node->nid',
    'uid' => '$user->uid'
    ))
    ->execute();
  $message = array('A new entry has been submitted');
  $to = 'example@example.com';
  $params = array(
    'body' => $body,
     'subject' => 'Website Information Request',
  );
  if (drupal_mail('my_module', 'some_mail_key', $to, language_default(), $params)) {
        drupal_set_message('Thanks, email sent.');
    } else {
        drupal_set_message('Email not sent.');
    }
}

You also need this function.

function my_module_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

in drupal_mail(), we pass $params array which contains parameters to build the email. If your module sends multiple emails, you can differentiate them using the $key variable.
But in this example, we simple assign message's variables from the direct $params variables.
Note that $message (in your submit handler) needs to be an array of text that you need to send.
For example,

$body = array();
$body[] = 'Hello,';
$body[] = 'There is a new submission...';

This is because when the email gets sent, body content will be imploded by a new line character. Each value in the $body array will appear in a new line.

Also, as a fine tuning, you won't need my_module_form function if you format your hook_menu function like this:

function my_module_menu() {
  $items = array();
  $items['my_module/form'] = array(
    'title' => 'My form', // We don't t() menu titles.
    'page callback' => 'drupal_get_form', // Directly call drupal_get_form...
    'page arguments' => array('my_module_my_form'), // ...with this argument.
    'access arguments' => array('access content'),
    'description' => t('My form'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}


Drupal Search function in custom module I created a drupal custom module for my website, the module functionality is it display list of students who have registered in my site. Now I want to update my custom module with search functionality, the search function should like google search function.

My custom module look like following structure

Now I want to implement the search function in my custom module. When I search using the fields of the table like student name, gender, author name, and status, how do I do this?

You have few options:

Use hook_views_data() to hook your custom tables with Views.
Use Data module as it features automatic integration with Views.
Reorder your setup to use Drupal's node type/user profile/entity, which has Views support out of the box.

Doing it really manually will be a waste of time, unless you need some very specific functionality that can be hardly achieved by using Views for it.

Views will also provide you with caching, paging and it will be easier to maintain it in the future.


Why is Drupal CSS/JS Aggregation files stored in sites/default/files? The storing of the CSS aggregation files became problematic for me as our Central Safety Services (CSS) department also tried to store files in the sites/default/files/css folder and everything got wiped out.

Why doesn't it use a root folder, like [drupal root]/tmp or /cache or something other than where I store my files?

Because the file is served and needs to be accessible via the web server. sites/default/files is typically the default location for uploaded content, or content that is generated dynamically, which these CSS/JS files are.

Your situation happens to be because css (Central Safety Services) happens to be the same directory that Drupal uses to store these files. The recommended solution is to update the path name in the database for their files to something else.

Drupal has the ability to configure the directory where the files are stored, under File System in the admin, but ultimately it has to store them somewhere below Drupal root directory.

Drupal 6: http://drupalsitename/admin/settings/file-system
Drupal 7: http://drupalsitename/admin/config/media/file-system


Importing existing users into a new Drupal site We have an existing Drupal site that has a requirement to inherit about 10k users into, and we've been able to gather most of this data through CSV exports on the Database, and Views Export/VBO. What we have is two CSVs, one with usernames, password hashes, UIDs; the other with user field data and a UID to join/union the data during import. There are differences between the Field structure between the site data we inherited and the new site, so new data relationships will need to be established during the import, ruling out a direct port of the existing Database records.

I have no issues writing a Drush script that will import all the users with a joined CSV. What I am wondering is if its possible to import the user records, complete with the password strings within the Drupal User space. Looking at the user_save() method its not clear as if I can define the User ID, or password hash. And we have a lot of logic implemented that depends upon this

So the approach I have in my head is this:

Use SQL IN FILE to import the baseline minimum data to establish users in Drupal's users table: Username, Password Hash, created date, changed date, etc...
Use a second drush script to iterate through the field data, and update the user records with user_save() off UID.

Is there another approach I can use that's strictly Drush based? This assumes that the data I import will be with a Unioned CSV file. Not being able to adjust the UID probably means this isn't possible, but its worth asking.

It sounds like you're after the Feeds module! It supports mapping fields sources to destinations, and will auto-create entities in some cases.

After installing & enabling the module, you'll want to create a Feeds Importer (under Structure) and go from there. Navigate to /import to upload a CSV file to a feeds importer for processing.

There's a sandbox module Drush Feeds Import that should allow you to run some of this from the command line if necessary.

Check out:

  The site builder's guide to Feeds:

  https://www.drupal.org/node/622698

If the stock Feeds modules don't quite solve your problem, you could use the Feeds API to define your own processing class that manipulates and inserts the data into the new site.


Find and display most recent referencing entities I have 2 different node types. The first one describes a factory and the second one describes a measurement of the water inside the factory. The measurement content type has an Entity Reference field that points to the factory that the measurement is associated with.

What I want to do is print a list of all the factories in a table format and a specific column that will contain a field from the latest measurement that references to the specific factory.

For example:

Factory 1

field 1
field 2
field 3

Factory 2

field 1
field 2
field 3

Measurement 1

Refers to Factory 1
Integer Field
Date Created: 21/5/2013

Measurement 2

Refers to Factory 1
Integer Field
Date Created: 22/5/2013

Measurement 3

Refers to Factory 2
Integer Field
Date Created: 10/2/2012

Measurement 4

Refers to Factory 1
Integer Field
Date Created: 23/5/2013

What I want to print:
    Factory 1 || field 1 || field 2 || field 3 || Integer Field (from Measurement 4)
    Factory 2 || field 1 || field 2 || field 3 || Integer Field (from Measurement 3)

Notice that I'm only printing the Integer field from Measurement 4 since it is the latest measurement for the specific factory. I started writing some custom code and looked into EntityFieldQuery but I can't understand how to use it in conjunction with Entity Reference.

I've made an assumption about the way you want the table to be formatted, but something like the following should get you most of the way there:

// Set up the table.
$header = array('Factory Name', 'Field Value');
$rows = array();

// Get some nids for the factories you're interested in. Your real query will probably be more specific (checking status etc).
$args = array(':type' => 'factory');
$factory_nids = db_query('SELECT nid FROM {node} WHERE type = :type', $args)->fetchCol();

// Load the factory nodes.
$factory_nodes = node_load_multiple($factory_nids);

foreach ($factory_nodes as $factory_node) {
  // Add the factory name to the first column of this row.
  $row = array($factory_node->title);

  // Get the latest measurement related to this factory with an EntityFieldQuery.
  // fieldCondition() and fieldOrderBy()/propertyOrderBy() are the important bits here.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'measurement')
    ->propertyCondition('status', 1)
    // This is the entity reference condition; entity ref fields use 'target_id' as the field column name.
    ->fieldCondition('field_factory_reference', 'target_id', $factory_node->nid)
    // If the date you're interested in is in a field, use something like this...
    ->fieldOrderBy('field_measurement_date', 'value', 'DESC')
    // ...or if you're interested in the node created date, this
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 1);

  $results = $query->execute();

  // Make sure there are some results.
  if (!empty($results['node'])) {
    // EntityFieldQuerys always return an array of nids even if there's only one result,
    // so it's easier to run through node_load_multiple and shift the element later
    $measurement_nodes = node_load_multiple(array_keys($results['node']));

    // Get the node
    $latest_measurement_node = array_shift($measurement_nodes);

    if ($field_items = field_get_items('node', $latest_measurement_node, 'field_some_field')) {
      // If we have an appropriate value, add it to the row.
      $row[] = $field_items[0]['value'];
    }
    else {
      $row[] = 'No data found';
    }
  }
  else {
    $row[] = 'No data found';
  }

  $rows[] = $row;
}

$rendered_table = theme('table', array('header' => $header, 'rows' => $rows));


Rebuilding content access permissions I have a site with 760123 nodes, and 20123 users.

When visiting any page, I get the warning, "Rebuilding content access permissions." I tried rebuilding the access permissions, but the process is very slow.
I see this post, and tried the proposed solution, but it is not working.

I'm using  Drupal 6.

Maybe you're hitting your server's max_execution_time. It's quite likely with such a big number of nodes, and this operation taking a long time is normal.


How do I export fields of a content type in one website and import it into another website? I'm trying to set up a data export through views that includes the title and a couple of fields of a content type and import it into another website. I'm using Feeds and Views Data Export and also tried Views XML but is doesn't seem to work.

How do I export fields and import them by creating nodes in another website?

Create a rss feed of your view or using Views Bonus Pack create a csv of your data.
Create the Content Type that will be the container for your new content. Or alternatively export the content type using the "Content Copy" module shipped with cck and then import it on the new site.
Using Feeds Create a node importer to import your nodes. Details in the video linked.


PHPUnit with custom/contrib and submodules structure I am starting to write our tests with PHPUnit on Drupal 8, and I am not sure about the best practices with the phpunit.xml.dist file.
We separates the custom and the contrib modules using two directories in the /modules directory - /modules/custom and modules/contrib.
The original phpunit.xml.dist file contains the following line <directory>../modules/*/tests/src/Unit</directory> so I had to add the
<directory>../modules/*/*/tests/src/Unit</directory> directory.

I have another issue with sub-modules, our current structure is /modules/custom/main_custom_module/modules/sub_module, so I had to add another directory to the file (<directory>../modules/*/*/modules/*/tests/src/Unit</directory>).

What is the best practice when it comes to overriding the phpunit.xml.dist file? should I remove the file from VC (e.g. git,svn..)?

The right thing to do is to not add it to the core phpunit.xml.dist file. You have your own code, so you want to test that. The idea that core also tests contrib / custom code is not the right thing to do, IMHO


Simplesamlphp behind reverse proxy I have configured my application and simplesamlphp behind reverse proxy. I have created a test SP But when I am going to test the SP, it redirects to https://web-server-ip/adfs/ls/?SAMLRequest=nZL instead of redirecting to ADFS server url https://adfs.server.com/adfs/ls/?SAMLRequest=nZL

I have changed the baseurlpath in config.php to "https://web-server-ip/simplesaml/". But still same error.

SP is working with App server. If I am trying to test the SP using https://app-server-ip/simplesaml, it redirects to ADFS server login.

But no luck via web server.

Please suggest any solution.

In my case it was the the problem of reverse proxy. It is fixed now.


How can I override the node edit in Drupal 6? I'm trying to override the "node edit"(using a "page-node-CONTENT-TYPE-edit.tpl.php") in drupal 6, and I'm stuck with the fact that I can't choose which field I want to publish in a specific edit page. I have to publish the whole $content or nothing !
I tried with drupal_render, $form etc... but nothing.

Does anyone have some clues on how I would be able to display the fields I want so I could design my edit page by content type?

I finally got it! It is quite simple; in fact, I just had to make a hook form filter, some "if" on user_access(), and rock and roll!

I am not exactly sure what you are asking here, but if you are trying to change the layout of the node edit form, you might check out the http://drupal.org/project/nodeformcols module that allows you to change the node edit/create form with a pretty straightforward drag and drop interface within CCK.


How to Wrap the text in Source View of CKeditor I am using CKeditor version 7.x-1.16 with Drupal 7.34.
How can I force the text to wrap in source view of the editor. I don't want the horizontal scroll bar to appear.

I managed to do that in WYSIWYG view.
Pressing the 'Enter key' in 'source view' will not solve it, since it gets overruled at the next switch between views.

See the images for differences. This is the same text as it appears when I switch between 'Source view' and 'WYSIWYG view'

This seems to be a Firefox problem, since in Google Chrome browser it is not an issue.

I found the solution to this:
This is a Firefox browser issue only (FF version >= 36). This behavior is not affected in other major browsers (Safari, IE and Chrome).
Here is the fix. Add the following code to you theme's CSS file:

.cke_source {
    white-space: pre-wrap !important;
}

Basically, you are overwriting the 'white-space' property of the "cke_source" selector in the "editor_gecko.css" file  of the CKEditor module. This file is located at: \sites\all\libraries\ckeditor\skins\moono\editor_gecko.css

References:

https://stackoverflow.com/questions/29038262/source-code-not-wrapping-in-ckeditor-on-firefox

https://www.drupal.org/node/1489340

http://dev.ckeditor.com/ticket/13031


Add the user role to the body class How do you add the class of the user role to the body tag, say in html.html.twig, in much the same way as you can add the path in How can I dynamically add URL or taxonomy to body class?

Here's how you could achieve that:

function YOUR_THEME_preprocess_html(&$variables) {
  // The getRoles() method will return us the machine names, so there is no
  // need to process roles names additionally. However, I suggest prefixing
  // the names with "role-", so it's more obvious.
  foreach ($variables['user']->getRoles() as $role) {
    $variables['attributes']['class'][] = 'role-' . $role;
  }
}

Then in your html.html.twig file you can set the attributes this way:

<body{{ attributes }}>

Note: you might want to pass TRUE to the getRoles() method, if you want to exclude the locked roles (anonymous and authenticated). You can read the docs on this method here.


Better tagging / taxonomy reference widget The Term Reference field type has three stock widget types:

Select List
Check boxes/radio buttons
Autocomplete term widget (tagging)

We need an alternative to the autocomplete widget that shows all existing terms in a vocabulary and allows users to enter another.

Here is a sample of what I'm looking for (I just made this in Firebug—I don't have a viable option yet). In this option, the vocabulary would include two terms, banana and pear, and the user could enter a different term.

Select (or other) module looks like provide similar UI.

  Provides a new Forms API element which is a select/radios/checkboxes
  element that has an 'other' option. When 'other' is selected a
  textfield appears for the user to provide a custom value.

Unfortunately it doesn't support Term References.

Try Autocomplete Deluxe module or Chosen module for better UI and functionality.


Apachesolr searching is not working with cck field I am working in Drupal 6 website with apachesolr. I have added a cck field (text field) in a content type.

When I am searching the value of textfield, apachesolr showing empty result.

The field is indexed properly into apachesolr index.

How can I implement apachesolr searching for cck text field?

Once you add a CCK field then the CCK will not by default get indexed. You have to delete all the existing index and have to re-index all items. This is because, CCK fields are properties of all the documents (nodes) that goes to the SOLR index.

Once all the items are index then you can find those by sis_cck_field_* names where sis_* is a type of dynamic field provided by SOLR itself. You can find the CCK index status in admin/reports/apachesolr/index page or in SOLR admin (http://127.0.0.1:8983/solr/admin/schema.jsp) page.

EDIT -- 1
As mentioned, the field is indexed properly then try to search by the value of the CCK field in Apache Solr's admin search (http://localhost:8983/solr/admin/form.jsp). If you see the search results appear as per your desire then there may be a permission issue. If your field is called "field_example" then in permission page check whether "view field_example" is checked for desired roles.

Edit -- 2
In that case I think the cck field is not at all being indexed. I had the same problem once with CCk fields that stores "multiple" values. In that case what I had to do is to create a new field in SOLR index and index the item again. This may solve your problem but may not be a proper way. However you will find this way is excepted in Drupal also in this link.

You have 2 ways to achieve this.

Append the item in the body field in time of content indexing hook.
Add a new dynamic field to the document object while indexing and fetch the field while searching.

For the 1st one,

function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  $document->body .= ' '. $node->field_MY_CCK_FIELD[0]['view'];
}

For the 2nd one,

function MYMODULE_apachesolr_update_index(&$document, $node, $namespace) {
  // For multiple values.
  foreach ($array as $value) {
    $document->setMultiValue('sm_multiple_value', $value);
  }
  // For text field.
  $document->addField('ts_element_name', $value);
}

And while searching,

function MYMODULE_apachesolr_modify_query(&$query, &$params, $caller) {
  $params['fl'] .= ',ts_element_name'; //Add the field name to the select query.
}


Views Slideshow - Bullets or Numbered Pager not displaying I have used Views Slideshow to generate a page slideshow. The rotation / cycle is working fine but I need to display a bulleted pager. Since I am not able to display any kind of pager, I started with trying to show a numbered pager first which is not working for me.

I have basically used this guide to setup numbered pagers.

However, I do not see the numbers after doing the same.

I have enabled the page controls and current page index for testing purpose. Below is what I get using Devel Themer module and the developer tools.

I just increased the height of the area which is supposed to display the pager so that I can click that area to show the themer information. I cannot see anything rendered in the div responsible for displaying the pager. Also, as I see in the template which is rendering the code for pager is simple.

From the file "views-slideshow-pager-fields.tpl.php" the code is the following.

<div id="<?php print $widget_id; ?>" class="<?php print $classes; ?>">
  <?php print $rendered_field_items; ?>
</div>

I do not understand why the pagers are not getting displayed. Where should I start looking for the fix?

You can achieve pager using View Slideshow by following steps:

Step 1: In view, add Global: View result counter field and mark it as Exclude from display.

Step 2: Now click on Slideshow format settings, go to Pager part and select Global: View result counter field as a Pager Type.

Step 3: To give perfect bullets effect, you will have add some CSS as given below

.views-field-counter {
    float: left;
    margin-left: 5px;
}

.views-content-counter {
    text-align: center;
    width: 29px;
    background: url(../bullets.png) no-repeat scroll center center transparent;
    cursor: pointer;
}

Step 4: Please check out CSS Classes, ID's and HTML markups form below screenshot, which worked at my end.


Using PHP ImageMagick with ImageCache Custom actions - Returning image I'm trying to composite some images using ImageMagick - I know imagemagick via PHP, i'm trying to return the image via PHP but it seems to overwrite the original source file - not ideal as it can apply the filter over and over.

Ideally, I'd like to write the original file with _thumb after it, then call this file via Drupal for display, where it would copy to the appropriate imagecache directory and display from there. Anyone with ImageMagick experience, would be appreciated if you can help.

$location = $image->source;

$newImage = new Imagick($_SERVER['DOCUMENT_ROOT'].'/'.$image->source);

$distort = array( 0.0, 0.0, 0.16, 1.0  );
$newImage->distortImage( Imagick::DISTORTION_BARREL, $distort, TRUE );
$newImage->resizeImage(1600, 1600, Imagick::FILTER_CATROM, 1);
$newImage->cropImage(1500, 1500,60, 50);

$extension_pos = strrpos($fileName, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($fileName, 0, $extension_pos) . '_thumb' . substr($fileName, $extension_pos);
$newImage->writeImage($thumb);

return $thumb;

Someone might find this useful as Documentation is very sparse for this (this took me over a day to figure out). The problem was I was writing to a seperate file - Works, but ImageCache will delete it, also defeats the point of using ImageCache.

The solution is as follows, to use $image->ops[] and ImageMagick CMD's. (This is entered in the custom actions of imagecache. Distort image, apply mask, and apply overlay. This is used for creating product images for a Shop with just normal images supplied. I'll probably make a blog post in more depth at some point.

$image->ops[] = "-distort Barrel '0.0 0.0 0.16 1.0'";
$image->ops[] = "-resize 1600x1600";
$image->ops[] = "-crop 1500x1500+60+50";
$image->ops[] = "'sites/default/files/coushin-bg.png' -compose Dst_In  -gravity center -alpha Set -composite -format png -quality 90 ";
$image->ops[] = "'sites/default/files/Blank-Cushion.png' -compose Multiply  -composite -format png -quality 90 ";
return $image;


Multi-value checkbox within content type I simply want to make a multivalue field within my venue content type (music venue)

funky, cool, dive, swank, disco etc.

I want to be able to select those when adding a venue, and then have it display everyone that was checked. I cannot figure this out!

Add a new field choose FIELD as 'List (text)' and Widget as 'Check boxes/radio buttons'
Then in allowed values list, give your values
eg:
funky|funky
cool|cool
dive|dive
swank|swank
disco|disco
Choose Number of values to "Unlimited"
Then in DEFAULT VALUE, you can see all the options as check boxes, check every boxes if you want display all as selected.

Now you will get the desired output


Custom Checkout page I have made a form_alter in template.php in my theme and I have created a custom page (page--checkout.tpl.php) to render my form.
If I render the content as print render($page['content']); everything is fine,
but I want to print the cart content on the top of the page, and the customer_profile_billing and commerce_payment below the cart contents in two seaprate columns. How can i call for these seperate panes in the page--checkout.tpl.php in order to show them the way I need?

I've searched everywhere but it seems that I cannot find something that works for my needs.

Thank you in advance everybody.

Well it might seem a little noobish mistake but nevertheless, for everyone that is interested out there.

After a lot of research I found out how to make it.

The problem that arises when you try to render a form in a .tpl file is the functionality of the form.

I was trying to render $page['content']
and I couldn't do the above.

So I had to add to MYTHEME\template.php these lines:

function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'commerce_checkout_form_checkout' => array(
      'render element' => 'form',
      'template' => 'commerce-checkout-form-checkout',
      'path' => drupal_get_path('theme', 'MYTHEME') . '/template/forms',
    ),
  );
}

and then I created: commerce-checkout-form-checkout.tpl.php in
MYTHEME/template/forms

and I just put this code inside:

<?php print render($form['cart_contents']); ?>

<?php print render($form['customer_profile_billing']); ?>

<?php print render($form['commerce_payment']); ?>

<?php print drupal_render_children($form); ?>

The key to render the form right was the last line:

<?php print drupal_render_children($form); ?>

which rendered all the missing funcionality (like ajax and submit buttons) from the form.

I hope this will help someone in the future to avoid all the time and hassle..


User must click Back button twice after adding item in cart I have added Drupal Commerce in an existing D7 site and I use the existing product nodes, in which I have added the Add to cart form. Everything looks nice and works fine, except for one thing. When a user adds an item into the cart and then tries to go back one step by clicking the browser back button, he or she stays on the same page. So the user must click twice to go back one step. The history information about previuos pages, must still be there since one lands on the correct page, after clicking twice.

Maybe I should mention that I use Authcache with Ajax calls to fetch the Cart block on cached pages, but i think this behaviour started before I installed Authcache.

How can I fix this?

While, not an specific answer. Just to point out another possibly cause, this could be caused by JS.

https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries

Basically, there are ways of modifying the history via JS. There might be some code somewhere that's introducing this. Not sure which module though.

Assuming JS, what you probably should look into is calls to,

 history.pushState()
 history.replaceState()


alter Suggestion box for apache solr autosearch I want to restrict the suggestions for Apache Solr Search with hook_apachesolr_suggestions_alter(&$suggestions, $env_id). I have gone through the code and found the suggestion is prompt from apachesolr_autocomplete_suggest_word_completion()
called by a menu callback.

How can I override the suggestion block? I do not want to block indexing the words but just to hide them from suggestions.

Is there any hook available? Is hook_apachesolr_suggesstions_alter(&$suggestions,$env_id) useful in this case?

I am using hook_apachesolr_querry_alter(DrupalSolrQueryInterface $query);
I want to skip the parameters from the query. Is there any way to do  this?

I was not able to find any hooks for the same. The alternate solution which I got is to implement hook_menu alter.

As apachesolr uses hook_menu() I altered the menu callback function.


Translate text on the front page with t() Have a multilingual site with English and French, I have all my static text on my page--front.tpl.php wrapped with a t(), cleaned my cache and refreshed the strings, but still i cant find the strings to translate them.
I'm I doing something wrong here?
example of code on page--front.tpl.php

<?php print t('Create New content'); ?>

<?php print t('OR'); ?>

<?php print t('check our content'); ?>

You need to activate the locale module.

Under "Admin >> Configuration" you find a section regional and language.
Add a new language, and set it as default language; after that, you can use the 'translate interface' to translate the strings wrapped in t() for your new language.