How to create and view a clickable list of information on a user profile? I am basically trying to replicate the attachment in Drupal. Ideally the user will click a user and have a Financial tab which they can add invoices/notes to. This would need to be a collection of fields (field collection?).

Seems like you're looking for something like what I'd call some type of "drill down" facilities. Have a look at the Master Summary with drill down example. Click on some of the links in the tabular report (or bars in the chart ...), to get some related report (for the link you followed). Think of "states" as the equivalent of your "invoices" to get the idea.

The above sample is created with the Forena module. After you install it in your own environment, you'll have access to another set (category) of reports, related to "Drupal Administration" (applied to your own site). One of the reports in it is the "Logs for User" report (located at /reports/drupaladmin.user_logs). It'll show you a summary of watchdog entries (for the user you selected). And the resulting report includes a link "Details" for any of the watchdog records shown, which you cann use (follow) to get way more details about the specific watchdog record. The format of such "detail" is shown in a format that is pretty close to your "Invoice details" screenprint.

Here is a screenprint of another (custom) report that also includes such drill-down facilities (don't look at the actual formatting of it):

The (red) numbers in it are actually hyperlinks which you can use to get the actual Watchdog details (corresponding to the link you selected). The (collapsed) "Report Execution Parameters" can be expanded to "filter" the data to be included in the report. Even though it's a custom report, it is pretty forward to build such kind of reports, e.g. using Forena's WYSIWYG report writer and/or WYSIWYG query builder.

The above is about displaying (reporting) all such data. To also be able to "add" new records (invoices), you could expand the so called "frx" files (which is just plain XHTML), to insert something like an hyperlink to "add a new invoice". Such link would then probably correspond to something like node/add/invoice (assuming the machine name of your content type is invoice). Optionally you could also use a destination parameter in such URL to return to the "report" after the new node (invoice) was added.

Disclosure: I'm a co-maintainer of Forena.


accessing fields in a view template I have a view that I want to create a view template for in my theme.

So, I have created: views-view--homepage-suppliers.tpl.php

I have then several content items of content type: Supplier that the view uses.

The have various fileds, such as title, field_supplier_image

How do i then access these fields in this view template?

Is it something along the lines of:

$rows['field_supplier_image']?

thanks

It would appear your using a 'Display output' template when you probably want a 'Row style' output so you can access fields. You will need to change your tempate by going to 'advanced > theme information', it will probably be something similar to 'views-view-fields--homepage-suppliers.tpl.php'.

You can then get a nid from the field and access a whole host of information through the node object.

  $nid = $row->{$view->field['field_supplier_image']->field_alias};
  $node = node_load($nid);

If you var_dump() the $node variable you can see what you have to play with.


Add a JavaScript file without ?hash Is it possible?

I am trying to include a JavaScript plugin that works incorrectly when path is /script.js?hAsh.

I found a solution using the following code.

global $base_url;
$path = 'sites/xxx/';
drupal_add_js($base_url . '/' . $path . 'script.js', 'external');


Filtering Taxonomy term descriptions in Views I've created a Taxonomy Vocabulary with the name "Remarque prix". I imported it as a Term reference field to Commerce Product with the aim to be able to give a unique Vocabulary term to each product (SKU).

I want to present the Vocabulary term description in the the node by using Views so I created a View showing the Term description and took it into the node as a dynamic field, but I can't figure out how to set Contextual filters and maybe Relationships within views so each SKU/Product will have the correct Vocabulary term.

I have spent over a full day on this but can't figure out how to do. Could maybe anyone help me, please?

All the Best

Hans

Create a block view of Taxonomy terms from your desired vocabulary.
Add a Contextual Filter (Taxonomy term: Term ID)
Check "Provide Default Value"
Select "Taxonomy term ID from URL" from the dropdown.
Check "Load default filter from node page, that's good for related taxonomy blocks"
Check "Limit terms by vocabulary"
Select your vocabulary ("Remarque prix" if I understood your question properly).
Add the Taxonomy Term name and description fields.

Now you simply add the block to your product pages (easiest is just using Drupal's blocks, but you may have a different way you want to handle this.

Appendix

It doesn't matter if your taxonomy term ID is visible in the URL or not, Drupal understands and will acquire it.

Note: If I understand you context accurately, it seems as if your content type for Product has a 1:1 ratio with your SKU vocabulary. At this point, I would consider whether it's actually necessary to have that vocabulary. Generally vocabularies are best used to group content similar in some ways (i.e. the same taxonomy term is used in multiple places). It might be better to make this a text field on the content type rather than a separate vocabulary. But I also don't know your exact situation, you may have good reason for doing it that way. Just some food for though.


Multiple sites routed to one codebase has the subdirectory name as prefix on the links I am trying to redirect multiple drupal sites to same code base using following htaccess file

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?site.com$ [NC]
RewriteCond %{REQUEST_URI} !^/subdirectory/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ subdirectory/$1
RewriteCond %{HTTP_HOST} ^(www.)?ngeneric.com$ [NC]
RewriteRule ^(/)?$ subdirectory/index.php [L]

It workds but, now every URL on the site has its subdirectory infront like

  http://site.com/subdirectory/.....

How to fix this?

More Info: Domain is routed to public_html/a/ The drupal site in inside this a directory as public_html/a/b and I am trying to use multiple sites, so I am getting this problem.

Try to set the $baseurl variable in settings.php, at Drupal site directory. Read the documentation around this variable in the settings file.


How do I programmatically empty a cart? I want to empty the cart before a product in the code. I tried

$this->cartProvider->emptyCart($cart);

But this did not work and gave an error. I am doing this in Drupal 8. I am adding products in the controller code.

This is how I am fetching the cart.

$destination = \Drupal::service('path.current')->getPath();
   $productObj = Product::load($productId);

   $product_variation_id = $productObj->get('variations')
     ->getValue()[0]['target_id'];
   $storeId = $productObj->get('stores')->getValue()[0]['target_id'];
   $variationobj = \Drupal::entityTypeManager()
     ->getStorage('commerce_product_variation')
     ->load($product_variation_id);
   $store = \Drupal::entityTypeManager()
     ->getStorage('commerce_store')
     ->load($storeId);

     $cart = $this->cartProvider->getCart('default', $store);

     $this->cartManager->emptyCart($cart);

   if (!$cart) {
    $cart = $this->cartProvider->createCart('default', $store);

   }

   $line_item_type_storage = \Drupal::entityTypeManager()
     ->getStorage('commerce_order_item_type');
// Process to place order programatically.
   $cart_manager = \Drupal::service('commerce_cart.cart_manager');
   $line_item = $cart_manager->addEntity($cart, $variationobj);

    $response = new RedirectResponse(Url::fromRoute('commerce_cart.page')->toString());
    return $response;

You must use the commerce_cart.cart_manager service instead.

So $this->cartManager->emptyCart($cart); should do the trick.

Update: The reason why you get an error is because you try to call emptyCart on $cart then it's NULL.

You must wrap the line where you empty the cart in an if statement, like this:

if (!empty($cart)) {
  $this->cartManager->emptyCart($cart);
}


How to embed private videos hosted on Amazon S3/Cloudfront using JW Player module? Have anyone tried using the signed url option provided by the new version of Amazon cloudfront with the JW Player module?
I´m using Drupal 7.

I´ve read that the idea of the signed url option is to generate the signed url at page load time with a short expiry. This way each user who loads the page gets a unique short lived URL they can access, if they share it, it will eventually expire limiting your exposure to hot-linking.

How may I add a dynamic expiring link? I know that this has more to do with how Amazon works than how JW Player works, but maybe someone can help me out because have made it through, or maybe have found a good n00b tutorial (I haven´t found any that explains how to use their services and this video player at once that I could actually understand).

Thanks in advance for any insight!
Rosamunda

Use this php function to get signed url

function getSignedURL($resource, $timeout)
{
//This comes from key pair you generated for cloudfront
$keyPairId = "YOUR_CLOUDFRONT_KEY_PAIR_ID";

$expires = time() + $timeout; //Time out in seconds
$json = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';

//Read Cloudfront Private Key Pair
$fp=fopen("private_key.pem","r");
$priv_key=fread($fp,8192);
fclose($fp);

//Create the private key
$key = openssl_get_privatekey($priv_key);
if(!$key)
{
    echo "
Failed to load private key!
";
    return;
}

//Sign the policy with the private key
if(!openssl_sign($json, $signed_policy, $key, OPENSSL_ALGO_SHA1))
{
    echo '
Failed to sign policy: '.openssl_error_string().'
';
    return;
}

//Create url safe signed policy
$base64_signed_policy = base64_encode($signed_policy);
$signature = str_replace(array('+','=','/'), array('-','_','~'), $base64_signed_policy);

//Construct the URL
$url = $resource.'?Expires='.$expires.'&Signature='.$signature.'&Key-Pair-Id='.$keyPairId;

return $url;
    }


Programmatically redirect users to the default "access restricted" I would like to programmatically redirect my users to the default "access restricted" page. I know that I need a "RedirectResponse" object for a simple redirect, but how do I specify the default "access restricted" page here?

You can throw an exception at any point in your code:

403:

throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

404:

throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();

The exception is then catched by DefaultExceptionHtmlSubscriber and a subrequest for /system/403 or /system/404 is returned, which you can configure in the basic site settings if you don't want to display a generic "access denied" or "not found" page.

Other options depend on where the code is placed:

Return a 403 or 404 response from a controller or a form
Set a response in an event if you are in an event subscriber.

What you should never do is to send a response directly. This doesn't stop the code and produces two responses, one you've sent and one returned by the Drupal kernel. This will result in unpredictable behavior.


Why is my image with URL that links to external site in a custom block not showing? I made a custom block in header that houses the following html along with 4 more of the same html for different social media sites:

a href="https://socialmediasite.com" target="_blank"
img src="/images/socialmedialink1_icon_32x32.png" alt="Social Media link" style="width: 32px; height: 32px; border:0"
/a

The problems aren't the links because they do work. The problem is the images aren't showing up and only showing up as broken links so there's a problem with the img src link. I made a folder under root directory named images using my website hosting companies file manager and the images have been uploaded to that folder so I don't know what I'm missing. Am I missing something in the img src or something else before the a href or can it just not be done using only a custom block?

Try using the full site url for the src tags.

Prepend return value of $base_url and the rest of your path leading up to the image to your src attribute


Where are the RESTful module permissions other than `Administer REST resource configuration`? According to the tutorial An Introduction to RESTful Web Services in Drupal 8, the admin/people/permissions path should contain the following permissions:

But now that I installed the latest version of Drupal, the big surprise is on my website there are no other RESTful module permissions than Administer REST resource configuration, no permissions to grant DELETE, GET, PATCH or POST to each role.

I have Enabled all core web services modules (HAL, HTTP Basic Authentication, RESTful Web Services, Serialization) + REST UI module.

Are those permissions removed from Drupal 8.2.5?

This was introduced since 8.2.0

Accessing entities via REST no longer requires additional REST-specific permissions

  This was actually only meant to be a temporary measure, because we
  already have an Entity Access API that governs access/operations to/on
  those entities. And in fact, Entity Access is respected when accessing
  entities via REST. So, there was no more reason for this to exist in
  Drupal 8.0.x and Drupal 8.1.x, but it was simply forgotten to be
  removed before Drupal 8.0.0's release. The fact that you needed to
  grant both those permissions as well as Entity Access needing to grant
  you access, was a source of confusion and frustration with Drupal 8's
  REST API, which has now been fixed.

  So, as of Drupal 8.2.0, new installations no longer need those permissions to access entities via REST. Existing installations
  continue to have the old behavior. Existing sites can opt out of that
  behavior, and opt in to the new behavior, by modifying the
  rest.settings configuration from

  bc_entity_resource_permissions: true

  to

  bc_entity_resource_permissions: false

  (The latter is the default on new Drupal 8.2 installations.)


Nodes created on 1st date of the month are not showing up on Calendar I am using the following modules

Calendar
Date

There is an attendance content type with a field of type date.
The nodes of this content type get pulled in a Calendar.

But, nodes which are created on the 1st date of the month are not showing up in the calendar.

It's not clear if you are A> using a "date contextual filter" and "page by date" or B> you are simply showing content in a calendar.

If it's B>, check your date filter and make sure you have "greater than or equal to" set to ensure the first day gets included.


Content type load via PHP We load a specific node in our template.php file via node_load(), in the same way <?php if ($content = render($page['content'])): ?> is used for loading a block.

I have a content type (news), and I want to load this content type items on my template.php file. How can I do it?

Try using the views module and views_embed_view


Returning a db query for select options in webform I am trying to return dynamic select options for a webform component.  I have it working to return node titles, but I need to instead return values from a manually created table in the db that is not drupal related.  How would I alter this function to achieve that?

function _MY_MODULE_get_rate_options() {
    $nodes = array();
    $select = db_query("MY DB QUERY HERE");
    foreach ($select as $node) {
        $nodes[$node->nid] = $node->title;
    }
    return $nodes;
}

If you're creating a select list then you only need two fields from the database, so you can use the excellent fetchAllKeyed() method of the database query. This will let you get your results in a single line of code:

function _MY_MODULE_get_rate_options() {
  return db_query('SELECT id, name FROM {my_table}')->fetchAllKeyed();
}

The result is an array keyed by the first field (id) with values from the second field (name).


Fieldable panels panes - add a default category when creating With Fieldable panels panes is it possible to programatically add a default category for all reusable entities?

Im adding new instances as follows, but it would be great if I could hard-code or even just suggest a category for all panes of this type to be created under. This way the Panels IPE wouldn't be such a mess if (when) editors don't set a category and everything gets lumped into 'Reusable Content'.

function logic_pane_bundles_entity_info_alter(&$entity_info) {

$entity_info['fieldable_panels_pane']['bundles']['poster_pane'] =
array(
    'label' => t('Poster Pane'),
    'pane category' => t('Hello bundles'),
    'pane top level' => TRUE, // set to true to make this show as a top level icon
    'pane icon' => '',
    'admin' => array(
        'path' => 'admin/structure/fieldable-panels-panes/manage/%fieldable_panels_panes_type',
        'bundle argument' => 4,
        // Note that this has all _ replaced with - from the bundle name.
        'real path' => 'admin/structure/fieldable-panels-panes/manage/poster-pane',
        'access arguments' => array('administer fieldable panels panes'),
    ),
);

}

Many thanks!

Currently it's not possible to assign a category in hook_entity_info_alter. See feature request https://www.drupal.org/node/2149989

To achieve this, couldn't you just fill the category form field, using hook_form_alter in a custom module, like in my other answer?


Display main menu vertically (Drupal. 7.9) I am not sure how this has happened. but wherever I render the block of my main menu, it displays it's links horizontally rather vertically. Essentially I want to create a main menu that displays its links vertically.

Anybody have a lead on how this can be done ? I am tempted to go into the CSS and alter the theme myself but given that Drupal probably has a switch that allows me to alter the way a main-menu is listed, I want to caution myself.

Thanks!

You need to use Firebug and find the style rule that is being applied to the <li>elements that will be displaying them inline. Firebug will tell you where the CSS is being loaded and this will lead you to the culprit. One tip is to make sure you're not aggregating CSS so you can find the correct stylesheet. If it isn't theme specific it may be CSS being loaded by a module, but I am confident that there is some CSS there that is creating the result you're seeing.


Image style not loading on first load I have images of a certain image style that only show up after reloading the page. I can see the image created in the style directory after the first page request. Its like the browser is not waiting for the image to be created.

I wrote a curl script to request all the images of that style on the site, which works. But I'm worried that when new images are added they won't show on first request. Any idea what would cause that?

UPDATE:

I spent most of the day yesterday working on this. It happens when the derivative image is first created and served by Drupal. I found an extra new line character at the beginning of the image. If I save it to my desktop and remove the newline it works fine.

I read elsewhere that this can be caused by an extra space in a file like settings.php or template.php, usually before the <?php or after the ?> if it has one. I checked and rechecked those files and I've also been using find and grep to try and find the offending file but so far no luck.

I also tried adding header("Fake: fake"); to different files to see if I could generate a "headers already sent" error. But the output buffering Drupal uses seems to prevent that from working. Also I added $conf['image_allow_insecure_derivatives'] = TRUE;` to settings.php but that didn't fix it either.

There was extra space before the <?php in index.php. Not sure how I missed it with all my searching before.


Drupal 7 auction module or something I'm search for a few days now. But I cannot find a good auction module for Drupal 7. I have try the module: uc_auction but the highest bid did not save in my shopping card only my sell price. I have no idea of there is an other option for een auction system but I cannot find him.

Who have a suggestion for me? I'm using the module Ubercart for my website now.

Auction module provides auction functionality. Commerce integration is an option.

  Structure: Auctions are entities with start / end date, starting
  price, minimum price and instant buy price. Auction content type with
  auction reference field is created upon installation.

or

Commerce Auction module lets you create auction/reverse auction websites using drupal commerce. see the Demo

Features

Allows creating auctions and reverse auctions using drupal commerce
Automatic auction timeout extension
Automatically adds auctioned product to the winner's shopping cart
By default disables remove and edit quantity fields of auctioned products in shopping cart
Global and per-auction bid limits (like uc_auction)
Lists bids using views


How can I select a user role at the time of the account registration? How can I show the field to let users choose the role when they register an account on Drupal 8?

Good day,

Have you tried the Select registration roles module? I think this would be a straightforward configuration for the role field that you want.

Hope everything is in order.

Thanks!


Is ist possible to get the page variables in node templates? I set a variable by implementing the hook hook_preprocess_page. The variable is available in $variables['my_custom_var'] within the page.tpl.php.

Is it possible to get access to this variable in node.tpl.php or any other node template?

In node.tpl.php you can render the particular field like this:

echo render($content['field_header']);
hide($content['field_header']); // This line isn't necessary as the field has already been rendered, but I've left it here to show how to hide part of a render array in general.

If you need to do this in page.tpl.php then you want to implement a preprocess function in your template file to get the variable you need:

function mymodule_preproces_page(&$vars) {
  if ($node = menu_get_object() && $node->type == 'page') {
    $view = node_view($node);
    $vars['my_header'] = render($view['field_header']);
  }
}


Does Apachr Solr use Taxonomy or CCK fields for faceted search? I'm trying to put together a simple faceted search block using Solr. Search with Solr works, but I'm unsure of what's required for creating a block of search properties for faceted search.

For example, my content is for accommodation, so I want to be able to search by price range, capacity and location. Price range and capacity data are already populated as CCK fields, but location is set up as a hierarchical taxonomy.

I'm wondering what Solr requires for me to implement a simple, faceted search block. Does it use CCK fields for search properties or Taxonomy? Or have I misunderstood how faceted search blocks for Solr are built?

Out of the box, apachesolr.module 6.x and its friends can facet on taxonomy and cck text fields (with certain limitations). You just need to enable the desired facets in the settings, having made sure that the vocabulary is actually connected to your content type in the vocabulary settings.

For price range / any numeric range faceting I have not found a working contrib module. There is a module though, http://drupal.org/project/apachesolr_facetbuilder which allows you to build at least categorized facets for your numeric values.


How do I unset the comment form in Drupal 7? In Drupal 7, the comment form appears on every node. I want to unset the comment form and display a link of "Add new comment" that will display the comment form on click.

Do you have any Idea?

Go to "Structure > Content types", "Content type > Comment settings", and uncheck "Show reply form on same page as comments."


Integrating html code into existing Drupal 6 webform I was provided some custom html code by my client’s email provider in order to automate getting the submissions into the client’s email system instead of the client having to enter them manually.  The code provided looks like this:

    <form method='get' accept-charset='UTF-8' name='oi_form' action='http://suivi.lnk01.com/xyz'>
    Email: <input type='text' name='email'/>

    First Name: <input type='text' name='firstname' />

    Last Name: <input type='text' name='lastname' />

    <input type='hidden' name='Source' value='Newsletter Website' />

    <input type='hidden' name='goto' value='' />
    <input type='hidden' name='iehack' value='&#9760;' />
    <input type='submit' value='Subscribe' />
    </form>

I originally tried adding components (one for the first line and another for the 3 input lines after the fields) to the existing webform but it would not create a submission.

I then installed the webform remote post module, entered the target url value for the form, entered some data on the form, and submitted.  It created a submission but on the client’s side, the first name, last name, and source fields are all blank.  Has anyone had this same experience before ??

The submission made might be reaching client's side as POST variables, can you try to alter your form's submission method to "GET" instead of "POST".

From

$form['#method'] = 'post';

to

$form['#method'] = 'get';


how many taxonomies i should use? there are different content types and associated with different taxonomies. for example forum content type associated forum taxonomy, article content type is associated with tag taxonomy and gallery content type is associated with gallery taxonomy. i want to show related contents in front page blog, but taxonomies different. how can i associate them? with using only one taxonomy for all content types or else?

Forum and Gallery taxonomies are used to maintain the information structure of their respective content types. They should not be mixed.

A tagging taxonomy, on the other hand, is generally freestyle, and allows a user to give keywords describing the content. There is no reason to restrict it to a single content type. Why not use your tags on all content types.


How to add a different specific image for each page in a region? I want to have a different specific image on every page in the same region for each. I don't want to have to create separate blocks for each one. Is there an easier way? I will be getting the images from the directory.

Thanks

I assume that you have a content type which contains the field image and that image field have to displayed randomly in different pages. If so the solution would be

Create a block view and add the content type as criteria and the field:image
Remove all sort criteria and just add Global: Random as a sort criteria
specify only one content should be displayed in Pager option

That's it. Now you can render it and it will randomly display the image in each page


How to Create Web Application in Drupal I have a platform independent specification for a web application. I have attached a very small portion of the UML specification posted here. Is it possible to implement the classes as shown by the diagram.

I am not a Drupal Expert and I am having very difficult time in explaning the feaures I want to the Drupal Expernt.

Is it possible to develop content type with this kind of structure and do the data entry from single Page.

It would be great if someone could show me the right direction.

Yes, you can build that type of data model using fieldable entities in Drupal 7.

For example add base "Member" fields to the user entity and use entityreference for the related reference fields on other entities (similar to a foreign key relationship)

The addressfield module provides a good standard address field and associated data structure to hold that info.

In your model, because it appears a "Member" may have many "Member Contact" records, you could perhaps just create a node type for "Member Contact" and add an entity reference field to the relevant "Member".

More info on Drupal 7 Entity API

Lastly, if you want to do it completely custom, you can define your own entity types with hook_entity_info


How to convert the drupal-entity tag into an img tag? I have a content type with a text field that uses CKEditor, in the editor is possible to add a media entity image, once the image is inserted inside the text the html tag for it is:

Document
\r\n\r\n<drupal-entity alt=\"Luz\" data-embed-button=\"media_browser\" data-entity-embed-display=\"media_image\" data-entity-embed-display-settings=\"{&quot;image_style&quot;:&quot;&quot;,&quot;image_link&quot;:&quot;&quot;}\" data-entity-type=\"media\" data-entity-uuid=\"4076130e-9ccb-43f1-a4d9-dc8176271ffa\" title=\"Luz\"></drupal-entity>\r\n

I have in the site a webservice that need to provide the text field with all the information, but I need to convert the drupal-entity tag into an img tag to provide a tag that can be used from the applications that use the webservice.

I made a search inside the CKEditor configurations and in the media module but I can't find any related to this, how can I convert the drupal-entity tag into an img tag?

Basically you'll want to get the field's value and do a str_replace(), but where?

I haven't done this myself yet, but I believe you'll have to create a normalizer.

Serialization API overview (good read).

I think you can achieve it by doing the following Changing the way Serializer handles entities.

There is more indepth info here Using Normalizers to Alter REST JSON Structure in Drupal 8.


Tableselect with dropdown per row I use a tableselect to output a list of terms and per row I want a drop down (select):

$header = array(
      'name' => array('data' => t('Name')),
      'weight' => array('data' => t('Weight')),
    );

    $options = array();

    foreach ($terms as $term) {
      $options[$term->tid] = array(
        'name' => array(
          'data' => array(
            '#title' => $term->name,
            '#type' => 'link',
            '#href' => sprintf('/taxonomy/term/%d', $term->tid),
          ),
        ),
        'weight' => array(
          'data' => array(
            '#type' => 'select',
            '#options' => range(1,25),
          ),
        ),
      );
    }

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

My problem is that I do not see the value of the drop down (select) when I debug.

function example_block_save($delta = '', $edit = array()) {
  debug($edit, null, true);
}

Here is what I get:

[term_list] => Array
        (
            [list] => Array
                (
                    [5] => 5
                    [4] => 0
                    [6] => 0
                )

        )

When I check the code I can see that the select has no name, I'm guessing that's why I don't see it in the debug.

give default value property to select element e.g select form element returns value if select has been checked

add this attribute

'#default_value'= 1;

to every select list and your data to select list must be an array with key and value

$element=array(
'#type'=>'select',
'#default_value'=>1,
'#options'=>array(
         0 => t('No'),
         1 => t('Yes'),
    )

);

maybe then you have to render this element array with theme_form_element to your data variable. sorry but i havent enough time to test this solution


CKEditor + IMCE file uploader. What am I missing? I've got CKEditor and IMCE modules installed and enabled. I've got an "Insert image" link at the bottom of the "body" text area. However, I can't seem to get the wysiwyg editor to display.

What am I missing?

In admin/config/content/formats
I only have Plain text format.

Should I add Fitered HTML, full HTML and php manually?

Or shoud have they been created automatically with one of the modules?

Depending on what version of Drupal you're using, my first inclination is to say the Media module is what you're missing.

That aside, there are a number of steps to take to configure the WYSIWYG image experience.

How did you install CKEditor? Did you install the WYSIWYG module and the CKEditor library properly?
Did you install the correct version of CKEditor? I think you might need the 3.6 version.
Have you set up the correct input format? Does your user have permissions to use it?
Have you set up a CKEditor profile with the correct image insert buttons that integrate with IMCE?

Those are the main things that come to mind, though knowing more about what happens (i.e., when you disable rich text, does anything display in the editing window?) and what steps you've already taken would help narrow it down.


Use drupal.settings variables on javascript I'm using the Google Maps API on my website regarding restaurants.
The map loads when a restaurant has been selected.
I was initially using the google embed map, but I got some errors (e.g. markers not showing), so I switched to gm API.

How do I use a drupal.setting variable to a javascript? This is my code.

var myCenter = new google.maps.LatLng(Drupal.settings.eatery_geo.address);
function initialize() {
  var mapProp = {
    center:myCenter,
    zoom:16,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"),mapProp);

  var marker = new google.maps.Marker({
    position:myCenter,
  });

  marker.setMap(map);
}

google.maps.event.addDomListener(window, 'load', initialize);

Where Drupal.settings.eatery_geo.address has the variable?

This doesn't seem to work; it only shows a blank <div>.

It gets its value from your PHP code. Here is an example of using drupal_add_js:

//Your module.php
$settings = array(
  'helloWorld' => array(
    'display' => 'alert',
    'message' => 'Hello World!',
  ),
);
drupal_add_js($settings, 'setting');

You can access the message in your JavaScript with Drupal.settings.helloWorld.message.


Changing the layout of a Taxonomy Term Page By default my taxonomy term page lists all articles using this term in 2-columns. I would like to change it to a 1-column layout.
(1) I have created a custom display layout for the taxonomy group:

(2) And selected the one column layout:

Still it doesn't work. Any other changes, like adding a field, do work though. What am I missing?
Note: I did clear the cache.

Thanks to @prkos, it turned out that the root of the problem was located inside the Bootstrap Sub-Theme.
Someone created a (hacky) template override for one specific content type in a generic manner. By renaming the file views-view-unformatted.html.twig to views-view-unformatted--SOME-CONTENT.html.twig it kept the override for the mentioned content item, but also made layouts of other, generic content types work as intended.


cache issue - misaligned views cached output I am trying to set the view on the home page.
http://www.userbase.com/

The content gets misaligned for anonymous user. I can see proper output if I am logged in.

Any ides?

I am using following cache plugins:

Block Cache Alter
Render cache
Render cache for comments added to a node
Render cache for display suite views integration
Render cache for node_show
Render cache for views_plugin_row_node_view
Safe cache_form Clear

It looks like you need to add clearfix to the css attribute of your views rows.


Checkout page change theme i use drupal 7 with Commerce module installed. I am searching a couple days to find out a way to change (alter) the presentation (theme) of Checkout page. I mean the first page that someone visit after pressing Checkout button. (Not the review or payment pages).

What is trying to do, is to have only the cart contents on top and below that i want to create a tab system with the following tabs:

Login
Create Account
Complete checkout as a guest

So i need to hide the billing or shipping or any other pane and make them visible only on the third tab.

I think i have some pieces of the puzzle, for example i have tried creating a custom module and playing with hook_commerce_checkout_pane_info_alter to unset some panes and hook_form_commerce_checkout_form_alter to create panes programmatically but i am lost in space...

Another puzzle piece, is the php code of the login form for the first tab(Login) for example:

<?php
   $elements = drupal_get_form("user_login");
   $form = drupal_render($elements);
   echo $form;
?>

I may need your help to make things clearer. I need to reorder panes, add some custom html and javascript to create the tab system and bring some forms there. Where is this canvas, the template that loads everything so to bypass that and create my own ? Where do i have to look, search and study ?

Thank you :)

In a custom module you can change the theme like this:

function YOUR_MODULE_custom_theme() {
  if (current_path() == 'checkout') {
    return 'plain';
  }
}

With this approach you need a full new theme (in the above example named plain). You then can directly use it's page.tpl.php. In template_preprocess_page you could add javascript and fill variables with your html (or blocks).

Also you can place the blocks like you want for this theme.

To get the correct current_path you would need to debug a lil. checkout is just guessed by me ..


Allow authenticated users to update submissions Drupal 8.6.5 and Webform 5 here

I have a webform in which I have enabled Signature Pad (I mean https://github.com/szimek/signature_pad). I would like to implement a workflow such that:

An authenticated user submits the form, and an email is sent to another authenticated user with a link to the webform submission (this second user is chosen by the first user by filling a field in the form)
The second user is able to follow the link, authenticate and update the first user's submission (he adds his signature to the submission)

This is easy to accomplish when the second user is known (just a matter of access permissions), but how can I implement such a thing when he is not known/predetermined?

You might want to implement an application evaluation workflow and the Webform module includes a 'Webform Demo: Application/Evaluation System' module.

The demo has an evaluation form attached the application form using a block.

For the email routing, you should be able to use a user entity reference token in email handlers 'To' field.


views_get_view in combination with i18nviews only translates part of header I'm using the following code to get a view and render it

  $view = views_get_view('viewname');
  $view->set_display('page');

  $view->set_arguments(array($type));

  $view->pre_execute();
  $view->execute();

  return $view->render();

Works great but some fields of the exposed filters and the header are not getting translated. I'm using the i18nviews modules.

Any ideas?

Thanks

Using the following code triggers i18nviews correctly:

$view = views_get_view('viewname');
$view->set_display('page', array($type));


How to add fields to a content type? I installed Drupal 8 minimum.
Create content type. Like normal there is one field. The body field.

I can't add an other field. In extend/modules all field types are enabled. Also fields and fields UI. What am I missing or have to enable to add fields to content type like: Image, link, references, etc.

I ran drush cr a couple of times.

I highly suggest that you do not use the minimal install in Drupal, and go with the standard install.

It is way more efficient to use the standard install and then remove the modules that you do not want, than to use the minimal install and install a bunch of stuff.


How do I create an invoice without product? Am working a project that required generating invoice for customer service payment, 'rent' to be specific. Am still a newbie to drupal environment (I do Wordpress Stuff).

Since the Payment is going to be recurrent I choose Drupal Commerce, but am confuse as to how to configure the module(s) needed.

Features that I need
- Admin created invoice for Client (registered user) with invoice status UNPAID
- Invoice sent to Client via email (PDF format)
- Client Pay at Bank and upload Prove of payment
- Admin change the invoice status to PAID upon Validation.

I could Create Content type for the invoice, but I may not be able to create PDF and mail it to user in which Drupal Commerce would handled well with other Contributed Module.

I should be able to handle it if I can get a kind of guide.

I would take a look at the Commerce Billy module

Features

Thread safe invoice number generation
Three invoice number generation methods: monthly, yearly, infinite
Configurable pre- an suffix values for invoice numbers
Arbitrary start value for invoice number
"invoiced" status on order entity (thus avoiding separate invoice entity)
Automatic or manual invoicing:
    Automatic: order moved to status "invoiced" on order completion
    Manual: admin moves order to status "invoiced" (VBO possible, Rules components already included)
PDF Generation (commerce_billy_pdf module)
Customizable PDF template
Views integration for PDF download link
Handling of credit memos (canceled orders)


Create stacked page with panels module I'm trying to create a stacked page with the Panels module, using flexible layouts. It should look like this:

How can I do this?

Simply add 3 rows in the flexible layout by clicking 'Column' > 'Add row to top/bottom' in the layout designer to stack the page. Add fluid or fixed regions afterwards in every row.

(Special thanks to @Letharion!)

You can also achieve this without the flexible layouts and do it programatically like @Andrew Welch said. This video can help you in doing that.


notice after entering a function in template.php I get the following notices on every page:

Notice: Undefined index: node in myZen_preprocess_page() (line 242 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).
Notice: Trying to get property of non-object in myZen_preprocess_page() (line 242 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).
Notice: Undefined index: node in myZen_preprocess_page() (line 246 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).
Notice: Trying to get property of non-object in myZen_preprocess_page() (line 246 of /Applications/XAMPP/xamppfiles/htdocs/drupalH1/sites/all/themes/myZen/template.php).

I put the function I need to use the files page--content-type, and is as follows:

function myZen_preprocess_page(&$vars) {
   if ($vars['node']->type == 'mappe'){
     $vars['theme_hook_suggestions'][] = 'page__mappe';

    }
  else if ($vars['node']->type == 'fatti_e_risorse'){
    $vars['theme_hook_suggestions'][] = 'page__fatti_e_risorse';

  }

  }

Can I disable notices or fix this? thank you!

That notification is displayed because the node key of the $vars array is not always defined in hook_preprocess_page() function.

Use the following code, which first checks if the node key exists and then continues. It also uses the switch statement, which is easier to read if you only need to check the node type and use one condition:

function myZen_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    switch ($vars['node']->type) {
      case 'mappe':
        $vars['theme_hook_suggestions'][] = 'page__mappe';
        break;

      case 'fatti_e_risorse':
        $vars['theme_hook_suggestions'][] = 'page__fatti_e_risorse';
        break;
    }
  }
}


How I can pre-populate a webform field with the node title and node link? In some page I have inserted a link "Contact me for info" that links to a webform page.
I would that some fields of the webform form are be pre-populated with the node title and node link from the previous page.
How I do it?

Use the PrePopulate module and Tokens to build dynamic links on your pages. When clicked, the link's content will be entered into those fields automatically.

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

There's an example on the project page.


How to test an alter hook in your .module with ModuleHandler service? I have setup a kernel test to test a function in my module:

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {
  // ... code
}

In my test, I tried:

$variables = [...array];
$this->container->get('module_handler')->invoke('mymodule', 'link_alter', $variables);

But what I got was:

  Parameter 1 to mymodule_link_alter() expected to be a reference, value given.

For now I removed that line and just called the function directly. Is there a way to invoke a hook that does not throw that error?

For alter hooks, there is ModuleHandler::alter(). That is what, for example, the AlterTest class uses.

// Verify alteration of a single argument.
$array_copy = $array;
$array_expected = [
  'foo' => 'Drupal theme',
];
\Drupal::moduleHandler()->alter('drupal_alter', $array_copy);
\Drupal::theme()->alter('drupal_alter', $array_copy);
$this->assertEqual($array_copy, $array_expected, 'Single array was altered.');
$entity_copy = clone $entity;
$entity_expected = clone $entity;
$entity_expected->foo = 'Drupal theme';
\Drupal::moduleHandler()->alter('drupal_alter', $entity_copy);
\Drupal::theme()->alter('drupal_alter', $entity_copy);
$this->assertEqual($entity_copy, $entity_expected, 'Single object was altered.');

The Drupal 7 documentation for module_invoke() is more explicit in suggesting to use drupal_alter() for arguments passed by reference.

  All arguments are passed by value. Use drupal_alter() if you need to pass arguments by reference.

If the hook you are testing is also implemented from one of the modules from which your module depends, ModuleHandler::alter() would invoke the hook implemented from those modules (if those modules are installed from the test), but I take that testing an alter hook means also testing it works together the same hook implemented by the module dependencies. (In this way, the module can also test if its alter hook implementation needs to be executed earlier or later, respect other implementations of the same hook.)

if you really need to invoke a single alter hook, and other modules installed from the test implement it, you could use the following method to add in the test class.

function protected invokeAlterHook($module, $type, &$data, &$context1 = NULL, &$context2 = NULL) {
  $function = "$module_$type";
  $function($data, $context1, $context2);
}

If you look at the code in ModuleHandler::alter(), that is simply the way it invokes the hook implementations.

  foreach ($this->alterFunctions[$cid] as $function) {
    $function($data, $context1, $context2);
  }

ModuleHandler::invoke() doesn't work with parameters expected to be passed as reference because it uses the following code to invoke the hook.

$function = $module . '_' . $hook;
return call_user_func_array($function, $args);

To pass an argument by reference, call_user_func_array() should be called, for example, as call_user_func_array($function, [&$data]).


FROM_UNIXTIME(o.created,'%d-%m-%Y') in where clause gives error I am working on Drupal 6. while executing  query when I add
and FROM_UNIXTIME(o.created,'%d-%m-%Y') <  '".arg(3)."'";
to WHERE clause it doesn't return result.
i have tried by using same query in MySQL Query Browser it returns result.
so I am confused how to pass above condition in WHERE clause,
as I am passing 31-10-2012 in arg(3).

You just need to escape the percent sign with another, i.e.,

FROM_UNIXTIME(o.created,'%%d-%%m-%%Y')

Also make sure you use parameter replacement rather than injecting strings directly into the query; you're not protected from SQL injection at the moment.

That would be something like

$sql = "SELECT * FROM {table} WHERE FROM_UNIXTIME(o.created,'%%d-%%m-%%Y') < '%s'";
$result = db_query($sql, arg(3));


How can i write url specific CSS How can i write css for content of the dynamic url page like 'http://mysitename/user/23/prayerrequests'. Here 23, assume user id. I want to effect conent div css of this dynamic url's.

you can use the following, it implements drupal_add_css().

if($_GET['q']=="user/23/prayerrequests") {
  drupal_add_css(path_to_theme() . '/custom_stylesheet.css', 'theme', 'all');
}

Edit 1:
If you want this to be able to do it for all users, you could use me aliases module. It enables you to use me in place of %uid.
So, the code would become

// "me" from the code is automatically replaced by uid of current logged in user.
if($_GET['q']=="user/me/prayerrequests") {
  drupal_add_css(path_to_theme() . '/custom_stylesheet.css', 'theme', 'all');
}

Edit 2:
You can use the variable global $user in the above code. You'll not need to install me aliases module.

//replace THEME with your theme name
function THEME_preprocess_page(&$variables) {
  global $user;
  if($user->uid == 0) {
    return;
  }
  elseif ($_GET['q']=="user/".$user->uid."/prayerrequests") {
    drupal_add_css(path_to_theme() . '/custom_stylesheet.css', 'theme', 'all');
}

Don't forget to clear the caches.


Link views page to taxonomy term page I have created a views block and page to display nodes based on term of a taxonomy vocabulary (contextual filter).
From this block I have a more link enabled and linked to the page.
Here how to make the views page path linked to corresponding taxonomy term pages?

Provide the path as taxonomy/term/%
Install the pathauto module and override the path using the required patterns.


Allow multiple instances of reCAPTCHA on the same page There are several forms in a page and I use recaptcha module for all of them. The problem is, the recaptcha is generated for one of them not all of them.

In Allow multiple instances of reCAPTCHA on the same page the recaptcha-mutltiple_instances-1833822-31.patch patch is offered, and sounds it is working (I am not sure). But the problem is the recaptcha.js file doesn't exist in the recaptha module folder while it asks to update that file as well.

This is the module folder:

The issue was first open for the developer version 7.x-1.x-dev, which contains that file; then it was updated for 8.x-2.x-dev, and then 7.x-2.x-dev. You need to install the developer version, and apply the patch for that developer version.


How do I display a form element only if the above checkbox is checked? I am about to create a blockForm with a display_count checkbox and two count_prefix and count_suffix textfields.

The count_prefix and count_suffix textfields shall only be shown if display_count is checked.

I have this code:

  $form['display_count'] = [
  '#type' => 'checkbox',
  '#title' => t('Display count'),
  '#description' => t('Display how many times each term is used on a node.'),
  '#default_value' => $config['display_count'],
];
$form['count_prefix'] = [
  '#type' => 'textfield',
  '#title' => t('Count prefix'),
  '#description' => t('Set a prefix to be displayed before count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_prefix'],
];
$form['count_suffix'] = [
  '#type' => 'textfield',
  '#title' => t('Count suffix'),
  '#description' => t('Set a suffix to be displayed after count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_suffix'],
];

I have tried to add this to count_prefix and count_suffix:

  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array(
        array('checked' => TRUE),
      ),
  ),
),

but it didn't worked.

I have tried to find other questions with the same but none of them worked for me.

Use like this:

$form['count_prefix'] = [
  '#type' => 'textfield',
  '#title' => t('Count prefix'),
  '#description' => t('Set a prefix to be displayed before count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_prefix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];
$form['count_suffix'] = [
  '#type' => 'textfield',
  '#title' => t('Count suffix'),
  '#description' => t('Set a suffix to be displayed after count number e.g. (5), [5] or <5>'),
  '#required' => FALSE,
  '#default_value' => $config['count_suffix'],
  '#states' => array(
    'visible' => array(
      ':input[name="display_count"]' => array('checked' => TRUE),
    ),
  ),
];


How do I render nodes, now that node_view() has been deprecated? In Drupal 7 I frequently use node_view() for rendering nodes (using view modes) in blocks or pages as follows:

$nids = array(123,456,789);
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  $node_view = node_view($node, 'teaser');
  $output .= drupal_render($node_view);
}
$build['nodes']['#markup'] = $output;
return $build;

node_view()/entity_view() has been deprecated and replaced by a view builder as explained in change record Entities are now rendered by a view builder . The information is not detailed enough for me to be able to figure out how to achieve the same result.

How can you render nodes in Drupal 8 so that the output can be used in the render array of a block or page?

The answer given by Berdir uses entityManager, which has been deprecated in favor of more specific services. This is the code I currently use.

$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';

$view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$node = $storage->load($nid);
$build = $view_builder->view($node, $view_mode);
$output = render($build);

This code is a little more verbose than some might like; you could reduce it down to a couple lines if you really want more brevity by chaining together some methods.

$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';

$node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($nid);
$output = render(\Drupal::entityTypeManager()->getViewBuilder($entity_type)->view($node, $view_mode));


Dynamic Views Pages - How to add in meta tags to these generated pages? I have 1000s of dynamically generated views pages using contentual filters. I want to be able to take certain keywords from these generated pages and add them to the on page meta tags. Currently I do not have any metatags on these pages. Is there a module that can add such a functionality that can inject it into a view?

If there is no such module, do you think the best way would be to create a custom tpl just for these dynamic pages and output these keywords on the html.tpl.php template?

The metatag module comes with 'metatag views'. Enabling this module you with have a metatag settings on the metatag config page (admin/config/search/metatags).

I am not sure what meta tags you are referring to but I will give you an example.

I am using the view that overrides the default taxonomy term pages. To set the description meta tag for this view I put '[view:description][current-page:url:args:value:1]' into the metatag setting for views.

If you are worried about the keyword metatag I would not bother as they ont seem  to impact seo anymore, and I don't know of an easy way to set this dynamically for views.

You may also want to check out the metatag views overview module which has a confusing description but may help you.

Also, take a look in the file 'metatag.api.php' in the metatag module for something that you could use.


How to grant access to anonymous users to submit contact form in webform module I installed Webform module and also Permission per Webform to configure permissions for each webform. this is configuration in  Permission per Webform:

but anonymous users are still unable to see the Webform submit form. how can I enable them to see and submit the form?

You understood wrongly, the image you posted is for webform submission results, meaning permission to access the results of the webform after submitted.

You need to give permission in the webform itself, simply go to that webform and then click the form setting tab and then give permission for anonymous user.


How to embed a custom content type in a Drupal 7 theme? How can I make a custom content type automatically available when a specific template is used?
e.g.: "Standard Page" is the custom content type I made with Drupal, going to structures-->content type etc. Now, it will be seen among the default content types, i.e. basic page and article. I want to make that custom content type, Standard Page, available without any effort when the template is enabled, i.e. without editing it: it must be embedded in the theme. How could it be done?
p.s. I'm new to drupal theming. Any suggestion will be really appreciated.

That's correct (answer below) -- you can't embed content types in your theme, however, you can create custom modules that users can install to have a content type you've created available.

If you are new to Drupal, and do not write your own modules yet, you can use the Features module to create custom content types on your site, export them to a feature via the Features module, and import them to any number of sites.

Using the features module can be a little confusing at first, but there's lots of additional documentation and tutorials online.  I'd start with the module's documentation page first: http://drupal.org/node/580026.  :-)


Site running from accidental upload of core in subdirectory Several months ago I accidentally uploaded the folder containing Drupal 6.25 core files to sites/all/modules.

The site now sees that folder as the base install and ignores the installation in the site root.  How can I safely get Drupal to look at the files in the site root as the base install and delete these files?   I tried simply deleting them when I did it and it takes down the site with a configuration error.

Configuration error:  500 - Internal server error - neither front end or back end will load

I had a similar incident where someone had put a second set of core modules in a second folder called "modules" inside the main modules directory.  As a result Drupal was running off of the system.module located in modules/modules/system.  This made updating the site problematic.

The only way I fixed it was by dumping the database as a text file (.sql), editing the modules/modules file paths in the systems table, then re-importing, overwriting the database.  You may also be able to do this via MySQL commands or using an interface such as phpMyAdmin.  You should also look at my other answer about steps taken when editing the database. (You would almost think that cowboy edits of the database is all I do everyday)

Know that editing the database is not best practice, but sometimes it is the only fix.  Make sure that you should have a backup in case you mess things up, which in most likely happen on our first attempt.


Show product commerce by taxonomy parent with childs I want to show several products filtered by apples. Apple is a hierarchy taxonomy and not always the values from the parents are in the childs.

Example:
apple (apple can have other results that are not in big_apple nor small_aplle)
-big_apple
-small_apple

Question: How can I create a view that when it's 'fruit/apple' shows apple + big_apple + small_apple and whent  it's 'fruit/big_apple' it will only be 'big_apple' ?

I think with this in contextual filters can help but it's far from working:

$id= taxonomy_get_term_by_name($argument);
$children = array_keys(taxonomy_get_children($id));
if(!empty($children))
{
    $handler->argument .= '+' . implode('+', $children);
    return TRUE;
}else
    return FALSE;

Well, I am my most popular fan so I will answer myself:
1. It's not possible to add that PHP code to the view, as it's a known bug that the view doesn't allow multiple contextual filter variables as a PHP. Although you can use them through the URL and changing the 'code PHP' option by 'Multiple Terms ID separated by ',' OR '+''. --> I don't like that option as the URL won't be very clean and can be a bit complicated.
2. Found a better option!! I decided to select the parent when one of its childs are selected. This option can be activated as automatically, when installing the Taxonomy Term Reference Tree Widget module:

About this module
This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.

Note: I don't know why but my tree view is not as nice as in the picture and I needed to use a fix but it works perfect.


Field collection: Can I make a field mandatory depending on another field's value? I'm trying to set up a custom solution using Field Collection consisting of:

term reference (autocomplete tagging style)
plain text.

What I need to achieve is to react to Javascript event of autocomplete (but only for that field) and - if the selected term title contains a string placeholder %1 - make the plain text mandatory, so that user is force to enter the substitution text.

Is that technically possible or would it require setting up a custom collection from scratch?

The Conditional Fields module can help you to achieve this.

You will probably need to create an explicit list of taxonomy terms for the case when you want the plain text field to appear and to be required instead of checking the existence of the aforementioned placeholder.


What is the progress bar periodic update function return data? In Drupal 7 from the function called with 'url/to/call/progressbar/update/function' (see below) you would return an array converted to JSON like this:

drupal_json_output($message);

I cannot find any examples for Drupal 8 and I suspect it's an object rather than an array that gets returned.

Does anyone know how/what to return from the progress bar update function?

The setup for the bar progress indicator would be something like this:

$form['some_item'] = array(
  '#type'  => 'submit',
  '#value' => t('My action'),
  '#ajax'  => array(
    'callback' => 'a_function',
    'wrapper'  => 'ajax-response-goes-here',
    'method'   => 'replace',
    'progress' => array (
      'type'     => 'bar',
      'message'  => 'Starting...',
      'url'      => 'url/to/call/progressbar/update/function',
      'interval' => '1000'
)

The core example is in FileWidgetAjaxController::progress. You need to return a JSON-encoded associative array with message and percentage keys. For example:

$progress['message'] = t('Uploading... (@current of @total)', ['@current' => format_size($status['bytes_uploaded']), '@total' => format_size($status['bytes_total'])]);
$progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
...
return new JsonResponse($progress);


Update a module and "is outside" error I have a new installation of Drupal 7.52 on a Windows server and during the update of some modules I receive that /websites/mydrupalroot/.... is outside from /website/mydrupalroot!

I found this question:

https://stackoverflow.com/questions/28701991/drupal-module-installation-error-file-transfer-failed-reason-mysite-com-site

but the solution didn't work for me!
What could be the problem?
Could it be the directories privileges?

Apart from the solution mentioned in the link included in your question, here are a few other things you may want to try:

Temporary change the configuration of the file system used by Drupal, to use a relative path to the temp folder (eg ..\temp) instead of a full path (eg C:\path\to\your\webroot\temp).
In your question it says "... during the update of some modules...", but nowhere you explained HOW you're performing this update. Are you using the update tool within Drupal? Are you using Drush? Are you performing this update using FTP or something like that? Whichever method you use, try to use any of the other typical approaches for updating modules. While doing so, you may run into some other unexpected problem/message, which may actually give you a clue about what your real problem is. E.g. some problem with a tmp-like folder to just unpack the new version of the module.
Try to disable all your modules first, then re-enable one of them again, and apply all updates, if any, related to that module you just enabled. If for this first module the error doesn't come back, you've reduced the list of modules that cause your proble with one. If the error does come back, disable that module again (to be investigated in more detail afterwards). Repeat for each of your other modules. This approach should help you to find/identify the problem module (and either leave that disabled, or start in depth debugging of that module).


Detect translatable strings in custom module code I have a D6 site with several custom modules. The site now needs to support multiple languages.

All my strings are wrapped in t() and I'm pretty familiar with locale.module and the i18n modules. I know that all translatable strings get written to the 'locales_source' table, and that from there I can export a .pot file to send to translators.

What I can't figure out, however, is how I can get all of the translatable strings in my custom modules into the 'locales_source' table. I know that the t() function calls locale(), which in turn will write a newly found string to this table, but how can I make all translatable strings get into the table at once?  I think I need a function that will parse the PHP source for t(), watchdog, hook_menu, etc to find everything that's translatable and write it to 'locale_source'...?

You can install the Translation template extractor module.

  The Translation template extractor provides a web based and a command line Gettext translation template extractor interface for Drupal as well as a reusable API to look for translatable strings and translatability errors. This tool is used under the hood at http://localize.drupal.org/ as well to serve as a parsing machine for Drupal.org project releases.

If you want a user interface that allows you to translate in any language the strings provided by your custom module, then you can install the Localization server.

  It provides a generic translation database backend with a community localization user interface, which allows people to collaborate on translating projects to different languages. It currently contains tools to translate Drupal projects as well as general Gettext based sources.

The difference is that the first module allows you to create the translation template files necessary to translate the strings provided by any module running on your server, including any custom module. Those files need to be edited to create the actual translation files that provide the translated strings.
The second module, which depends from the first one, allows to create the translation files using a user interface. While the first module requires you to manually edit the translation template files to obtain the translation files, with the second module you can do it using Drupal.


What are the major differences between Drush versions 3 & 4? What are some of the biggest differences between Drush versions 3.x & 4.x?

There's a lot of new user management stuff

user-add-role    Add a role to the specified user accounts.
user-block   Block the specified
user(s). user-cancel Cancel a user account with the specified name.
user-create  Create a user account with the specified name.
user-information Print information about the specified user(s).
user-login   Display a one time login link for the given user account (defaults to uid 1).
user-password    (Re)Set the password for the user account with the specified name.
user-remove-role Remove a role from the specified user accounts.
user-unblock Unblock the specified
user(s).

The cache clear functionality has become more fine grained
The backup folder for module updates now appears outside of webroot and you have greater control during updates over which modules to update (security updates only)

Check out http://docs.drush.org/ for more information.


Entity Query using conditions that ignore special characters I have an entity query where I search the body for user provided text.
I'm performing the query like so

$searchterm = 'test';
    $query = \Drupal::entityQuery('node')
            ->condition('status', NODE_PUBLISHED)
            ->condition('body', $searchterm, 'CONTAINS');

This gives me the results I need, but what if I run into a situation where the body contains the text 'test-1' but I want searches for 'test1' to bring up that result.

Is there anyway that I can write a query that ignores all special characters in the field I'm searching?

Drupal does not supply a solution to your problem out of the box.
However you can create a list of all the permutations and create a condition for each of them.

Code snippet

$searchterm = 'test-1_2 3';

$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED);

// permutation generator function.
$permutations = function($source_term) {
  $result = [$source_term];
  $unprocessed_terms = [$source_term];
  $regex = '/[\W_]/'; // Selects all the non-alphanumeric characters and _

  while (!empty($unprocessed_terms)) {
    $unprocessed_term = array_pop($unprocessed_terms);
    $matches = [[]];

    // By using PREG_OFFSET_CAPTURE we get the position of the match.
    preg_match_all($regex, $unprocessed_term, $matches, PREG_OFFSET_CAPTURE);
    foreach($matches[0] as list($match, $pos)) {
      $result[] = $unprocessed_terms[] = substr_replace($unprocessed_term, '', $pos, 1);
    }
  }

  // the above algorithm will create duplicates.
  return array_unique($result);
};

// Create an OR condition group that contains a
// condition for each permutation term.
$query->condition($or = $query->orConditionGroup());
foreach ($permutations($searchterm) as $term) {
  $or->condition('body', $term, 'CONTAINS');
}

$nids = $query->execute();


Views: attachment inherits exposed filters when set to No I created a page with an attachment to it.
Its a Glossary for the Username.

And here is my attachment setting:

i Have exposed filters on the page where it is attached to:

And the Filters works together: When i write something to the name it searches it and when i click on the glossary it retains the name's search value. I don't want that.

If i click on the Glossary i oly want that search, any other filters should reset. How do i achive that?

You can't do that by default with views settings. Filters are meant to stay upon adding / removing one of them, because otherwise you can't search items combining them. You can add a "Reset" button form the "Advanced" block of the view UI (see screenshot).

If you want this behavior to be exactly as you describe, I think you'll need write up a plugin for the filters yourself, or alter the default ones.


Style views row layout debending on result count How to style views row layout debending on result count?

If views has 4 results then items should be placed on two rows and two columns:
| |
| |

And when views has more than 4 items - for example 6 then:
| | |
| | |

You could implement hook_views_pre_render and count the number of results, then apply a class to the wrapper element.

function hook_views_pre_render(&$view) {
  switch($view->name) {
    case 'MY_VIEW_NAME':
      switch($view->current_display) {
        case 'MY_DISPLAY_ID':

          $numResults = count($view->result);

          /*
            Do your logic with $numResults here
          */
          if ($numResults <= 4) {
            $grid = 2;
          }
          else {
            $grid = 3;
          }

          $view->style_plugin->options['class'] = (isset($view->style_plugin->options['class'])) ? $view->style_plugin->options['class'] . ' grid-' . $grid : 'grid-' . $grid;

          break;
      }
      break;
  }
}

So then you can style the width of the views-row under grid-2 to be 50%, and 33% width for views-row under grid-3 in your CSS.

Your View display needs to use "HTML List" format for this code to work.


Attaching two or more jQuery files to a theme I was trying to add some jQuery files to a theme (to do some simple css logics). I could add one jQuery file by defining as follows

In the custom theme folder I edited themes.libraries.yml and added the following

global-scripts:
  js:
    js/jqueryfile1.js: {}
  dependencies:
    - core/jquery

and then I wrote my jquery code within inside custom_theme_folder/js/jqueryfile1.js as

(function ($){
Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
        $(document).ready(function(){

            //code goes here

            });
        });
    }
};
})(jQuery);

Everything was fine till now. But when I'm trying to add my next file(jqueryfile2.js) only the the latest (jqueryfile2.js) is taking in action. I can see the previous file is also called in the DOM while checking the source but the code is not executing. After adding my second jQuery my libraries.yml will look like

global-scripts:
  js:
    js/jqueryfile1.js: {}
    js/jqueryfile2.js: {}
  dependencies:
    - core/jquery

At this point jqueryfile2.js is only taking in action not the first file. And there will be both my jquery files within inside the js folder and is called to the document.

By default, multiple local files will be aggregated where possible. To disable this for a file, set its 'preprocess' flag to false.

mymodule:
  version: 1.x
  js:
    js/custom.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/jquery.ui


Where to initialize module specific variables I have been using hook_init in order to initialize some _SESSION variables on my application, however a problem I got after... is that hook_init is called on every ajax request. That's why I wanted to ask, what other hook, function or method should I use in order to initialize my module specific variables. I'm looking for something that's called just the first time the user enters the page, and not when a submit button is launched. (similar to isPostback???).

hook_init() is always invoked for not cached pages, even for AJAX request. You can verify the page request is made because an AJAX request, though.

There are two conditions that should be common on any AJAX request:

The menu path is system/ajax
The delivery callback is ajax_deliver()

While the first condition is only true when the form element doesn't set #ajax['path'],  the second condition should always be true.

Code similar to the following one should detect when a menu callback is called because an AJAX request.

if ($router_item = menu_get_item()) {
  if (isset($route_item['delivery_callback']) && $route_item['delivery_callback'] == 'ajax_deliver') {
    // It is an AJAX call.
  }
}

In Drupal 6, the menu callback for AJAX/AHAH requests changes, and each menu has its own callback. You can notice the path for those menu callbacks follows a specific pattern: It usually ends with /js, but that is not necessarily true. This means a menu callback could be associated with a path ending with /js, but that menu callback is not for a AJAX/AHAH request.


How to skip creating records with blank fields when migrating from csv file? I have created a migration with the Migrate module that migrates data from a csv file into a custom entity. There are some rows in my csv file that don't have any data for the entity that I'm importing into, so I would like to skip the creation of those entities.

Is there a way I can do this?

in your prepareRow function test to see if a field is empty and if it is, return FALSE.  For example:

public function prepareRow($row) {
  if ($row->data == '') {
    return FALSE;
  }
}


weird error - failed to open stream - .module file in theme path? I am just editing empty template, creating regions and so on. After I first time cleared cache weird error started to appear at every cache clearing:

  Warning: include_once(C:\xampp\htdocs\hkmzvolen/sites/all/themes/activit/activit.module):
  failed to open stream: No such file or directory v
  _theme_process_registry() (riadok 565 z C:\xampp\htdocs\hkmzvolen\includes\theme.inc).

  Warning: include_once(): Failed opening
  'C:\xampp\htdocs\hkmzvolen/sites/all/themes/activit/activit.module'
  for inclusion (include_path='.;C:\xampp\php\PEAR') v
  _theme_process_registry() (riadok 565 z C:\xampp\htdocs\hkmzvolen\includes\theme.inc).

It is trying to include activit.module from theme folder and not from module folder. There are a custom module and custom theme with the same name - activit. But there is no any activit.module file in theme directory nor I am including the file anywhere in my code.

Why is drupal trying to include this nonexisting file from my theme path?

There are a custom module and custom theme with the same name - activit

That's what causes the problem. Module and theme names need to be unique amongst one another. Drupal doesn't support duplicate names, and weird things can happen if you go against that.

See Module/theme name collision for more information.


How do I add content type in taxonomy settings? In Drupal 6, taxonomy can be added content type.

How do I add content type in taxonomy settings in Drupal 8?

Below is Drupal 6:

Below is Drupal 8:

Drupal 7 and 8 Core does not have that. I've never used Drupal 6, based on your question, it seems like they changed how tax terms are added to content types in D7.

For Drupal 8, all you have to do is go to Content Type (ex: Article) >> Manage Fields >> Add Field >> Select: Taxonomy Term >> Save Field Settings >> Checkmark your vocabulary >> Save settings.


Field collection item table names in mysql I am building a feature which will conditionally need to output entity data. The entity type is a custom one I created, which is complex and implements multiple nested field collections.

My issue is that looping through entities using Entity::loadMultiple() is very slow, as each entity needs to use FieldCollectionItem::load() multiple times to get to the data it needs to output. Over 1000 entity instances this uses up a lot of resources and takes a long time to load.

I am trying to circumvent this by retrieving the data via a SQL query and joining tables together. I'm hitting a road block when retrieving data from field collection items with long machine names, as the data appears to be stored in tables with names like field_collection_item__5d28be6634, basically just "field_collection_item__" with a 10-character hexadecimal hash added to it.

This would not theoretically be a big issue, except it looks like all records for the same field collection item seem to be split up across many of these tables with no pattern or connection that I can discern.

How do I know which tables to retrieve my data from for any given parent field collection instance?

Edit: I have revisited this recently and thought some of these tables might be revision tables, but none of them include the "_r_" in the table name. I still cannot determine which tables to use as there seem to be multiple tables (not including revision tables) for one field collection item. Looping through entities and loading nested field collections is taking upwards of 5 minutes which is just too long for my users.

In Drupal 8 the field tables are created as [ENTITY_TYPE]__[FIELD_NAME] and [ENTITY_TYPE]_revision__[FIELD_NAME] in database. The [ENTITY_TYPE]__[FIELD_NAME] is a main field table where latest revision data of entity field is stored. Where as [ENTITY_TYPE]_revision__[FIELD_NAME] is field revision table where all revision data is stored for a field.

In your case I think your Drupal/Database has some issue, because of which the table name has random character (10 characters) hexadecimal in it. I'm not sure of exact reason of this, but I too have notice this sometime in my Drupal Site (only twice one in D7 and one in D8) not every time.

In such case, where you're unsure of which table is used for which field, you can use name and value column in key_value table to get field table mapping. The name column contains, the entity and field name and value column contains serialized array of field schema stored in blob type. The name column format is as below:

[ENTITY_TYPE].field_schema_data.[FIELD_NAME]

So if I've field named as field_test in field_collection_item entity, then the mapping will be stored as field_collection_item.field_schema_data.field_test in key_value table. Check the screenshot below:

Screenshot 1: key_value table showing record of field_test field.

Screenshot 2: value column data from key_value table for field_test field.

I know this is not a better solution but, if table name doesn't has field name in it you can use data in value column in key_value table, you can find which table is used for which field.

Hope this helps.


The geographic data (latitude, longitude) isn't saved in content I have installed the Geofield module, created a new content type, and added a geofield field.
When I start to add nodes with latitude and longitude, those values aren't saved. Editing again the same node doesn't show any value for latitude and longitude.
What I'm trying to do is to install the Leaflet module, so I need to save the values first with the Geofield module.

Geofield module doesn't work without the GeoPHP library. You need to download both the module and the library and place them in the correct locations in order for the module to work.
When using Composer to install Drupal and modules the library is automatically downloaded to the correct place.
If you're not using Composer you can do that process manually. You probably already downloaded and installed the module Geofield in the common location /web/modules/contrib.
Now you have to download the GeoPHP library, you probably want the latest stable version, from the page noted on the Geofield documentation: https://github.com/phayes/geoPHP
The library is compressed, so you need to extract the archive file to get the folder with the library files. Then place that folder in your Drupal installation, usually in /vendor folder that is within Drupal root folder, so you end up with something like /vendor/geophp/ (I haven't checked the exact path and name).
Check the Status Report that the library is available and read properly by Drupal. Sometimes you need to adjust the library file permissions or ownership so Drupal can use it but I don't expect problems in cPanel.
Not using a Composer makes maintaining your site more difficult. You'll have to do updates manually and check for all dependencies yourself.
If you can invest a bit of time and use your computer for development you should install Composer and use it to build your Drupal site. Then just upload the resulting files to cPanel to host your site, but always keep a local copy with Composer to do the updates and maintenance.


Unable to upload large files (>50mb) to Amazon S3 from D7 on EC2 I'm trying to configure Drupal to upload large videos (eventually goal is ~300mb, but currently testing with ~50mb files) to S3 through my Drupal site running on an EC2 instance.

I have configured and tried both the Amazon S3 and Storage API modules. When trying to upload a small file around 5mb, everything is fine and works perfectly. However, when I try with a large file, I receive the following error:

  Warning: filesize(): stat failed for storage-field-storage-test://[FILE NAME].mp4 in file_save() (line 601 of /var/www/includes/file.inc).

This error is the same for both the Amazon S3 and Storage API modules.

It turns out that the large videos are not being uploaded to S3, which explains the error message.

I am able to upload files directly to S3 okay and I am able to upload large files to local storage just fine as well (the PHP upload limit is set well above what I'm trying). What I don't understand is what could be causing the failure with the large file sizes between Drupal and S3. Any suggestions?

As pointed out in the comments, this ended up being a PHP config issue.

While I had set the post_max_size and memory_limit arguments to 1GB, the upload_max_filesize was not set at all. Setting this to 1GB in the php.ini file as well resolved the problem.


"recommended-project" installs drupal into the /web subdirectory, but hosting solution directs traffic to webroot Per https://www.drupal.org/node/3082474 the preferred document template, drupal/recommended-project, uses a "relocated document root" for security purposes. HOWEVER, many cPanel driven hosting services mandate that the website user lands in the hosting site's public_html web root directory. I can't make it work for a website vistor.
I have researched many ways to accommodate through the use of .htaccess files and settings.php; however, nothing I've tried actually works. For example, I can land on the page, but if I try to log-in, then it gets lost. Or /web shows up in the address bar. Or people write about security concerns that are worse than not doing the relocated document root in the first place. Or...
This solution is "STANDARD", so there must be a well-researched standard way for a web user to land on the public_html, but be redirected SECURELY to the /web subdirectory.
UPDATE: this is the best solution that I have found and it seems to work safely, per https://www.drupal.org/project/drupal/issues/2612160#comment-11767977. I inserted this snippet at the bottom of /web/sites/default/settings.php file:
if (isset($GLOBALS['request']) and
'/web/index.php' === $GLOBALS['request']->server->get('SCRIPT_NAME')) {
$GLOBALS['request']->server->set('SCRIPT_NAME', '/index.php');
}

(with /web/ being the name of the subdirectory below the web root).
I also had to add this to my .htaccess file at the webroot, public_html:
# https://www.inmotionhosting.com/support/domain-names/how-to-redirect-your-primary-domain-to-a-subdirectory/

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?domain_name.com$
RewriteCond %{REQUEST_URI} !^/web/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /web/$1
RewriteCond %{HTTP_HOST} ^(www.)?domain_name.com$
RewriteRule ^(/)?$ web/index.html [L]

(with /web/ being the name of the subdirectory below the web root). Substitute your domain_name in the two places above).

When you use the drupal/recommended-project template to create a Drupal project via Composer, you can use a different directory for the server document root.
Instead of running composer create-project drupal/recommended-project my-project:

Run composer create-project drupal/recommended-project my-project --no-installation
Edit the composer.json file found in the my-project directory to replace any occurrence of web/ with public_html/
Inside the my-project directory run composer install
Copy the content of the my-project directory (including any subdirectory) into the directory containing the server document root directory

This is described in Using Composer to Install Drupal and Manage Dependencies.

If you want to modify some of the properties of the downloaded composer.json before composer install is executed, use the --no-install flag when running composer create-project. For example, it is possible that you want to rename the subdirectory 'web' to something else.
To do that:

Run composer create-project --no-install drupal/recommended-project my_site_name_dir
Change directories to my_site_name_dir and edit the composer.json file to suit your needs. For example, to change the sub-directory from 'web' to something else, the keys to modify are the 'extra' sub-keys 'webroot' and 'installer-paths'.
Run composer install to download Drupal 8 and all its dependencies.


How do I redirect to a certain page from user profile page I have created a hook and redirected the users after login from the login page to a certain page.

But when I go to /user/login after a successful login will redirect me to the user profile page (/user/1). How do I redirect a logged in user when trying to access /user/login page to a certain page that I have previously created.

Maybe this module user_default_page, might be what you are looking for.

From the description,

  Fill the 'Redirect to URL' field and 'Message' field for both Login
  and Logout fieldset.


Get taxonomy terms added to nodes I am trying to get all the taxonomy terms added to a node. How would I get only the taxonomy term values that are added to a code in a mymodule_preprocess_node hook?

Current term list:

value1 (tid=1)
value2 (tid=2)
value3 (tid=3)

Node list:

node1 has field_category = 1
node2 has field_category = 3
node3 has field_category = 1,2,3

Here is what I tried, but cannot find a way to filter and only return the taxonomy term values that are added to a node.

// Returns entire list of values, but we want only ones added to Basic page
$term_tree = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('field_category');

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

I am trying to get all the taxonomy term values, but just the entity field values.

Another example:
As with all referenced entities you can load them quickly using the referencedEntities() method.

Also, if you are not using the Devel module and Devel Kint submodule, you should check it out. You can then use ksm() to explore variables and see available methods.

function hook_preprocess_node(&$variables) {

  //make sure you have Devel module installed, then you can use ksm() to explore variables
  //ksm($variables['node']);

  if ($variables['node']->hasField('field_permit_city')) {
    //this will give you the referenced terms on the node as objects
    $term_objects = $variables['node']->get('field_permit_city')->referencedEntities();
    $term_labels = [];
    foreach ($term_objects as $term_object) {
      print $term_object->id(); //the id of the term
      print $term_object->label(); //the term title
      $term_labels[] = $term_object->label(); //build an array of term labels
    }
    //send an array of term titles over to the node twig template
    $variables['my_custom_template_variable'] = $term_labels;
  }
}

Then in your node.html.twig template you can iterate through the labels and do the stuff.

{% for term in my_custom_template_variable %}
    <p>{{ term }}</p>
{% endfor %}


How can I return literal JSON from a node as a JSON object in views json? I have a content type with a field called output. This field will contain JSON. I want to output this field as JSON using Views JSON (in Views Datasource). The problem I'm encountering is views datasource is a. wrapping my field in quotes, and b. escaping my double quotes...

    [
    {
    "content": "{\"account-confirmation\":{\"body\":\"\",...

I need it to return something like:

    [
    {
    "content": {"account-confirmation":{"body":"",...

I've tried everything I could possibly think of. Is there any way I can output the literal value of the field without wrapping the value in quotes and escaping quotes?

Views Datasource will escape the contents of any string field. If the field were an object, it would be formatted as JSON. (See: views_datasource/views/plugins/views_plugin_style_json.inc.) There doesn't seem to be any way to override this behaviour other than patching the module or using some field type that would produce this result.

I faced a somewhat related problem and had to write my own API endpoint to get the JSON as I wanted it. I used views_get_view_result() to get the raw data and rework it so that I had the correct array structure. Then I run drupal_json_encode().


Add a signature and date line to node print template? I am trying to find the cleanest way to create a signature (your written signature, not forum signatures) and date line on printable pages.

I would like to do it without actually changing template files just to keep things upgradable without going back and tampering with it (it might not be me). However, if I have to I will.

Basically I need to have a "sign and date" line that shows up only when a node is being printed not when viewed on the webpage.

Something like:

By signing this you agree to our terms of service and agree to pay the minimum service charge. ETC...

Name:________________________Date:_________

(*Comments not printed)

Obviously, this doesn't need to actually show up on any webpage but only show when someone hits CTRL+P and prints the page.

Is there a module that can do this? Or is using the print module the best way to accomplish this? If it only requires a few lines of HTML/PHP, I would rather do that than add another module. I am using Display Suite...so maybe a custom view/field could work?

Thanks

Add a code field to Display Suite that is visible on nodes, and add your HTML to the code field.

Place the field last for the specific view mode, and make sure to assign a class (or assign the class directly in the html of the code field) on outer html element.

Test that the html is displayed on node view (normal page view).

In you theme's style css (css that targets web page view) set the display of this class to none. Now it should only show for print. If it does not go into your theme's print.css file and set the display to block or whatever you prefer. If there is no print.css (highly unlikely) then just add a @media print rule to your css.


Modules to set up audio podcast functionality I am looking for modules to set up audio podcast functionality which allows playing of uploaded audio files as well as take audio source as external links like iTunes links. Any recommendations?

Take a look at FileField Podcaster

  Using Views2, this module delivers a way to podcast with nodes that
  have CCK FileFields included as RSS file enclosures. It provides a
  podcast-compatible (as determined by Apple) RSS feed, using node
  variables, getID3, filefield in cck, and filefield meta data to
  generate the RSS tags


Exporting a group of pages as a single or multiple PDF programatically I would appreciate any pointers on this problem.

I have a site which have a set of pages with a given content type, I would like to take all these pages and generate a single (if possible) PDF with the content of each page.

I'm able to write some PHP code but I'm not sure where to start or what modules would help me with this issue. I have checked other answers but they talk more about having an option to click and export a single page where I want to export a dozen/hundreds of pages.

Thanks

I think your best choice here is Views Bulk Operations, you can create a view that lists your content and add the filters and fields you want and then generate the pdf using one of the modules for that matter, such as Views PDF or the Print module. You could generate actions that will be executed by the Bulk operations, one option to do this is to use Rules and Rule sets that are automatically exposed as VBO actions.

You've got a screencast on how to do this in https://www.youtube.com/watch?v=PszjYSq7xQQ and step by step here: http://blog.hsl.virginia.edu/drupalpress/views-pdf-vbo-rule-sets-thousands-of-custom-forms/


Use AJAX without writing a module - D7 I want to use ajax to load some html from a php file. I don't want to write a module. So, here's the thing I did:

In sites/all/themes/mytheme/js/myjs.js:

$('#color_main_id a').click(function() {
  $.ajax({
    url: "get_node_details.php",
    type: 'GET',
    cache: false,
    // data: nid <--- Question#1
    data:  "color=" + this.rel,
    success: function(data, status, jqXhr) {
      $('.product-summary').html(data);
    }
  });
});

In sites/all/themes/mytheme/js/get_node_details.php I wrote some code to get a node detail with entity_load and field_view_field.

Here's the questions:

How can I pass the current node id from my js function in js file to php function in php file? (See the comment above)
In get_node_details.php I've got Call to undefined function entity_load(). How can I solved this?

Thanks

I'm sorry to say but, you are doing it wrong.

In some very few cases it could be worth not to write a module for an ajax request. The reason would be that you want to do something simple, not related to Drupal that needs to be very fast. I did this once for a site where I needed to look up if a domain name was registered or not.

In this case you are not isolated from Drupal. You need to know the context of your script (The node id) and you need to use the Drupal API's entity_load, so instead  of creating a custom PHP file and writing code in there, why not create a module which is a PHP file, only it's named foo.module, use the drupal API's to in make the ajax callback hook_menu, and add the javascript with context drupal_add_js and you will save yourself a lot of work, by doing things the Drupal way. Drupal is made it make it easy to develop stuff by creating modules, instead of adding custom PHP files, which makes things a lot more difficult to manage.

If you really wanted to do this without creating a module, you would need to bootstrap Drupal in your custom PHP file (making it pointless to use a custom php file), and add the node id in the preprocess_node hook in your theme.


Reasonable use of Custom Content Types? Should I be paranoid about creating new content types or should I create them for each new content type I come across.

My particular scenario is having several distinct blogs on my site.

Kitchen Blog
Gardening Blog
Wine Blog

I could have each of these as a standard blog type and just ask the person to remember to set the correct tags. I know I can set up a view to only show each blog with the correct content type but it all seems  a bit messy.

Alternatively I could set up a content type for each based on the blog, then I can set a custom template to look differnt for each blog.

We currently have about 10 content types on the site, could I go to 30 without worrying too much about performance or anything else?

I would not expect any performance problems on a site with 30 different content types. Nevertheless I wouldn't recommend implementing a scheme like you are intending. Should you come into the situation where you have to add a new field or change field/display settings, it will require you to go over all blog-types.

In order to simplify the creation of new content for your authors, I recommend to create shortcut links where the term-id of the blog is passed by an url parameter. You may use the Prepopulate or the Entityreference Prepopulate module, or simply alter the node_form in a custom module.