Aegir different site folder from site name When you create a new site in Aegir it creates the a directory using the sitename in the corresponding platform. So if the site name is example.com the path for the site will be /var/aegir/platforms/platform_name/sites/example.com/.

Is there a way to create the site in a different directory, like:  /var/aegir/platforms/platform_name/sites/my_awsome_path/?

Using a different sitename would be your best option. You could then add an alias for the real sitename.


Views slideshow + ajax content if there any solution for this?
I need to do views slideshow with content loading (with ajax).

Have a look at the Flex Slider module. It provides this functionality, but you might need to theme it a little bit. A screenshot similar to what you want is below. Note that you are not limited to pictures, but you can use any type of content in the display.

It is quite a hassle to start with at first, but I found these youtube videos very valuable:

Basic set-up instructions: https://www.youtube.com/watch?v=MboDby9-PCE

Theming guide: https://www.youtube.com/watch?v=-Jukg7UlSZA


Views template- how can I still use "hide if empty" behavior with my custom template? I want to customize the output of a field on my site so I made a custom views template.  Here's the code:

<?php foreach ($row->field_field_location_taxonomize_terms as $data): ?>

  <?php if ($data['rendered']['#markup'] == 'Unknown'): ?>
  <?php elseif ($data['rendered']['#markup'] == 'United States of America (USA)'): ?>
    <?php print 'USA'; ?>
  <?php elseif ($data['rendered']['#markup'] == 'United Kingdom (UK)'): ?>
    <?php print 'UK'; ?>
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>

As far as editing the output, this works fine.  However, if the field is empty, the Label (set in views) for the field will still be printed, even though I have Hide if empty checked under No Results Behavior.  If I remove my custom template, then the label is hidden when there is no value, so there must be something wrong with my template.  Any ideas?

Quick and dirty, how about turning the label for this field off in Views and add something like:

<?php if (!empty($row->field_field_location_taxonomize_terms)): ?>

Label:

<?php endif; ?>

at the top of this template?  (Changing up the HTML around Label: to match your system and t()'ing it, etc)


Command line submit node Previously I'm using combination of cURL and sed to submit to Drupal 6 website. It was very flexible but it will works if I submit very frequently. If I want to submit 2 posts in one week, it will fail because of unique number generated in Drupal system over time.

I need to know any ways (drush or any other commands) that allow me submit new post easily

Drush has a php-script argument which will allow you to run a PHP file with any code in it. Since Drush performs a bootstrap and includes the usual files required at Drupal runtime before running your script, you have all of the Drupal API available to you in your custom script.

If you need to submit any arbitrary form you can pre-populate a $form_state array and then submit the values using drupal_execute (see its API documentation). Getting to know what values to pre-populate in $form_state can be tricky, but this line can help you out:

drupal_set_message('<pre>' . print_r($form_state, TRUE) . '</pre>';

Place this in the submit handler function for to the form you'd like to programatically submit and then run through the form once in your browser. Upon submitting that form, you should get a print out the $form_state structure that you would need to mimic. Be weary on live sites though, users will be able to see that debug message too!

If you're just needing to submitting nodes then you could even use node_save() directly which is a bit simpler. How to do this is detailed on another question, How to create nodes using node_save?


Why can't I uninstall a module if I deleted a field type in a content type? I have an installation of Drupal 7. I installed Field Collection module. I created a content type (Books), added a collection type field, and created a View showing these data. Now, I deleted the collection type field in Books, and now I am not able to uninstall the module. I have run cron and cache delete to no avail. The message displayed in the modules page is the following.

Field collection

  7.x-1.0-beta11+13-dev
  Provides a field collection field, to which any number of fields can be attached.
  Requires: Entity API (enabled)
  Required by: Drupal (Fields pending deletion)

You can try this process
Log into database and ->
Select * from field_config where type = "field_collection"

Delete the rows
Same with field config instance table like
SELECT * FROM field_config_instance where entity_type = "field_collection";

Delete the rows
You can also check.

1.) first remove all the fields inside the Fields Collection.
2.) Then remove the field collection from the content type
3.) Run the Cron
4.) try to disable the module, if you cannot then Go ahead with first query statements above.

Get more details Here.


Possible display options in Drupal views I am a newbie into Drupal 7.
I am learning D7 views. I exported a view and found :

$handler->display->display_options['access']['type'] = 'perm';

with no permission array to specify the user group who can access this view.
Which user group does it take by default?
Also, in my custom view in code I have replaced it with following:

$handler->display->display_options ['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
    3 => '3',
);

It is working fine. I want to know all possible values of $handler->display->display_options this array. Where can I find all these options? Is there any documentation available for this?

Restrictions to access view can be set through Views UI to "role", "permission" or "none". See this page in Views documentation.

As for "role", those are IDs of different roles on your website. You can find those IDs in adiministration admin/people/permissions/roles - just hower over role edit link, number is in its URL.


Regarding term clarification in the database api So I was making a custom block, and implemented the build() method.

public function build() {
    $result = $connection->db_query("SELECT n.title, u.uid, n.created    FROM node_field_data n, users u WHERE u.uid = n.uid AND n.type = :type ORDER BY n.created DESC LIMIT 5", array(
        'type' => 'article',
    ));
    $content = '';
    if ($result) {
        while ($row = $result->fetchAssoc()) {
            $content .= '
' . $row['title'] . '
';
        }
    } else {
        $content .= 'No blog posts to show';
    }

    return array(
        '#markup' => '
' . $content . '
',
    );
}

So this is a pretty basic helloworld kind of example calling the database. But db_query is deprecated with the following surgestion:

     * @deprecated as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get
     *   a database connection injected into your service from the container and
     *   call query() on it. E.g.
     *   $injected_database->query($query, $args, $options);

The surgestion seemed kind of spacey not entirely knowing all of the expressions but i eventually fixed it with the following code:

    $connection = \Drupal::database();
    $result = $connection->query("SELECT n.title, u.uid, n.created FROM node_field_data n, users u WHERE u.uid = n.uid AND n.type = :type ORDER BY n.created DESC LIMIT 5", array(
        'type' => 'article',
    ));

to call the database.

My question is, \Drupal::database() is a static method, and i call it from inside of my own block, am i doing it wrong? or am i misunderstanding their meaning of dependency injection? if i had to do DI in other web programming i would find the DI container and configure it to give the database into my constructor or via a accessor method right?

Follow up questions is

What exactly constitutes my container?
What is "my service" referring to?  my module maybe?

Yes, you are doing it wrong by calling \Drupal::database.

Look at Drupal\block_content\Plugin\Block\BlockContentBlock in core as an example. The create() method gets the services and passes them to the __construct() method. That is the proper way.


node.tpl render field from referenced entity I have a node.tpl.php file where I need to output a field from an entity referenced via the entity module (a reference field). I have tried using:

print render($content['field_parent']['#items'][0]['entity']->field_main_image);

but nothing appears! I also tried this way:

$parent = node_load($node->field_parent['und'][0]['target_id']);
print render($parent->field_main_image);

I just would like to render() a related field just as I do with $content fields.

Any hints ?
Thank you

You can use https://www.drupal.org/project/inline_entity_display to do that with entity reference and field collection field.


RSS feed is not including I have an RSS feed going into mailchimp for my website (www.abercynonprimary.org.uk), feeding off the News page which is a View of teasers. The feed address is the website address with "/news.xml" on the end.

The problem I have is that mailchimp needs the tag :

<content:encoded>

somewhere in the feed, in order for me to properly use the mailchimp rss tag of full_content. At the moment, as mailchimp cant see the content:encoded html tag in my feed, it treats it as summary content, and generates a Read More in my Newsletter which doesnt work (links to nothing).

I'm just using the Views setting of Content (not fields) in my News View for the feed (see screen shot attached). I have also attached the note back from Mailchimp Support.

Mailchimp Support - *"I checked the feed for the your account and it appears that there's "content:encoded" within the feed, but it is not explicitly spelled out in the tags as

<content:encoded>

In order for MailChimp to read this as expected, this tag needs to display exactly as stated in the Merge Tags article on the feed.
Once these tags are added, things should work as expected and you would only need the default "read more" link that comes with the Merge tag. "*

can anyone help me get my feed to show full content instead of defaulting to summary, and therefore causing Mailchimp to generate a Read More which doesnt work.

thanks

You can use Views RSS: Content Elements module, I'm using it and works well...


How to Embedd youtube video in body field (converts URLs into embedded players)? Is there a simple way to insert youtube video in body field like other CMS where you copy a youtube link in the article body and it is automatically converted into a video player in front end.

I’ve search here and some topics talk about modules but there are not drupal 8 yet.

Is there a module that can do that or Drupal 8 maybe can do that natively ?

I’ve found and tested this module which do excaly what I want :

Url to Video Filter

  This module adds a new input filter that automatically converts URLs
  for various video sharing websites into embedded players into the
  text.

Here is a screenshot of the CKEditor filter :

I’ve tested this module on multiple sites and it works very well.

Currently this module supports the following services : YouTube / Vimeo

EDIT
Now, It also supports Youtube URL with parameter like ?rel=0 (rel=0 is used to disable related videos shown at the end of a video)


How do I convert "entity:node/9 in a link? I need to get some values from a custom block I've created, and I am using the following code.

// Get the block
$block = \Drupal\block\Entity\Block::load('hightlight');

// Get the block content
$uuid = $block->getPlugin()->getDerivativeId();
$block_content = \Drupal::service('entity.repository')->loadEntityByUuid('block_content', $uuid);

// Get the field value
$field = $block_content->get('field_link')->getValue()[0];

The problem is that the field contains entity:node/9. Is it possible to convert that value in a link?

This is the content of the field.

You have to rewrite

$value = $block_content->get('field_link')->getValue()[0];

to something like this:

$value = $block_content->get('field_link')->first()->getUrl()->toString();

See What is the correct way to get the link url?


How to implement a notifications on my webpages while any data insertion or updation occured on my custom tables How to implement a notifications on my web pages while any data insertion or updation occured on my custom tables.

My requirement is for an auction website where once an user places a bid, then all the  other logged in users in that region should get the notifications.

You need to accomplish with three module and rules, private message and custom module.

rules provide event, condition and action through which you need to set, events supports CRUD. Condition provides you to check condition has been fulfill and Event sends you private message to groups or personal mail / text message.

Private message provides you send bulk message / mail through rules. Message itself can be thread.Private message has feature to count unread message to particular user.

Custom module to create event, conditions and actions for rules to custom table.


Landing Page Based on Role? Use Case - I've got several Dashboards (some custom View pages) in the site. Depending on the Role associated with a User, I want to direct them to thier respective Dashboard.

So an Editor would go to the Editor Dashboard, a Contributor would go to a Contributor Dashboard, etc. after they login.

(I'm using the OpenPublic distro)

You can redirect user after checking their role(by using below PHP snippet)

<?php $GLOBALS['user']->roles; ?>

Your code will look something like this:

<?php
if($GLOBALS['user']->roles == 'editor') {
  drupal_goto("dashboard_editor"));
}
?>

Note: this will work only when a user has single role associated with him.


How to receive JSON data in controller with Drupal 8? I'm using AngularJS one of my module's settings page, so I have a javascript object in client side as a model. Could anyone help me please, how to catch this data in a controller if I send it as JSON with ajax?

This is the model I assembled is angular:

var model = {
  title: 'This is a title',
  url: '/random-custom-url',
  description: 'little descrp',
  blocks: [
    {id: 1, name: 'block1', description: 'blockdecrtiption1', terms: [{"tid":"1","name":"term1","vid":"tags"}]},
    {id: null, name: 'block2', description: 'blockdecrtiption2', terms: []},
    {id: 3, name: 'block3', description: 'blockdecrtiption3', terms: []}
  ]
};

I'd like to "catch" it in a controller's function(as a php associative array), so then I can process it and save to database(I have some own table in the database, created in the module's hook_schema()). What's the right route setup for this? In the controller's function how can I get the data posted with ajax and how to convert it to associative array?

Thanks a lot!

In case you want to do it more the D8 way here is a rough outline what you could do, which allows you to be flexible without the requirement to do everything in your own. A proper rest integration requires you to work with all the different HTTP status codes, header fields etc. Rest takes partly care of that

The rest module provides a generic abstraction for REST, not tight to entities in the first place. Entities are just one example.

First you should register your rest plugin, like every other plugin:

namespace Drupal\pinguin\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;

/**
 * Provides a resource for database watchdog log entries.
 *
 * @RestResource(
 *   id = "pinguin",
 *   label = @Translation("Example rest plugin for pinguins"),
 *   uri_paths = {
 *     "canonical" = "/pinguin/{id}"
 *   },
 *   serialization_class = "Drupal\pinguin\PingInterface"
 * )
 */
class Pinguin extends ResourceBase {
}

If you do an updating request like PUSH or UPDATE, it uses the serializer component to convert your data into some php array/ object.
It uses two steps in order to do that. First the data incoming is decoded,
for example from JSON into a PHP array. The next step is the denormalization.
This step converts the denormalized data (PHP array) into a domain object,
for example the Ping (a single pinguin).

The first step is to specify the resulting class in the annotation (see above).
To register a new denormalization you add the following entry into your .services.yml:

services:
  pinguin.denormalizer.pinguin:
    class: Drupal\pinguin\normalizer\PinguinDenormalizer
    tags:
      - { name: normalizer }

This normalizer specifies which interface it can convert to:

<?php

namespace Drupal\pinguin\normalizer;

use \Drupal\serialization\Normalizer\NormalizerBase;

class PinguinDenormalizer extends NormalizerBase {

   // IMPORTANT
   /**
    * The interface or class that this Normalizer supports.
    *
    * @var array
    */
    protected $supportedInterfaceOrClass = array('Drupal\pinguin\PingInterface');

    /**
    * {@inheritdoc}
    */
    public function denormalize($data, $class, $format = NULL, array $context  = array()) {
      // Validate the data.
      if (empty($data['location']) || $data['location'] == 'northpole') {
        throw new \UnexpectedValueException("this can't be real pinguins");
      }

      // create the domain object.
      return new Ping($data['name'], $data['location'], $data['family']);
    }
 }

Once this serialization is done, it calls a method named after the HTTP method
on the plugin class, so for example "post". There you can do whatever you want.

<?php
class Pinguin extends ResourceBase {
  public function post(PingInterface $ping) {
    // deal with the data, save it for example.
    $ping_storage->save($ping):
  }
}

The advantages of these abstractions are that you don't have to deal with the incoming format but on the other hand it needs a bunch of code to get started.


Display Drupal taxonomy tree I sucessfully printed the whole taxonomy tree using this code.

$voc = taxonomy_vocabulary_machine_name_load('product_sub_categories');
$tree = taxonomy_get_tree($voc->vid, 0, NULL, TRUE);
foreach ($tree as $key => $term) {
  print $term->name."
";
}

Now I want to separately print parent and child in order to custom theme them, because I already have a mark-up in which parent has separate
 Parent terms
 and children has separate
Child terms
.

How should I do this?

I have done it using taxonomy_get_children(), but it is giving me the children of parent of the taxonomy whose ID is 1.

child1
child2
child3

This is what I need, but now I want to get the children of parent
child1. I tried to get them by reusing the above function but it give me this.

child1

children of child1

child1
child2
child3

Use nested foreach like below.

$terms = taxonomy_get_children(1);
foreach ($terms as $term) {
  $items[] = $term->name;
  $child_term = taxonomy_get_children($term->tid);
  if (!empty($child_term)) {
    foreach ($child_term as $child) {
      $items[] = $child->name;
    }

  }
}
return theme('item_list', array('items' => $items));


How to replace classnames in sub theme How to replace two classnames by writing a function in template.php

The two classnames given are:

comment-add

and

comment-comments

Generally this is a matter of figuring out which preprocess function or functions are setting those classes and then implementing those preprocess functions within your own theme and modifying the $variables['classes_array'] variable to meet your needs.

Without knowing what theme you're using as a base theme I can't say for sure how this is being done. But using the following steps you should be able to figure it out.

Figure out which template file (*.tpl.php) file contains the markup where the classes are being printed out, and note the name of this file. Example, 'comment-wrapper.tpl.php'.
Working backwards up the chain you should be able to find the preprocess function that's setting these classes.

YOURTHEME_comment_wrapper_preprocess()
BASETHEME_comment_wrapper_preprocess()
template_comment_wrapper_preprocess()

This will at least confirm that you're on the right track, and allow you to see in what context those classes are set and what other classes may be set.

Implement HOOK_comment_wrapper_preprocess() in your own theme. (Comment wrapper being the example here, you'll need to know the appropriate template file that's being used to know which preprocess function to implement.)
Modify the $variables array inside your template file to change the classes.

Here's some additional information about preprocess functions: https://www.drupal.org/node/223430


How do I show username & email address of currently logged in user on a page he is viewing? I want the logged in user to see his name and email address in the text of a paragraph on a given page, how to I extract that information from the currently logged in users account, and show it in the body of the page?

You can create a block with the PHP code format (don't forget to activate the PHP filter module) and put inside:

<?php
  //Retrieve the global variable for the connected user
  global $user;
  echo 'Hello ' . $user->name;
  echo 'Your email is :' . $user->mail;
?>

Then you set up this block to show only for authenticated users and you place it in a region.

See Drupal global variables documentation.


Does Drupal strip out style and span tags? I was trying use span and style tags in pages, rather than in CSS and it seems that Drupal is configured to strip them out whether the input format is Filtered HTML, i.e. they are applied to Full HTML.

Is that something which can be fixed only by editing the core files, or are the some modules or settings in Drupal's admin settings that can override that?

Go to Configuration -> Content Authoring -> Text formats. Here you can configure what tags are allowed.

All unallowed tags are stripped out,  is always stripped out.

Check out https://www.drupal.org/project/wysiwyg_filter for more advanced filtering.


How to remove modules via ftp? I need to know how to remove modules via ftp, i activated some modules, and now im getting constantly errors like

  Fatal error: Call to undefined function views_include() in /home/a7898297/public_html/sites/all/modules/eva/eva.module on line 113

so how can i remove custom modules?

You need to disable the module on http://example.com/admin/modules first. That should take care of your error messages.

If your administration interface is not accessible - caused by the error message - you could access the database directly and disable the module in the system table - as suggested by Mołot and outlined in https://drupal.org/node/157632.

Additionally to disabling the module, you should also uninstall it - which will remove any configuration and data associated with this module from the database: http://example.com/admin/modules/uninstall (at least it should, if it is properly written).

Now, you can safely remove the module from the modules directory, if you want to. Since the module is disabled and uninstalled, it will not interfere with your Drupal installation, however, it is advisable to clean up the modules directory, and move the module to a location outside the webroot - to avoid issues if the module has security holes and the web-server is (mis)configured to allow direct execution of modules.

Before you do all this, I would save a backup of the database and the custom module, in case the functionality and data might be needed after all.

You can of course do all of this also on the command line using drush - since you asked about ftp, I assume you do not have ssh access.


Can't get Flagging API to accept POST request trying to use the REST API that comes with the flagging module on Drupal 8.

I've enabled and secured the endpoint that comes with the module: /entity/flagging: POST

I'm nearly there, but following examples from earlier releases don't seem to work; What I'm trying to achieve is adding a flag for one user (1) for one content item (34). I got this far on the POST:

{
"entity_id":[{"target_id":34}],
"flag_id": "my_flag",
"uid": [{"target_id": 1 }],
"flag_action": "flag"
}

But I get this error:

InvalidArgumentException: Field flag_action is unknown.

Without the flag_action argument though I get:

{"message":"You are not authorized to create this flagging entity of bundle my flag."}

I'm not sure how I can not be authorised i'm sending credentials of the sys admin (using basic_auth).

Anybody know how I can add or remove a single flag from an entity using the Rest API?
thanks!

I tried to create a flag, however, I had the same results.

To solve this, I have created a module.

note: to make tests I installed the "Flag Bookmark" module.
file test_api.info.yml.

    name: Test API
    type: module
    description: Custom RESTful API module with GET/POST/PUT/DELETE etc.. method examples.
    author: Minnur Yunusov
    core: 8.x

file test_api.routing.yml.

# Test API endpoints

  test_api.get:
  path: 'my-api/get.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::get_example' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

test_api.put:
  path: 'my-api/put.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::put_example' }
  methods:  [PUT]
  requirements:
    _access: 'TRUE'

test_api.post:
  path: 'my-api/post.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::post_example' }
  methods:  [POST]
  requirements:
    _access: 'TRUE'

test_api.delete:
  path: 'my-api/delete.json'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::delete_example' }
  methods:  [DELETE]
  requirements:
    _access: 'TRUE'

we create the following directories and file TestAPIController.php
src/Controller/TestAPIController.php

<?php

/**
 * @file
 * Contains \Drupal\test_api\Controller\TestAPIController.
 */

namespace Drupal\test_api\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\user\Entity\User;

/**
 * Controller routines for test_api routes.
 */
class TestAPIController extends ControllerBase {

  /**
   * Callback for `my-api/get.json` API method.
   */
  public function get_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'GET';

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/put.json` API method.
   */
  public function put_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'PUT';

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/post.json` API method.
   */
  public function post_example( Request $request ) {

    // This condition checks the `Content-type` and makes sure to
    // decode JSON string from the request body into array.
    if ( 0 === strpos( $request->headers->get( 'Content-Type' ), 'application/json' ) ) {
      $data = json_decode( $request->getContent(), TRUE );
      $request->request->replace( is_array( $data ) ? $data : [] );
    }

    //get value json
    $flag_id= $data["flag_id"];
    $entity_type= $data["entity_type"];
    $entity_id = $data["entity_id"];
    $uid= $data["uid"];
    $created = REQUEST_TIME;

    //get user
    $user= User::load($uid);

    //get field uuid
    $user_uuid= $user->get('uuid')->value;

    //add entity_id to the field field uuid (unique value);
    $user_uuid= $user_uuid.'-'.$data["entity_id"];

    $fields=array(
      'flag_id' => $flag_id,
      'uuid' =>$user_uuid, //unique value
      'entity_type' =>$entity_type,
      'entity_id' => $entity_id,
      'uid' =>$uid,
      'global' =>0,
      'created' => $created
    );

    if ($data["flag_action"]=='flag') {

        //verify if exists record
        $sql="select * from {flagging} where entity_type ='$entity_type' and entity_id=$entity_id and flag_id='$flag_id' and uid=$uid ";
        //execute query
        $connection = \Drupal::database();
        $result = $connection->query($sql);
        $result=$result->fetchAll();

        //if not exists record, create flag
        if (count($result)>0) {
          $response['¿Flag exists?'] = 'true';
        }
        else {

              $resultado= db_insert('flagging')
              ->fields($fields)
              ->execute();

              $response['newflag'] = $resultado;

        }

        $response['data'] = $data;

    }

    else if ($data["flag_action"]=='unflag') {

        //verify if exits record
        $sql="select * from {flagging} where entity_type ='$entity_type' and entity_id=$entity_id and flag_id='$flag_id' and uid=$uid ";
        //execute query
        $connection = \Drupal::database();
        $result = $connection->query($sql);
        $result=$result->fetchAll();

        //if exists record, delete flag
        if (count($result)>0) {

          $num_deleted = db_delete('flagging')
          ->condition('entity_type', $entity_type)
          ->condition('entity_id', $entity_id)
          ->condition('flag_id', $flag_id)
          ->condition('uid', $uid)
          ->execute();

          $response['¿Delete flag?'] = 'true';
        }
        else {

          $response['¿Flag exists?'] = 'false';

        }

        $response['data'] = $data;

    }

    /*

    //send json example
    //change "bookmark"  by "my_flag"

    {
      "entity_id":31,
      "entity_type":"node",
      "flag_id": "bookmark",
      "uid": 1,
      "flag_action": "flag"
    }

    */

    return new JsonResponse( $response );
  }

  /**
   * Callback for `my-api/delete.json` API method.
   */
  public function delete_example( Request $request ) {

    $response['data'] = 'Some test data to return';
    $response['method'] = 'DELETE';

    return new JsonResponse( $response );
  }

}

Note: in the tests change "bookmark"  by "my_flag"

test:
url: http://jeremiselxi.260mb.net/drupal8/my-api/post.json
method:post;
headers:
Content-type: application/json
X-CSRF-Token: token()

note: this token is obtained through the GET method to the url
localhost/session/token

create flag

{
  "entity_id":34,
  "entity_type":"node",
  "flag_id": "bookmark",
  "uid": 1,
  "flag_action": "flag"
}

result:

200 OK

Headers
{
  "newflag": "22",
  "data": {
    "entity_id": 34,
    "entity_type": "node",
    "flag_id": "bookmark",
    "uid": 1,
    "flag_action": "flag"
  }
}

note: If the flag does not exist, then create the flag

"newflag": "22"

else

"¿Flag exists?": "true"

create unflag

{
  "entity_id":34,
  "entity_type":"node",
  "flag_id": "bookmark",
  "uid": 1,
  "flag_action": "unflag"
}

result:

200 OK

Headers
{
  "¿Delete flag?": "true",
  "data": {
    "entity_id": 34,
    "entity_type": "node",
    "flag_id": "bookmark",
    "uid": 1,
    "flag_action": "unflag"
  }
}

note: If the flag exists, then delete the flag

"¿Delete flag?": "true"

else

"¿Flag exists?": "false",


How to apply a theme function/template to my form I think theme_form() is responsible for rendering forms! I want to change the look of a form, a lot. I think just instead of theme_form I can use my custom theme function/template file.

I can use hook_form_alter to change any form's structure using my module. Now my question is, how do tell the form to use a theme function/template I've created?

Is there a #theme property (or something like that) available for forms, which I can set to my theme function/template file?

P.S. I checked out this but I need more explanation, when the case is: I'm trying to theme a form defined by another module/core modules.

Is there a #theme property (or something like that) available for forms, which I can set to my theme function/template file?

Yes there is. Take a look at the #theme key in the Form API Reference. Take a look at the code for theme_form() for the default implementation.


Set the menu link as disabled by default When I create a new node its menu link is enabled by default. I would like to enable it manually only in case if I need.
Is there a way to set the checkbox in menu tree as uncheked by default?

Have a look at this module, I guess that is what you want.
http://drupal.org/project/default_menu_link
Some details from the module's project page:

Provides the user with a check box on all content types to set the "provide a menu link" value to true by default.
This is basically a nice way to ensure the menu system is adhered to by all content authors.
There is a similar module called menu_force that does just that. Whereas Menu Force mandates menu assignment, Default Menu Link merely changes the status of "Provide a Menu Link" to true. The user can still create content and choose to un-check this box. However, the default state (on node creation) will be true, and as long as you've set a default menu parent item, all content will be filed under that parent.


Organic Groups - How to disable "Groups" Tab I enabled OG and now I have a tab that lists all "public" groups if you're not registered, and it'll show the groups you belong to if registered. What's the best way to get rid of the groups tab for Anonymous users? It can be visible to authenticated users.

I had a similar problem with OG Extras installed, the view and members tab would show even when a site visitor wasn't logged in, I wanted it hidden for non registered users or non-admin users.

To stop it showing I edited the view 'OG Extras group members (User)' made sure I had the Page, not the block of the view selected and changed 'Access:' for the 'tab menu' to Role | administrator, this means that when logged in as an administrator I can see the desired tabs but when logged out the tabs are hidden.


Commerce PayPal wps sends to and gets data from sandbox but no payment method available I'm on localhost without ssl and fix IP.
I can checkout with PayPal WPS, go to sandbox, confirm as buyer, and when I click in the sandbox I go back to my testsite after confirming to leave SSL.

In my logs I can see (watchdog) that the function commerce_paypal_wps_redirect_form_validate() works fine and gives me a lot of data from my client and the transaction.

In my sandbox seller account I can see the payment is accepted and I earned my bucks ;)

Here the problems:

The orders overview at admin/commerce/orders only shows pending orders instead completed although the posted data from paypal show

  [payment_status] => Completed

Next when I go to the payment of any order I see that there's no payment method available although payment is done per WPS.

admin/commerce/orders/1/payment:

  No payment methods available to add payments.

I believe that these are the reasons why my hook I want to use is not called??
I want to change the user role after the transaction is completed so I took hook_commerce_paypal_ipn_process() without success.

Does anybody has any ideas??

My modules: commerce 7.x-1.11+52-dev, PayPal 7.x-2.3+4-dev, Commerce (Tax)7.x-1.0-rc2, rules 7.x-2.9

PayPal WPS has to send IPN to your Drupal website(application) in order for Drupal to process and store payment for the order. When IPN is received and payment transaction is registered in db you can then run some logic (via Rules) to set the order status accordingly and do other things.

You are not receiving IPN from PayPal because your website is on the local host. You have to host your website on live domain(sub domain, domain sub folder , etc.) so that PayPal server can ping yours and send you data.

Read your question a few more times, and here's more thoughts:

You may be messing up PayPal WPS module's logic by using that hook in a wrong way. Why not assign the role via Rules?


Overwrite field description in an image widget I have an image field (multiple).

In the node form, the ImageWiget has a process method that adds previews and form fields for images that have already been uploaded.

The description for the title tag is hard-coded on line 278: '#description' => t('The title is used as a tool tip when the user hovers the mouse over the image.'). We are actually showing the title as a caption and not a tooltip.

How can I override the description?

Using hook_field_widget_form_alter You can do this:

function MYMODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  if ($context['field']['field_name'] == 'field_image_top') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element

      $element[$key]['#process'][] = 'MYMODULE_image_field_widget_process';
    }
  }
}

function MYMODULE_image_field_widget_process($element, \Drupal\Core\Form\FormStateInterface $form_state, $form) {
  // Change the title field label and description

 $element['title']['#description'] = 'SOME NEW DESCRIPTION HERE.';
 return $element;
}


Drupal 7 localhost is shortening css strings My local copy of a Drupal 7.19 site has been cutting the css strings and I cannot figure it out.  I have checked my .info file, settings file and tried disabling modules, all to no avail.  It continues to render css like this:

<link type="text/css" rel="stylesheet" href="http://localhost/rwr/" media="all">

Where is should be

<link type="text/css" rel="stylesheet" href="http://localhost/rwr/sites/all/[themename]/css/global.base.css" media="all">

My remote site is generating @import calls to the css, but my localhost is not.

Feel free to link me to an existing solution for this.  I have been googling and reading for hours, but I cannot find a solution.  Thank you!

same issue, to me helps:

visit: admin/config/development/performance

turn on "CACHING" for:
 Cache pages for anonymous users

turn off all "BANDWIDTH OPTIMIZATION"
 Compress cached pages.
 Aggregate and compress CSS files.
 Aggregate JavaScript files.

Then Clear all cahces

That fix my issue with css ;)


Image gallery with original image proportions I was looking for a module a tutorial how to create an image gallery in drupal 7 where when you go in album all images are not cropped in rectangulars and displayed in a table, but remain with their natural proportions and displayed in columns as I provided a print screen below(tumblr theme), each image has a unique page with it's caption. I am not sure what is the particular term for such way of displaying images is called so I am asking here

You most probably want the functionality provided by Masonry API and its sub-modules: Masonry Views and Masonry Fields.

  Masonry is a dynamic grid layout plugin for jQuery. Think of it as the
  flip-side of CSS floats. Whereas floating arranges elements
  horizontally then vertically, Masonry arranges elements vertically,
  positioning each element in the next open spot in the grid. The result
  minimizes vertical gaps between elements of varying height, just like
  a mason fitting stones in a wall.

In the view you will specify a image formatter that only sizes on the width so that the height remains proportional.


Create a distribution How is it possible to create a new Drupal distribution based on site that I already built? I've already exported the content types using

drupal config:export:content:type MYCONTENTTYPE --module MYMODULE

Drupal console has the following function which may be useful.

https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/generate-profile.html

This following link leads to the current drupal.org documentation on creating a Drupal 8 distribution. It looks like it only shows how to create a distribution manually though.

https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile

I was hoping that there was something in Drupal console or Composer that would take all the information in my current database and create an installation profile out of it.

EDIT

The Drupal Profile Builder seems wonderful but current only supports D7.

Actually, the drupal.org link above will work. At the bottom of the page there is a section that discusses bringing configuration files into the install directory. You can use Drupal Console (DC) to create the configuration files like this:

drupal config:export

It will put all the configurations in the public folder unless you specifiy a directory.

https://hechoendrupal.gitbooks.io/drupal-console/content/en/commands/config-export.html

https://www.drupal.org/docs/8/creating-distributions/how-to-write-a-drupal-8-installation-profile

EDIT

Also, I've added a Drupal.org page has a lot of resources for creating a distribution. On the sidebar it lists common make errors and other useful links.

If you check the release download page of your distribution, you can find the Drupal packager error messages if you send a distribution for packaging.

A lot of this needs to be learned by trial and error. I've spent a fair amount of time on this and still haven't gotten the hang of things.

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

EDIT

Also, there appears to be something called drupalorg_drush. It's a drush extension that helps build a replica of what drupal.org would do with your distribution files should you upload them to your project's Git repository. However, at the time of this writing, Drupal 8 version is not available.


Adding Search Block to Bootstrap 3 Navbar The search block using the twitter bootstrap 3 theme doesn't show inline with the rest of the navbar. What is the trick to get this to show inline?

I have tried to add it to the page.tpl.php without success.

Any ideas?

EDIT:::

I've added this to the template:

           <?php if (!empty($page['searchblock'])): ?>
            <?php print render($page['searchblock']); ?>
          <?php endif; ?>

However, that doesn't seem exactly right for this bootstrap theme. In the bootstrap code one wraps the search like so:

<form class="navbar-form navbar-right" role="search">

    <input type="text" class="form-control" placeholder="Search">

  <button type="submit" class="btn btn-default">Submit</button>
</form>

Do I need to modify the default search block template? Thanks for any help to my ignorance as i learn this system. Really digging Drupal 7 right now!

I had the same feature request.
In mytheme/template.php I've added

/*
 *  Preprocess page.tpl.php to inject the $search_box variable.
 */
function mytheme_preprocess_page(&$variables){
  $search_form = drupal_get_form('search_form');
  $search_box = drupal_render($search_form);
  $variables['search_box'] = $search_box;
}

/*
 *  Form alter to add missing bootstrap classes and role to search form.
 */
function mytheme_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#attributes']['class'][] = 'navbar-form';
    $form['#attributes']['role'][] = 'search';
  }
}

In mytheme/templates/page.tpl.php I've added

  <?php print $search_box; ?>

After the

 div.

There still was a problem with a float:left applied to secondary links menu (instead of the proper boostrap navbar-right.
So, for a quick workaround, in mytheme/css/style.css I've added:

@media(max-width:768px){
  ul.secondary{
    float:none!important;
  }
}


How does Acquia Dev Desktop create the connection to the database? I am using Acquia Dev Desktop 2 on my windows 10 PC in order to develop Drupal 8 websites.

As far as I know, every Drupal website requires a connection between its files and the database
which is accomplished by using the following code in the setting.php file.

$databases = array(
  'default' => array(
    'default' => array(
      'database' => 'databasename',
      'username' => 'sqlusername',
      'password' => 'sqlpassword',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
    ),
  ),
);

I downloaded Drupal 8 and I imported it in Acquia Dev Desktop 2 using the
Import local Drupal site option.

The site is correctly imported and installed; a new database has been created.

I cannot see the above database connection code anywhere in the settings.php file.

I noticed, however, that the following code is added to the bottom of the setting.php file.

// <DDSETTINGS>

// Please don't edit anything between <DDSETTINGS> tags.

// This section is autogenerated by Acquia Dev Desktop.

if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_sitename_dd.inc')) {
   require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_sitename_dd.inc';
}

// </DDSETTINGS>

How does Acquia Dev Desktop 2 create the connection between the site's files and the database without using the common database connection code shown above?

When moving my website from the local development server (Acquia Dev Desktop) to a remote server, I must create a connection to the database. Is it safe to delete the code between the <DDSETTINGS> tags added by Acquia Dev Desktop 2*?

Thank you all for your help and point me to the right direction !

I will give a detailed explanation because i believe this will benefit plenty of people with common error as mine !

Acquia Dev desktop 2, while creating/importing you website, will create a hidden file (loc_your_site_dd.inc) within its folders where the database connection code is located and then it will refer to that file by adding at the bottom of your setting.php file, few lines of codes similar to:

// <DDSETTINGS>

// Please don't edit anything between <DDSETTINGS> tags.

// This section is autogenerated by Acquia Dev Desktop.

if (isset($_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR']) && file_exists($_SERVER['DEVDESKTOP_DRUPAL SETTINGS_DIR'] . '/loc_sitename_dd.inc')) {
require $_SERVER['DEVDESKTOP_DRUPAL_SETTINGS_DIR'] . '/loc_sitename_dd.inc';
}

// </DDSETTINGS>

Actually this is not a problem and this is how Acquia Dev desktop handle the database connection and other configuration codes.

However, if you are using Drush with your Drupal 8 website but you are using it from a Git Bash instead of using the built-in cmd inside Acquia Dev Desktop, you will be facing a problem similar to this one:

The drush command 'XXX' could not be executed.
[error] Drush was not able to start (bootstrap) the Drupal database.

The problem here is that Drush won’t be able to find the  which it was added to your sites settings.php file and so it will not be able to find a connection to the database and in result will display the above error.

SOLUTION:

The best solution here is to find the hidden file created by Acquia Dev Desktop which is usually in Windows is located at (*C:\Users\username.acquia\DevDesktop\DrupalSettings*) and copy and pasted all of its contents to your settings.php file and then from inside the settings.php file, delete the code  codes added by Acquia Dev desktop.

Doing so, now Drush will be able to find a connection to the database and all will be working as expected.


How to add a select menu to a form with the ability to insert new values? I need to add a select field to a form, but I also want the ability to add more values to select field later on. How can I accomplish this in Drupal 7?

I heard (read) some place that you can accomplish something like this with a custom content type? but isn't there any better method to do this?

As a first step, You can use Select or Other module to collect values from user if not available...

Project page says

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

As a second step, You need to read this values on hook_node_presave and insert it into select list available options using code like below..

// Get the field info
$info = field_info_field('field_some_field');

// Get a reference to the values
$values = &$info['settings']['allowed_values'];

// Manipulate the values in some way, e.g.
$values['new_value'] = 'New Value';

// Save the field
field_update_field($info);


How to update the below action for each view bulk operations? It is for Drupal 7 I wants to delete the below folder every time only on each view bulk operations but currently it is getting deleted for each node selected in VBO. I am executing this action in rules module.
Please let men know how to run this only once for each VBO.
$pdfdir="/var/www/websites/test/sites/default/files/pdffolder";
$directory = escapeshellarg($pdfdir);
shell_exec("rm -rf $directory");

This is the code executing via Rules Module.

If you define a VBO event in rules that triggers on every node save, then it will happen once per node saved by VBO.  VBO takes all the selected items in a view and runs them through a batch process, performing operations per item.
So, you need to change the rule event to something else.
If the goal is to run the code once per time, here is one lazy way to do it:

Set the event to be "page is viewed". (doing this from memory, actual event name is different)
Set a condition on the rule to be the path of the VBO page.
Use your execute PHP code as the action.

This will cause the code to execute whenever the VBO url is accessed.  This is not exactly what you asked for, but hopefully this gives you an idea of how to use events and conditions in rules to get what you want.


How to override "Create @bundlename" text? I'm using String Overrides module to override some strings on my site. I could override some strings like

"Performance" to "Clear"   (admin/config/development/performance)

"Content" to "List of Nodes" (admin/content)

But it doesn't override "Create @bundlename" strings like

"Create Article" to "New Article".

When I navigate to /node/add/article it's still showing Create Article as title of the 'Node add form'.

I've cleared cache, but still not working.

Any suggestions?

You can try using Node Add title module ...

  Above module allows you to configure the title of the Node Add pages
  and the Node Editing pages.

  The default title of the page where users create new nodes is
  constructed by Drupal in a dynamic way that not always looks good. By
  default Drupal concatenates the word Create and the name of the
  content type. The result could be something like "Create Basic page"
  or "Create article". This is not always acceptable.

  With this little module you can replace Drupal's default concatenated
  Node Add page title and the Node Editing page title with a title of
  your choice for every content type.

  After installing this module you will see the following two new fields
  at the bottom of the content type configuration form:

  Node Add page title Node Edit page title Use these two new fields for
  overriding the titles of the new node creation pages and the node
  editing pages.

PS : Module is in Dev Version.... Test before you use..

If you are interested to change same using code you can use drupal_set_title

function mymodule_form_alter(&$form, $form_state, $form_id) {
    if($form_id == 'mynodetype_node_form'){
         drupal_set_title('My new title');
    }
}


Hyphenated nodeName or DTD nested in XML causes Feeds XPath Parser failure I am using Feeds and Feeds XPath Parser.

I have an XML source like this.

<xml>
  <records>
    <record>
      <EAC-CPF xmlns:eac="http://jefferson.village.virginia.edu/eac" xmlns:edit="http://nla.gov.au/nla.party" xml:id="_cb2bf3c2-b54c-42c3-a890-048c06549e45#10" xsi:schemaLocation="urn:isbn:1-931666-33-4 http://eac.staatsbibliothek-berlin.de/schema/cpf.xsd">
        <cpfDescription>
          <identity>...</identity>
        </cpfDescription>
      </EAC-CPF>
    </record>
  </records>
</xml>

Which I am trying to import with field settings like

EAC-CPF/cpfDescription/identity/...

With debugging turned on I can see that fields outside of the EAC-CPF node are correctly found whereas those within are not. I've tried various escaping of EAC-CPF but I'm wondering if its a limitation of XPath in PHP or the Parser module. Or is it the nested namespace and schema?

There are 2 errors regarding the xml:id and xsi:schemaLocation, but they are not fatal. I'm guessing the xsi namespace is defined previously.

There's nothing wrong with nested namespaces.

Is there a default namespace declare somewhere passed the root? That could be because of https://drupal.org/node/1220834.

The hyphen in EAC-CPF is not causing the problems.

Remember that if elements have a namepsace, the namespace must be present in the XPath query.


Is it possible to write test against the current database? I'm building some modules onto an existing and somewhat active site. From my understanding, SimpleTest creates a new, temporary database and effectively reinstalls a copy of Drupal.

However, I'd like to take over some current items for the existing site such as taxonomy and content types and test against this data.

Do I have to manually do this all in setup()? Or is there a way to clone or import existing tables into the testing database that SimpleTest sets up?

The testing environment is by default completely separated from your website, so module testing is in no way affected by the environment. However you might be able to switch the database. There is this article about testing on the live database: http://www.codesidekick.com/blog/break-out-simpletest-sandbox. Basically you override some variables during setup and teardown in a class extending DrupalWebTestCase:

/**
 * @file
 * Common testing class for this Drupal site.
 */
abstract class SiteTesting extends DrupalWebTestCase {

  /**
   * Overrides default set up handler to prevent database sand-boxing.
   */
  protected function setUp() {
    // Use the test mail class instead of the default mail handler class.
    variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
    $this->public_files_directory = $this->originalFileDirectory;
    $this->private_files_directory = variable_get('file_private_path');
    $this->temp_files_directory = file_directory_temp();

    drupal_set_time_limit($this->timeLimit);
    $this->setup = TRUE;
  }

  /**
   * Overrides default tear down handler to prevent database sandbox deletion.
   */
  protected function tearDown() {
    // In case a fatal error occurred that was not in the test process read the
    // log to pick up any fatal errors.
    simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);

    $emailCount = count(variable_get('drupal_test_email_collector', array()));
    if ($emailCount) {
      $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
      $this->pass($message, t('E-mail'));
    }

    // Close the CURL handler.
    $this->curlClose();
  }
}

Then in the test, make sure to extend your newly created class:

class SiteTestingHomePageTest extends SiteTesting {
  ...
}

I have never tried this, and please be aware that depending on the test, they might alter the live database (if you add a node in the test, it will show up on the site), but it might be what you are looking for. Make database backups and remove all created entities in the end of the test.

If you do not want to affect live data, you will have to add the content types and taxonomy terms manually.


Migrate address field I am currently searching for a example to migrate data into an address field in Drupal 8 without any luck for now.

Has someone a hint for me on how to map the fields?

I tried the following:

my.migrate.yml file:

'field_date_address/address_line1': date_tmp_address_address_line1
'field_date_address/locality': date_tmp_address_locality
'field_date_address/postal_code': date_tmp_address_postal_code

Callback:

$row->setSourceProperty('date_tmp_address_address_line1', 'Teststreet 18');
$row->setSourceProperty('date_tmp_address_locality', 'Test locallity');
$row->setSourceProperty('date_tmp_address_postal_code', '12345');

I was able to solve it :-)

This helped me:
https://www.drupal.org/node/2594631#comment-11322879

It is important to map all addressfield subfields, otherwise it will not work.


Add markup before form output for user-login I've created a template override for the user login form (user-login.tpl.php) and want to put some content before the form's elements (e.g, header text and copy). Anything you add in user-login.tpl.php become children elements of <form>. I want my supporting content outside the form structure.

Is there a template suggestion to get higher up in the processing chain or is this only possible using a specific preprocess hook in template.php or a module? Any examples would be greatly appreciated.

Thanks - Jeremy

Unless someone has a more elegant solution, I used:

$form['#prefix'] = '
Header
';

What seems odd here is the potential for a lot of markup in your code. I'm relatively new to Drupal, so I'm not sure if this is common practice.


How to make exposed filter show results on another page? Possible Duplicate:
  Expose Views filters both in a block but in the actual view also

I have a Views-based page (Page A) with exposed autocomplete filter. I want that filter form to appear in a block on Page B, but the search results should be displayed on Page A.

Unfortunately I have to search open value fields (node title), which eliminates Better Exposed Filters from play.

Does anyone know of a ready module that could work for me?

In Advanced section :
EXPOSED FORM
Exposed form in block:No -> set it to yes


Add link to call by Skype in a message - relative reference I have rules' module and in the last part I set an action to show a message. In that message I want to add a link to call one user by Skype, I am using this:

     $message = "Click to call to your student";

     echo $message;

That only works in php (You can try it http://phptester.net/).

But the problem is that Drupal is using that reference as a relative url so when I click it, it takes me to "http://www.example.com/yyyy/echo123?call". How can I do to do a reference to Skype?.

Thank you so much for your help.

your link contains "skype" protocol that is filtered out by filter_xss_bad_protocol() Drupal core function.
You can install Filter Protocols module which allows you to configure allowed protocols. Skype protocol is not included in configuration by default, you'll have to add it yourself - then your skype link will work.


Why is my twig variable not working inside my block twig? I have a field I'm pulling into a block twig template block--block-03.html.twig, and it outputs fine by itself (= {{content.field_content_side}}). But when I put it inside of a conditional it is not working.

Here's my code to illustrate what I mean:

{{ content.field_content_side }}

{% if content.field_content_side == 'left' %}col-sm-push-7{% else %}wtf{% endif %}

The output is here:

Why is it recognizing the twig variable correctly as left (= 1st line of my code), but in the conditional it is saying it's not left (= 2nd line of my code)?

Because the field is being rendered, which is different than evaluating its value. content.field_content_side is a render array which holds a lot more than just 'value'.

Try:

{% if node.field_content_side.value == 'left' %}

To get this in a block, you would add this to mytheme.theme:

/**
 * Implements hook_preprocess_block().
 * @param $variables
 */
function mytheme_preprocess_block(&$variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $variables['block_content'] = $variables['elements']['content']['#block_content'];
  }
}

Then:

{% if block_content.field_content_side.value == 'left' %}


Drupal 8 Custom Entities from a UI? Does anyone know away to create custom entities from Drupal 8 UI that is not ECK? I try it out using ECK and still a little bit buggy.

Each entity needs a lot of classes for access, forms, storage, listing, viewing,  etc... so you would have to create a module with default classes that would be somehow generic and you would have to handle the discovery of these new entity types since D8 uses annotations. Overall a quite a lot of work.

The same goes for config entities but that would be easier since they do not need that much handling compared to content entities.


How do I re-save all users? I need to re-save about 300 user to initialize geo-coding on their address fields. On /admin/people, I don't see any bulk action that would fit my needs. I have tested the update path-alias but with no luck.

Also, the VBO module for Drupal 8 doesn't offer a solution for users, AFAIK.

Any help is appreciated.

I don't know how comfortable you are with code. I would suggest writing an update hook in a custom module. Something like:

MYMODULE_update_8100(&$sandbox) {
  // On the initial run, set up the update.
  if (empty($sandbox)) {
    // Get all user ids.
    $sandbox['items'] = \Drupal::entityQuery('user')
      ->accessCheck(FALSE)
      ->execute();
    $sandbox['max'] = count($sandbox['items']);

    if (!$sandbox['max']) {
      // Prevent division by zero if there are no users.
      $sandbox['#finished'] = 1;
      return;
    }
  }

  $iteration = 0;
  while ($iteration < 25 && $sandbox['items']) {
    $iteration ++;

    // Resave each user.
    \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load(end($sandbox['items']))
      ->save();

    // Remove the end of the items list when the item has finished
    // processing.
    array_pop($sandbox['items']);
  }

  // Update the completion status as a number between 0 and 1.
  $sandbox['#finished'] = ($sandbox['max'] - count($sandbox['items']) / $sandbox['max'];
}

See hook_update_N for more information.


How to programmatically insert and update Field Collection values? I would like to insert and update Field Collection values. I'm using Drupal 8 with field_collection 8.x-1.0-alpha1.

Setup

I have created a new content type test_content_type with the following fields:

Title
Body
…
Test Field Collection

Machine name: field_test_field_collection
Type: field collection

The field collection field_test_field_collection has only one field:

Example Text

Machine name: field_text
Type: text

The Problem

I also created a node with values, for instance Lorem Ipsum as field_text.value, but I don't know how to read and define the value programmatically. I tried the following, which updates body but doesn't update field_text:

<?php

namespace Drupal\my_module\Controller;

use Drupal;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityStorageInterface;

class FieldCollectionTestController extends ControllerBase {
    /**
     * @return array
     */
    public function content() {
        $nodeId = 1402;

        /** @var EntityStorageInterface $entityStorage */
        $entityStorage = Drupal::entityTypeManager()->getStorage('node');
        $node = $entityStorage->load($nodeId);

        // Dump.
        {
            ob_start();
            var_dump($node->field_test_field_collection->field_text);
            $dump = ob_get_clean();
        }

        // Update node and field collection.
        {
            $exampleText = "Updated at " . time();

            $node->body = $exampleText;
            $node->field_test_field_collection->field_text = $exampleText;

            $node->save();
        }

        $response = [
            '#theme' => 'item_list',
            '#title' => 'Dumps',
            '#items' => [
                [
                    '#type' => 'markup',
                    '#markup' => $dump,
                ],
            ],
        ];

        return $response;
    }
}

The value of $dump is null.

Question

How do you insert, update and delete Field Collections in Drupal 8?

The following snippet (compatible with field_collection 8.x-1.0-alpha1) reuses an existing FieldCollectionItem or creates a new one on demand. The last few lines show how to modify fields inside the FieldCollectionItem.

If one has a field collection with a different name, then it should be enough to replace all occurrences of field_test_field_collection with the custom field collection's machine name.

<?php

// […]

$nodeId = 123;

/** @var EntityStorageInterface $entityStorage */
$entityStorage = Drupal::entityTypeManager()->getStorage('node');

$node = $entityStorage->load($nodeId);
$node->body = 'Body Update: ' . date('c');

/** @var Drupal\Core\Field\FieldItemList $fieldItemList */
$fieldItemList = $node->field_test_field_collection;

// Reuse existing Field Collection.
if (count($fieldItemList))
{
    /** @var \Drupal\field_collection\Plugin\Field\FieldType\FieldCollection $fieldCollection */
    $fieldCollection = $fieldItemList[0];
    $fieldCollectionItem = FieldCollectionItem::load($fieldCollection->value);
}

// Create new Field Collection.
else
{
    $fieldCollectionItem = FieldCollectionItem::create([
        'field_name' => 'field_test_field_collection',
    ]);

    $fieldCollectionItem->setHostEntity($node);

    $node->field_test_field_collection[] = [
        'field_collection_item' => $fieldCollectionItem,
    ];
}

$fieldCollectionItem->set('field_text', 'Last Update: ' . date('c'));

$node->save();

Deleting an existing collection is as simple as: fieldCollectionItem->delete();

Please have a look at the source code of the unit test class Drupal\field_collection\Tests\FieldCollectionBasicTestCase for more information.


Querying a web service via WDSL I am thinking about creating a search engine frontend for a special use case using Drupal 7. There are some modules in the module directory, and questions like Consume SOAP web service in Drupal 7 on SO, but I still am confused.

How is the mapping from external datasets to dynamic Drupal nodes done? For every dataset I retrieve through my service's WSDL interface, I'll need to create a node, a block or anything displayable in Drupal.

Is this even possible within the scope of Drupal's framework?

Yup its possible, PHP is specifically a web based language -- which Drupal is built upon.

For a REST based consuming service client for instance look at the Guzzle drupal community project. There is also the Services Client drupal community module to consume remote web services and uses UUIDs to map/sync fetched data. Your mileage may vary but all the pieces exist within Drupal and PHP. For instance even D7's core drupal_http_request can be used to craft your own HTTP requests, or your underlying PHP's installation CuRL library if you find drupals http function hindered by defaults.

There is also an issue and related sandbox project to add SOAP support to the Feeds drupal community module.

You say SOAP but thats only 1 piece of what can go over the wire. I've had to consume WS-* + SOAP based APIs from Drupal/PHP and I ended up creating XML by hand with CuRL to do it all. There are also libraries such as:

http://wso2.com/products/web-services-framework/php/

or this library to extend php5 ext/SOAP:

https://code.google.com/p/wse-php/

Ultimately understanding the remote API specs, and inter-operating with them from Drupal is on you the developer.


Is it possible to declare option inside drupal_add_js? I'm stuck on including an external JavaScript file on a custom page. The API service requires the HTML to be formatted as below

<script type="text/javascript" src="//platform.example.com/api.js">
api_key:   [key]
</script>

No idea if this can be done the Drupal way. I tried:

// load SDK
drupal_add_js('//platform.example.com/api.js', 'external');
drupal_add_js('api_key:   [key]', 'inline');

But without success. The API_key declaration need to be done inside the first  tag that links to the external JS. I know you can add extra parameters like documented on https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7.x but this case is not described.

You can try something like

$external_js = array(
  '#markup' => '<script type="text/javascript" src="//platform.example.com/api.js">
    api_key:   [key]
  </script>',
);

drupal_add_html_head($external_js, 'my_module');


For each image uploaded in a node: get the url I'm begining with Drupal 8 and I want to get the url of the photos in the content I create to display them.
 The context is : a photograph upload pictures for a customer. This customer can see it on a page. To get this data in common I created a content for my shooting with an id.
 What i did is :

$photos = $shooting->field_shooting_photos->target_id;

This allow me to get the id of every pictures uploaded.
Now I want to do a foreach on $photos in my .module that will return every url in an array.
Then I will use this array in my Twig and do a foreach on it too to return every photos.
I just can't figure out how to do, I think I will have to use something like that

$path = $photo_id->getFileUri();

but I can't figure out the syntax to get it into an array.
Thank you for your help!
Solution :
Here is what I did in case it can help someone :

$photosTest = $shooting->field_shooting_photos->referencedEntities();

$photoUrls = [];

foreach($photosTest as $media) {
  $photoUrls[] =
  $photoUrls[] = [
      'render' => [
         '#theme' => 'image_style',
         '#style_name' => 'medium',
         '#uri' => $media->field_media_image->entity->getFileUri()
       ],
       'href' => $media->field_media_image->entity->getFileUri(),
     ];
}

In my Twig file I render the array :

 {% for photo in photos %}
    {{ photo.render }}
 {% endfor %}

Giving field_shooting_photos is a multi valued field of Files, this is how to generate your array of URI :

$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $image) {
    $photoUrls[] = $image->getFileUri();
}

For media image :

$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $media) {
    $photoUrls[] = $media->field_media_image->entity->getFileUri();
}

Note this will give you the File_id of the first image in the entite file reference list :

$shooting->field_shooting_photos->target_id;

NB : Best way is probably to generate render array or use built-in drupal themes, is none fit your needs, your may also generate a custom field formatter.


How to fix drush php configuration on the hosting? I am facing a pretty award drush problem. In order to run drush I need to use this command on my hosting:

/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php

When I run

/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php status

it works correctly. But when I try to do the update command:

/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php upc drupal

and it fails with the message:

  pm-updatestatus failed

I found out that upc runs drush in subshell with incorrect php. So I added path to php:

/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php
                 --php=/opt/php/bin/php --debug upc drupal

But it also fails without configs. When I pass configs:

/opt/php/bin/php -c /home/pisar/etc/php.ini
                 -d memory_limit=128M /home/pisar/opt/drush.php
                 --php=/opt/php/bin/php\ -c\ /home/pisar/etc/php.ini\
                 -d\ memory_limit=128M --debug upc drupal

it fails because it tries to run them using quoted php with params:

Backend invoke: '/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M' /home/pisar/opt/drush.php --php='/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M'  [command]
 --backend=2 --verbose --debug --root=/home/pisar/site.com/docs/drupal --uri=http://default  pm-updatestatus drupal 2>&1 [1.45 sec, 14.72 MB]
'/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M' /home/pisar/opt/drush.php --php='/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M'  --backend=2      [notice]
--verbose --debug --root=/home/pisar/site.com/docs/drupal --uri=http://default  pm-updatestatus drupal 2>&1 [1.45 sec, 14.73 MB]
The command could not be executed successfully (returned: /opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M: not found

I put this:

export DRUSH_PHP='/opt/php/bin/php'
export PHP_INI='/home/pisar/etc/php.ini'
export PHP_OPTIONS='-d memory_limit=128M'

into ~/.profile, ~/.bash_profile and ~/.bashrc. Then ran without --php, but nothing helped.

How to fix?

I had to use --php-options parameter. The working command looks like this:

/opt/php/bin/php -c /home/pisar/etc/php.ini -d memory_limit=128M
                    /home/pisar/opt/drush.php --php=/opt/php/bin/php
                    --php-options="-c /home/pisar/etc/php.ini
                    -d memory_limit=128M" upc -y drupal


Redirect user/register to external user creation I have a secondary system handling user authentication, but I would like to use the user creation code from that system instead of Drupal.  I want to redirect the Drupal user creation to the secondary system instead.

I already have my own user creation page, so I don't want to do a form_alter on Drupals user creation, I'd rather just send the user to my creation page instead.

How do I redirect user/register to my code instead of Drupal?

Roling your own user registration and authentication requires a number of steps. I try to eyplain them.

Calling yourmodule_form_user_register_form_alter(&$form, &$form_state, $form_id) would be a good idea. Actually you have to alter only the submission call back and may be the validation call back. You can have a look at the last lines of user_register_form how this is done in drupal core.

To make sure the users can login. It's possible to include an external authentication service. Have a look at user_login_default_validators for this.

What is most important for you, that at the end of the login procedure you have to have a valid drupal user object. I'd recommend to have parallel external and drupal users. Probably do the authentication on your external service but let drupal load the corresponding drupal user once this was successful.

This gives you basic working system. Next steps would be to handle password change and one time password recovery links in a correct way.


Error: Argument 2 passed to drupal_array_get_nested_value() must be of the type array, string given I'm using Entityform with some custom module for multipage which is based on FGAM.

Recoverable fatal error: Argument 2 passed to drupal_array_get_nested_value() must be of the type array, string given, called in includes/form.inc on line 1200 and defined in drupal_array_get_nested_value() (line 6771 of includes/common.inc).
The website encountered an unexpected error. Please try again later.

Why this happens and how do I fix or debug this kind of error?

The error:

  Argument 2 passed to drupal_array_get_nested_value() must be an array, string or null given

means there is a problem with the structure of your form you're trying to submit. So string/NULL were given instead of array for the second parameter.

The function:

&drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL)

retrieves a value from a nested array with variable depth, for example:

$value = drupal_array_get_nested_value($form, $parents);

Here are the example calls from Drupal core (see the 2nd argument):

./common.inc:  drupal_array_get_nested_value($array, $parents, $key_exists);
./form.inc:      $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
./form.inc:  $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);

If you don't know which field is causing it, the easiest way to find out is by doing this simple hack (which should be reverted after that of course):

function &drupal_array_get_nested_value(array &$array, $parents, &$key_exists = NULL) {
  if (!is_array($parents)) { var_dump($parents, debug_backtrace()); exit; }

Which would display value of $parents which should be an array and the backtrace.

Usually this could happen during the validation and it can caused by invalid #parents or #limit_validation_errors structure of form array.

If there is no any custom coding involved, then it's a bug of the contrib module which cause that (e.g. Conditional Fields, Email Field, Entity Translation, etc.), so it should be reported against the right module.

In my specific case, I've to fix #limit_validation_errors by wrapping it into array() where it contained list of $group['children']:

  $form['actions']['continue'] = array(
    '#type' => 'submit',
    '#value' => t('Continue'),
    '#limit_validation_errors' => array($validate_fields),
    '#submit' => array('foo_form_submit'),
    '#validate' => array('foo_form_validate'),
  );


Make phone field required if certain shipping method is selected I use drupal 6 and ubercart 2. My aim is to make phone field in delivery address required if certain shipping method is selected. I have set up a jquery script that shows a message to the user saying that phone is needed after customer selects the shipping method. Despite of this, some customers don't fill out the phone field.
I would like to add a non js check after submission of checkout page.
I suppose I would need to write a small module. A need help with the start of the code

<?php
IF
{[mymethod] = true}
then {
  $form['panes']['delivery']['delivery_phone']['#required'] = true;
}
?>

Thank you very much.

EDIT: according to @Adam Balsam answer I tried to make custom module
This is uc_checkout_phone.module

<?php
function uc_checkout_phone_uc_cart_checkout_form_alter(&$form, &$form_state) {
  $form['panes']['delivery']['delivery_phone']['#element_validate'] = array('uc_checkout_phone_phone_validate');
}
function uc_checkout_phone_phone_validate($element, &$form_state) {
  if (($form_state['panes']['shipping']['shipping_method']['#value'] == 'Doprava - kurier DPD') && ($element['#value'] == '')) {
   form_error($element, t('You must enter a phone number if you select XXX as a shipping method.'));
 dpm($form_state); }
}
?>

This is uc_checkout_phone.info

name = uc_checkout_phone
description = phone required
core = 6.x

The form id should be uc-cart-checkout-form. I had to write it using underscores. The shipping method is Doprava - kuriér DPD, I tried also the value which is flatrate_3---0 but I get no warning message if I let the phone number empty. Where can be the problem?
I named themodule: uc_checkout_phone

You will have two functions in your custom module. The first one is hook_form_FORM_ID_alter:

/**
 * This function adds an additional custom validation function to the delivery phone field
 *
 * Make sure you update MYMODULE and YOURFORMID to match your circumstances.
 */
function MYMODULE_form_YOURFORMID_alter(&$form, &$form_state) {
  $form['panes']['delivery']['delivery_phone']['#element_validate'] = array('MYMODULE_phone_validate');
}

The second function is the custom validation function that we added using hook_form_FORM_ID_alter above:

/**
 * Make sure you update MYMODULE again and update the array to match your shipping method
 */
function MYMODULE_phone_validate($element, &$form_state) {
  if (($form_state['panes']['shipping']['shipping_method']['#value'] == 'THE SHIPPING METHOD') && ($element['#value'] == '')) {
    form_error($element, t('You must enter a phone number if you select XXX as a shipping method.'));
  }
}


How can I add styles attribute to Global Custom field markup? I have created a view to display my articles and I would like the article thumbnails to be used as background.
So I added the different fields I've hidden.

I added a relationship to the image field to get the thumbnail URI. Then I added the following code in the custom global field.

{{ field_categorie }}

{{ title }}

{{ created }}

But on display, the style is ignored.

Instead of
, I have
.

How can I make Views to print the style attribute to let me put a dynamic background image URI?

Drupal 8 views will strip away any markup it thinks it is dangerous

you have to rely on a custom theme solution here is a general overview of how this can be done

if you don't have a custom theme you have to create one (more info)
Enable Twig debugging (more info)
Inspect your page in browser to find the appropriate templates to override.  In the html comments you will find which .twig template is responsible to output a specific piece of html markup  (More info)
Copy required template into your CUSTOM_THEME/theme folder
Add or modify the markup in the twig template

Alternatively you might want to give https://www.drupal.org/project/viewscss a try which promises to allow viewscss but it does not have a stable release.


Can't use drush site-install to drop tables and reinstall in MAMP I have a local multisite instance running MAMP 3.0.7.3, and I can't use the drush site-install command to do a re-install of one of my sites without actually dropping the database first.

If I try the command without dropping the database, I get the following output:

$ drush --uri="www.example.local" si -y my_great_install_profile --account-pass=admin --sites-subdir="www.example.com"
You are about to DROP all tables in your 'example_site' database. Do you want to continue? (y/n): y

Additional uncaught exception thrown while handling exception.

Original

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &amp;#039;example_site.registry&amp;#039; doesn&amp;#039;t exist: SELECT filename FROM {registry} WHERE name = :name AND type = :type; Array
(
    [:name] =&amp;gt; drush_drupal_site_install
    [:type] =&amp;gt; interface
)
 in _registry_check_code() (line 3188 of /Users/gravelpot/sites/www.example.local/includes/bootstrap.inc).

Additional

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &amp;#039;example_site.registry&amp;#039; doesn&amp;#039;t exist: SELECT filename FROM {registry} WHERE name = :name AND type = :type; Array
(
    [:name] =&amp;gt; drush_drupal_environment
    [:type] =&amp;gt; interface
)
 in _registry_check_code() (line 3188 of /Users/gravelpot/sites/www.example.local/includes/bootstrap.inc).

Drush command terminated abnormally due to an unrecoverable error.                                                                            [error]

Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &amp;#039;example_site.semaphore&amp;#039; doesn&amp;#039;t exist: DELETE FROM {semaphore}
WHERE  (value = :db_condition_placeholder_0) ; Array
(
    [:db_condition_placeholder_0] =&amp;gt; 1731533568552880e6a71ed3.80394544
)
 in lock_release_all() (line 269 of /Users/gravelpot/sites/www.example.local/includes/lock.inc).

I also have the same problem when trying to import a SQL dump file by doing something like drush sql-drop followed by drush sqlc < path/to/file.sql, which is a pattern I see suggested in a lot of blog posts.

I am using Drush 6.5 installed via composer. My co-workers have a similar configuration, and do not have this problem.

Make sure nothing breaks Drush calls; attempt a drush cc all to see if the error still appears, and debug if it does.

To avoid dropping the database, the simple "hacked" answer is:

Edit site's settings.php file to use another database scheme (make sure it exists though).

$databases = array (
  'example1' =>
  array (
    'example1' => array (
      'database' => 'example2', // Changed from "example1".
      'username' => 'user',
      'password' => 'pass',
    ),
  ),
);

Use site-instal . This will drop "Example2" and install the site there, without hurting the original database.
Edit the site's configuration file back to original database scheme.

You need to use backquotes on the "drush sqlc" part:``drush sql-connect`` < path/to/file.sql.


Hide label for input on focus and when has value I have some simple jQuery working to hide labels for text inputs on focus, keyup and blur if (value !== ''). I am using replacement tokens in my forms to fill in a default value based on the currently logged in user. I need to hide the labels if the default value gets prepopulated. I can't get the right function to hide the labels if a default value populates the form. (I've installed jQuery update to get the .on() function.)  Here's the script in my js file:

(function ($, Drupal, window, document, undefined) {
Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {
/*------ Hide labels when user interacts with forms ------*/
    $(".form-item input", context).on({
      focus: function() {
        $(this).prev('label').fadeOut('fast');
      },
      keyup: function() {
        $(this).prev('label').fadeOut('fast');
      },
      blur: function() {
        if($(this).val() !== "") {
          $(this).prev('label').hide('fast');
        } else {
          $(this).prev('label').fadeIn('fast');
        }
      }
    });
/*------ Hide label if has default value on page load --------*/
    $(document).ready(function(){
      if($('.form-item input').val() !== "") {
          $(this).prev('label').hide();
      }
    });
  }
};
})(jQuery, Drupal, this, this.document);

Drupal outputs

  Email Address *
 <input type="text" id="edit-field-email-address-und-0-email--2" name="field_email_address[und][0][email]" value="foo@foofighter.foo" size="60" maxlength="128" class="form-text required">

Check out this

   if ($(value).val() != ""){
  var fieldId = $(value).attr("id");
  $("label[for='"+fieldId+"']").hide();
}


Set legacy database in Aegir context Im fairly new to aegir and I have some hard time finding out the proper way to set a legacy database in aegir context. As far as I can see settings.php inside a platform is automatically generated so if I edit this file and run verify all changes will be lost. Other option is to insert it into drushrc file but Im still not sure what the syntax should be there. I see that database is inside the options array. Anyone with similar experience and few advice how to tackle this properly?

Such definitions can be placed in a local.settings.php file, alongside the generated settings.php.

You'll find an include statement at the bottom of the generated settings.php


Views content show current state - workbench I have a page that lists all the content and want to display the current state for each node.

But for now I can only see published content on the page. The view of mine is a content view.

Can we make some changes in the view to show current state of nodes as well?

Have tried the Workbench Current state filter as well but it did not work

Have you already installed workbench moderation module?

I have used this module and it gives you a Workbench page with the tabs for each state of the nodes. The user can see which nodes are in Draft state and which are in review state.

You can adjust the look and feel of the page using panels and make it the way you want to display the content of each state.

In the views, you can add exposed filters for any other specific field you want to filter.


.js extension for javascript file is missing I am using below code in my custom module "my_module".

    function my_module_theme(){
        return array(
                'my_module_javascript'=>array('arguments'=>array(),),
        );
 }

 function my_module_init(){
        theme('my_module_javascript');
 }

 function theme_my_module_javascript(){
        drupal_add_js(drupal_get_path('module','my_module').'/my_module.js');
 }

After I enable the module page source is showing the javascript file without .js extension.
like src="modulepath/my_module?lrmjns"
Am I doing anything wrong? why is it skipping .js?

What version you are using? And are you sure the my_module.js is exist?

I think the best way is using hook_library to add js and css for your module:

function my_module_library() {
  $libraries['my-module'] = array(
    'title' => 'My custom module library',
    'version' => '1.0',
    'js' => array(
      drupal_get_path('module', 'my_module') . '/my_module.js' => array(),
    ),
  );
  return $libraries;
}

function my_module_init() {
  drupal_add_library('my_module', 'my-module');
}


How can I keep paragraphs of text in one cell when i import data from a CSV file without it making it all one big paragraph? I'm using Migrate, Migrate Tools, Migrate CSV to import data from a csv file into my website.
One field I have is Text (Formatted, Long), and this is where I import a bunch of information about my specific item.
If in my csv file I write out something like this in a cell (Using Alt+Enter to create a line break in the cell):
This is paragraph 1 of a block of text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut optime, secundum naturam affectum esse possit. Tu autem, si tibi illa probabantur, cur non propriis verbis ea tenebas? Sine ea igitur iucunde negat posse se vivere? Quod autem satis est, eo quicquid accessit, nimium est;
This is paragraph 2 of a block of text. Duo Reges: constructio interrete. Non enim quaero quid verum, sed quid cuique dicendum sit. Quod quidem iam fit etiam in Academia. Cum ageremus, inquit, vitae beatum et eundem supremum diem, scribebamus haec.
It ends up importing like this into Drupal:
This is paragraph 1 of a block of text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut optime, secundum naturam affectum esse possit. Tu autem, si tibi illa probabantur, cur non propriis verbis ea tenebas? Sine ea igitur iucunde negat posse se vivere? Quod autem satis est, eo quicquid accessit, nimium est; This is paragraph 2 of a block of text. Duo Reges: constructio interrete. Non enim quaero quid verum, sed quid cuique dicendum sit. Quod quidem iam fit etiam in Academia. Cum ageremus, inquit, vitae beatum et eundem supremum diem, scribebamus haec.
Just one big block of text.
Does anyone know of anything special that I need to put into my Excel cell after each paragraph so that Drupal knows to break up each paragraph into its own <p> paragraph tag once imported from the saved .csv file?
I've gone through numerous sites/threads trying to find an answer but I can't quite seem to find anything explaining what I need to do in Excel prior to exporting as CSV to maintain the paragraph breaks.
Note, after I export from excel to csv, i open the file in Notepad and resave as UTF-8 in order to import the content properly in Drupal.
Is this something that is even possible at all?

If your CSV file is saved with new line characters then I expect it is also saved that way into the database. You can check this if you have access to the database. But you can also check this more or less on the Edit page of some of the content that has been imported.
Drupal uses Text formats to display the text. This means it can change what is being served from the database.
Check which Text format is being used on that field and then check the configuration for that format. You can check which Text format is being used on the Edit page, right below the text area element.
"Losing" new line characters can happen if you don't have a Convert line breaks into HTML (i.e.
 and
) option turned on on the format that you apply to your field.
Try using that option on the Text format of the content you've imported, or maybe you have the "Plain text" format, since you're importing content, but make sure that this format has the option Convert line breaks into HTML (i.e.
 and
) enabled.
You can find Text formats under Configuration > Content authoring > Text formats and editors.
Just make sure you don't save the node with a Text format chosen that doesn't have that option enabled (you will see all the paragraphs lumped together), because saving the node will override what is written in the database. Don't save if it doesn't look good, and try to find which Text format makes it look good, it will probably be the one that has the mentioned option enabled ;)


How do I get a simple template to work? I have a Drupal module where I want to separate the html from the logic by placing it in a template file. You'd think this would be easy but I can't figure out how it's supposed to work within Drupal. When I google it I come upon massive guides on making Drupal themes or articles on focusing on a single aspect of the templating process. I downloaded and installed the Examples for Developers module which has a section for templating, but even that does not do exactly what I want and breaks as soon as I make any significant change.

I made a simple module called blob to try to get this to work.
I have the following template file called blob-stuff.tpl.php:

<div class="container-inline">
    Hi <?php  print $myname; ?>
</div>

In blob.module I have

function blob_menu() {
  $items['blob1'] = array(
    'title' => 'Blob1',
    'page callback'    => 'blob_stuff',
    'access arguments' => array('access content'),
  );
  return $items;
}

function blob_theme() {
  return array(
    'blob_stuff'  => array(
      'template' => 'blob-stuff',
    ),
  );
}

function template_preprocess_blob_stuff(&$variables) {
  $variables['myname']='Bob';
}

function blob_stuff(){
  return 'Bob';
}

Which of course doesn't work, because at this point I'm just guessing.

Can anyone give me a simple, working example of this, following Drupal best practices?

You're on the right track, the only thing you need to do is call your theme function in your page callback, blob_stuff(). There are two ways to do this, the preferable way is using a render array:

function blob_stuff(){
  $page = array
  (
    '#theme' => 'blob_stuff',
  );

  return $page;
}

You could also directly call your theme function, but this is not the preferable way to do it:

function blob_stuff(){
  return theme('blob_stuff');
}

But to go further with this, you've hard-coded the name Bob into your code. Usually you'll want something dynamic, pulled from the path in the URL. You can define a dynamic path with a wildcard in hook_menu()

function blob_menu() {
  $items['blob1/%'] = array(
    'title' => 'Blob1',
    'page callback' => 'blob_stuff',
    // Pass the 1st index of the path (the wildcard) to your page callback
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );
  return $items;
}

In hook_theme(), you'll add a variable:

function blob_theme() {
  return array(
    'blob_stuff'  => array(
       'variables' => array(
         'name' => FALSE,
       ),
       'template' => 'blob-stuff',
     ),
  );
}

Now in your page callback, you can pass the wild card to your theme function, which will output it in your template:

// $name comes from the wildcard in the URL
function blob_stuff($name){
  $page = array
  (
    '#theme' => 'blob_stuff',
    '#name' => $name,
  );
  return $page;
}

Your template will now look like this:

<div class="container-inline">
  Hi <?php  print $name; ?>
</div>


How to theme views using Taxonomy Terms? The site on which I'm working has a variety of views for multiple sections of the website. These different sections, which are defined by Taxonomy terms, use different themes. So, for example, sections 'X' and 'Y' each have views which we want to be displayed in themes 'X' and 'Y.'

Is there a way in Views to assign the page created by Views a taxonomy term, so that, using ThemeKey, it can be assigned a theme by it's taxonomy term, like the other nodes with that taxonomy term?

I'd really like to do this without using templates, so that it can be easily managed within Drupal's UI.

Are you saying that you are using the not-yet-stable 7.x module Taxonomy Theme? Terms are assigned by Term Reference fields on fieldable entities.  Since drupal is open source, there is always more than one way to do something.  If you wanted to build a site that can do exactly as you have asked here, then I suppose it is possible to make a new entity that has a term reference and also embeds the view in its custom theme processes to get the fusion you are requesting.  You will have to crawl into the Taxonomy Theme module code and see if it is using hook_node_view to do the check/change.  If so, it would not fire on a straight view anyway but this custom entity (maintenance nightmare) should trigger it.

An easier method would be the template files that you dont want.  Use theme_hook_suggestions where you have different tpl.php files for the different views based on path or whatever else you want.  Different templates by path alias.  You then just have the different templates use the different theme styles.  I would also recommend putting the taxonomy term values as body level css classes so you can have one theme, and it just trigger different stylesheets based on term classes. Option1 | Option2  This would relieve your dependence on the dev-version module.

Option 3.  In whatever theme is your default, copy the relative style sheets over from the other themes and just use the view-specific css class for each one, applying it manually.  This means that you have duplicated style commands, so it will be a little harder to maintain what is coming from where, but at least you dont have to code any php.

Option 4.  Sareed's comment about using block displays and embedding the views on other pages that have the terms.  (...I should have thought of that)