programmatically getting custom node belonging to a term have searched google but cannot find anything specific . Intention is to get all Custom Node types that have been assigned a specific term of vocabulary . for example the follwoing is a db query to get custom node type.

$query->condition('type', "news_article")->fields('n',array('nid'))->orderBy('created', 'DESC')->range(0,90);

can the same query be modified to also add the  filter for term id .

One other related question is that how can (in PHP) we get the term id from the url of the pattern e.g <drupal site>/taxonomy/term/2 .

any help appreciated

This might be helpful

How to use EntityFieldQuery

It works great for me. As far as the other question is concern, there are many ways of doing this. the simplest would be below, provided that you are accessing link in your question:

<?php
    $arg0 = arg(0);
    $arg1 = arg(1);
    $arg2 = arg(2);

    echo $arg0; //this will echo 'taxonomy'
    echo $arg1; //this will echo 'term'
    echo $arg2; //this will echo 2 (term ID)
?>

Info about arg() can be found here: arg()


How do I setup download links for pdf files directly? I want to add a pdf file via a file field on a content type,
I want to display a download link, and if the user clicks save it to your computer, as in a normal download.

Try the DownloadFile module. In your content type change the field display formatter to download file or whatever suits your need.


Show latest content date from group content type I've a group type vendor with following groups:

V1
V2
V3

Each group is associated with content type notes as shown below:
Notes (Content Type) with nodes associated with groups:
N1 (Group: V1)
N2 (Group: V1)
N3 (Group: V2)
N4 (Group: V2)
N5 (Group: V3)

So the relationship between them goes like this.

Vendor (Group Type)

Group V1
Group V2
Group V3

N1
N3
N5

N2
N4
None

Where N* are nodes of content type Notes
I want to create a view where following data should be displayed:
V1
    Latest content update date
V2
    Latest content update date

But I do not want all the contents update date listed. When I use grid layout I can group the content as per associated group but the output contains all the last updated date for all contents. I want to limit the output only to last 2-3 contents.
Example:
Views -> Grid Layout -> Group by group title -> Number of columns per row -> 2
Output:
V1

N1 last update date     N2 last update date

V2

N3 last update date     N4 last update date

Expected output:
V1

N1 last update date

V2

N3 last update date

After a some research and hit and trial I'm able to configure views output as per requirements with Views merge row module. Below are the steps I've followed:

Install Views Merge Row module.
Create a Views with group content type.
Select Format -> Card
Add fields:

Group Title
Content Changed on (relationship content)

In card settings Select "Group Field 1" as a Group Title.
Now under views Advance-settings Select "Merge rows"
Under Merge row settings select following configuration:

Field
Merge Option

Group Title
Use Values of this field as a filter

Content Changed
Use First Value of this Field

Sort -> Ascending


Mails are not always send When a user creates an account, sometimes all the mails are sent, sometimes not all, and sometimes no mails are sent but they are returned on the site-owner mail address. All the mails are considered as spam and i don't know why. On the returned mail i get this (I have no error in Drupal report and logs) :

This is the mail system at host "my host".

I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can
delete your own text from the attached returned message.

               The mail system

<"site mail">: host
    gmail-smtp-in.l.google.com[2a00:1450:4013:c01::1a] said: 550-5.7.1
    [2001:41d0:d:363d::] Our system has detected that this message does
    550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and
    550-5.7.1 authentication. Please review 550-5.7.1
    https://support.google.com/mail/?p=IPv6AuthError for more information 550
    5.7.1 . w82si7064886wma.125 - gsmtp (in reply to end of DATA command)

Final-Recipient: rfc822; "targeted email"
Action: failed
Status: 5.7.1
Remote-MTA: dns; gmail-smtp-in.l.google.com
Diagnostic-Code: smtp; 550-5.7.1 [2001:41d0:d:363d::] Our system has detected
    that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding
    PTR records and 550-5.7.1 authentication. Please review 550-5.7.1
    https://support.google.com/mail/?p=IPv6AuthError for more information 550
    5.7.1 . w82si7064886wma.125 - gsmtp

----- * MAIL RESUME * -----
...

What can i do to fix that ?

The error message you have provided indicates that you do not have a reverse PTR record in your DNS for the IP address you are using, specifically in this case for IPv6.  When you look a specific IP address up it should resolve back to a known hostname which identifies it in DNS.  Some mailservers and systems will not accept email from hosts without a valid PTR record.  I would imagine that in your case you have some IPv6 records in place, and that your server is connecting to Google's SMTP servers over IPv6 but that you do not have the correct records in place.  The error message provides a link to https://support.google.com/mail/?p=IPv6AuthError which should tell you more about this error.

You should also make sure that you have correctly setup SPF for the domain that is used as the from address in your emails, you may need to add an SPF record, or update the existing one for the domain so that your webserver is trusted to send email on behalf of your domain.


Redirect the title field of a content type to some external url in a view I am using drupal 7 with view3

I have content type named News having many fields along with a taxonomy field named News Type, News type have terms: 'Free' and 'Premium', I am displaying News on my page through view, the problem i am facing is I need to redirect the news node to some external url like popup, if its premium news, means if its News Type field is set to premium it should not be redirected to its content, In short when premium news is viewed it should popup some message instead of showing the content of that news,and for free news it should go to the news node detail page. Please find the screenshot of view attached. Please help will be greatly appreciated. If I need to clarify please comment.

To change content link... You can try using Views Conditional Module...

Project page says

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

  Equal To

  Not Equal To

  Greater Than

  Less Than

  Empty

  Not Empty

  Views conditional allows you to output text based on the result of the
  condition.

If it doesn't work then you can solve it using views php module..


Email Change Confirmation module -- Avoid confirmation email from user_login hook I'm using the "Email Change Confirmation" (email_confirm) module with Drupal 7. It works well. However, I also have a user_login hook that sets certain users' email addresses, thus:

    user_save($user, ['mail' => '<new address>']);

In this instance, I want the change to take effect immediately, without the need for confirmation (via email or otherwise). The module already provides a configuration option to override sending a confirmation email when the address is changed via the interface by users with specified roles. I want it to behave like that when I change it via the login hook. Is there a way to override sending an email in this case?

After looking at the email_confirm code, I came up with a simple solution. A confirmation message isn't sent if an email address is changed to or from empty, so:

  user_save($user, ['mail' => '']);
  user_save($user, ['mail' => '<new address>']);

does the trick.


How do I get a view to display as themed within a simplenews html email? I am trying to create a simplenews newsletter, also using Simplenews Scheduler, to weekly send out a newsletter with the content defined by views.

I have a content type set up, and the views defined. I have the views inserted into the content type using Viewfield. This all works fine and the email sends with the views content. However, the styling is not correct.

My views return lists of full nodes which I have set the View Mode of as "Email: HTML". Within the templates in my theme I have added the mark-up I want for the node with that View Mode. When viewing the newsletter on the site (as a node) it all looks correct. However, when I send the newsletter, the email I receive has the view in it's raw format (like that which is displayed in the view preview) and has none of the mark-up I've specified.

How can I get the correct mark-up showing? I don't know if I'm just missing a setting somewhere or something.

Many thanks.

My newsletter template (simplenews-newsletter-body--13--email-html.tpl.php) is as follows:

<?php /*This appears in the email*/ ?>
TEST NEWSLETTER TEMPLATE

    <?php /*The following should print the full newsletter node including the views*/ ?>
    <?php print render($build); ?>

    <?php /*The following should print a single view*/ ?>
    <?php print views_embed_view('news_upcoming_events','block_1'); ?>

The event node template (node--event.tpl.php) which is returned in the view used in the newsletter template:

<?php if($view_mode == 'email_html'){ ?>
    TEST EMAIL TEMPLATE

<a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php print render($body); ?>

<?php }else{ ?>
    NORMAL VIEW
<?php } ?>

The newsletter template all appears fine in the email. I see the line TEST NEWSLETTER TEMPLATE, but the event node templates are not used in the views output. It is instead some generic drupal/views output.

This is the way the view is setup.

And this is the preview displayed with in the view setup. This is also what is appearing in the email when the newsletter is sent, instead of the mark-up declared in my template file. (It is correct when viewing the node on the website though)

This sounds very similar to what I did a while ago. I documented my setup on drupal.org. This seems to work for your already. I think your MailSystem is the source of error here. Make sure the MailSystem that is used by Simplenews is using the required style sheets and of course the custom templates from your web theme. Also note, that not all styles that are possible on a website an be used in an email, in fact, only a pretty small subset of styles will work at all.

Take a look at the Emogrifier module, it converts your stylesheets to inline styles for emails. Also, for images and other URLs, the Pathologic module may be of help as it converts relative URLs to absolute ones.


Add a translatabe text into panels i want to add a translatable text into panels.So I enabled the php filter and add this snippet :
Unfortunately it doesn't appear.What am I doing wrong?
thanks

If using Drupal 6, ensure these edits are within the settings.php file, as this is where the translation will take effect.

If using Drupal 7, there are a few reasons why this may not work. Most usually, if the text you are translating contains anything that needs to be substituted (i.e. using %user:name etc.), then the text will be substituted before being passed to t(), and as such will not work! Also, the functionality of t() in Drupal 7 for attributes and variables is limited, so perhaps an additional module will be helpful.

For solutions using additional modules: Place the text in a basic page,  you can then use Entity translation to handle the languages and translation. @pedrosp also suggests that "to avoid SEO duplicated content issues, install Rabbit hole module and use the redirect to your panel page for those nodes."

Also, i18n has some solutions to tranlsate text within panels. It may take some playing around with however, to match the intended functionality of your site.

Finally, @Letharion has shared before some custom code to "force" a title to become translatable, perhaps playing with this to focus instead on where you would like your translatable content would also help:

/**
 * Implements hook_panels_pane_content_alter().
 */
function HOOK_panels_pane_content_alter($content, $pane, $args, $context) {
  if ($content->title) {
    $content->title = t($content->title);
  }
  return $content;
}

Hope this is of some assistance!


How to create paragraphs item programmatically? How to create paragraphs item programmatically?

In Drupal 7 I am using the following code.

    $node = node_load($nid);
    $paragraph = new ParagraphsItemEntity(array('field_name' => 'field_name', 'bundle' => 'para_bundlename'));
    $paragraph->is_new = TRUE;
    $paragraph->field_ptest1['und'][0]['value'] = 'Foo';
    $paragraph->setHostEntity('node', $node);
    $paragraph->save();
    node_save($node);

But its not working ?

Yes, That was for adding the value in existing paragraph item. If you want to create new paragraph item with new value try this code.

$node = node_load(...);

$paragraph = new ParagraphsItemEntity(array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->field1_name_in_paragraph_bundle[LANGUAGE_NONE][0]['value'] = 'Test Data';
$paragraph->field2_name_in_paragraph_bundle[LANGUAGE_NONE][0]['value'] = 'Test Data';
$paragraph->save();


How to get cache metadata from nested render array when returning response? I have a controller action that renders a list nodes and returns them, and only them. It's invoked via AJAX and the JS code just takes the result and inserts it into the page somewhere.

My problem is getting the cache metadata from the render array of nodes and passing it to the response. Here's the simplified action:

public function myControllerAction() {
  $builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  // Get render array containing a few nodes.
  $nodes = $builder->viewMultiple([1,2,3], 'teaser');

  $response = new CacheableResponse();
  $response->setCacheableMetadata(CacheableMetadata::createFromRenderArray($nodes));
  return $response;
}

The problem is CacheableMetadata::createFromRenderArray() expects you to not give it a nested render array, but that's what the view builder returns. It returns an array of render arrays.

How can I efficiently extract the metadata from each node in the list and apply it to the response?

Render the nodes in a render context, so that the metadata can bubble up:

  $storage = \Drupal::entityTypeManager()->getStorage('node');
  $builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $nodes = $storage->loadMultiple([1,2,3]);
  $build = $builder->viewMultiple($nodes, 'teaser');

  $render_context = new \Drupal\Core\Render\RenderContext();
  \Drupal::service('renderer')->executeInRenderContext($render_context, function() use (&$build) {
    \Drupal::service('renderer')->render($build, TRUE);
  });

  $response = new CacheableResponse();
  if (!$render_context->isEmpty()) {
    $response->addCacheableDependency($render_context->pop());
  }

The rendering is not lost. The rendered nodes are in $build['#markup'] and you can add the html to the response if that is what you want to do:

$response->setContent($build['#markup']);

Edit:

Just seen in the related question on the right a similar topic. While the above code is good for demonstration purpose, because it shows how to get cache metadata from a nested render array, the simpler code in the answer to How to handle cache metadata in an AJAX response? is actually working for this nested build array too, because the dependencies of the build array are added after rendering and at this point the metadata has bubbled up to the top level.


Display content type images using taxnomy In a drupal block view that I have created I am currently displaying the images and title of a certain content type. On that content type I have two taxonomy term fields one is a multi-select box

My question is this, I want to filter the title and images according to the taxonomy multi box field when a node is displaying, how?

For example if I have a multi list

water
coffee
tea
drupal
views

On creating the node I select water and drupal so when the node displays it will show all the images and titles that have the same taxonomy term in the block view

Below I have an image of a view that is trying to displaying an image and title according to the taxonomy terms save on a node that a user is currently looking at

It is not working of course. Do I have the right idea what am I missing?

I would try removing your Content: Related Products filter criteria.

Make sure your contextual Content: Nid filter is setting the default from the content ID in the url, and under "More" this filter is set to exclude.

Add another contextual filter for Content: Has Taxonomy Term ID. Select "Provide default value" and use type PHP Code:

$node = menu_get_object();
$terms = array();
if (empty($node->field_related_products)) return;
foreach ($node->field_related_products[LANGUAGE_NONE] as $term) {
  $terms[] = $term['tid'];
}

return implode('+', $terms);

Under "More" for this filter, enable "Allow multiple values"

Under "Other > Query Settings" select "Distinct"


How can I make the taxonomy terms appear in a drop down list? How to make the taxonomy term in drop down list?

Vocabul

Drupal 6 taxonomy term in drop down list while creating new article.

Drupal 8 taxonomy term can't show drop down list while creating new article.

Thanks to @Bhuvana

I had just changed the setting, it's work.

Home > Administration > Structure > Content types > Technology


How can I debug why user_save() is being called twice? I have a site with a large number of modules (100+) installed and I have an issue with my rules firing twice, which appears to be caused by user_save() being called twice.  (I was able to confirm this by adding a dpm($account) in user_save(), which is printed to the screen twice on my dev site when I log in as an authenticated user and update that user's profile.

Now I'd like to find which contrib module is caused user_save() to be called twice (of course this assumes it is a contrib module). I'm not a developer so I'm getting stuck.  I have Netbeans set up with Xdebug and I set a breakpoint on user_save().  Then I started the debugger and logged in and updated a user account, but when I look at the call stack I see the following:

  /mysite/modules/user/user.module.include_once:424
  /mysite/includes/bootstrap.inc.drupal_load:1126
  /mysite/sites/all/modules/contrib/devel/devel.module.devel_boot:616
  /mysite/includes/module.inc.call_user_func_array:833
  /mysite/includes/module.inc.module_invoke:833
  /mysite/includes/bootstrap.inc.bootstrap_invoke_all:1097
  /mysite/includes/bootstrap.inc._drupal_bootstrap_page_header:2454
  /mysite/includes/bootstrap.inc.drupal_bootstrap:2214
  /mysite/index.php.{main}:20

And then when user_save() is called again (in the same page load) I see exactly the same output.  If it is a contrib module that is causing user_save() to be called twice, how can I find out which one it is?

It turned out Rules was the culprit.  I didn't realized that using the Set a data value action could cause user_save() to be called twice.


How to make a private file visible after changing file URI? My task is automatically convert image files to pdf, when they are attached to a certain field. So the field accepts both the images and pdf files, but converts uploaded images to pdf.
The field saves files to private directory.
If I do not apply the conversion, the files are accessible well. But when I apply conversion, I convert images to PDF then save the PDF file into the same directory with the same name but with .pdf extension using the following code in hook_entity_presave:

$file_field = $entity->get('field_invoice_file');
if ($file_field) {

  $file_value = $file_field->getValue();

  if ($file_value && !empty($file_value[0]['target_id'])) {
    $entity_manager = \Drupal::entityTypeManager();
    $file_entity = $entity_manager->getStorage('file')->load($file_value[0]['target_id']);

    if ($file_entity) {

      $filename = reset_m($file_entity->get('filename')->getValue()); //reset_m is my custom function that extracts string from an array of any deepness, do not focus on it
      $uri = reset_m($file_entity->get('uri')->getValue());

      $type = pathinfo($uri, PATHINFO_EXTENSION);

      if (in_array($type, ['png', 'jpg', 'jpeg', 'gif'])) {

        $file_dir_arr = array_reverse(explode('/', $uri));
        unset($file_dir_arr[0]);
        $file_dir = implode('/', array_reverse($file_dir_arr));

        $file_name_arr = array_reverse(explode('.', $filename));
        unset($file_name_arr[0]);
        $file_name_no_ext = implode('.', array_reverse($file_name_arr));

        $new_uri = $file_dir . '/' . $file_name_no_ext . '.pdf';
        $new_filename = $file_name_no_ext . '.pdf';

        mymodule_image_to_pdf($uri,
            $file_dir . '/' . $file_name_no_ext . '.pdf');

        $file_entity->set('filename', $new_filename);
        $file_entity->set('uri', $new_uri);

        $file_entity->save();
      }
    }

  }
}

I made sure that the pdf has been generated successfuly and can be opened in acrobat if downloaded and can be viewed in browser if it is in a public directory. So here is some permissions issue: http://mysite/system/files/myfile.pdf returns dark gray page with a little gray square with white borders in the middle of the page.
If I upload pdf without conversion, it works good, if I upload an image without conversion, it also works good. If I use the same conversion behavior but with files in public storage it also works good.
Please note that I do not get 403 or 404 error (I checked in browser console too), I get 200 response but it looks as I wrote above.

It sounds like Drupal is telling the browser that the PDF file is an image.

When you're modifying an existing file entity, File::save() will not change the filemime property of a file automatically. Drupal only does this during execution of ::preCreate().

The filemime property isn't being used when serving from the public dir, but is being used when serving from the private dir (where Drupal is serving the headers/payload instead of your web server).

Try executing $file_entity->setMimeType('application/pdf') or create a new file entity with your PDF artifact.


How to modify a form to have some field surrounded by 'Details'? I created a custom content entity with Drupal Console.
Three of its fields are defined this way:
// ----------------------------------------------------------------------------
    $weight++;
    $fields['picture'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Picture'))
      ->setSettings([
        'file_extensions' => 'gif jpeg jpg png',
        'file_directory' => 'sel',
        'alt_field_required' => 0,
      ])
      ->setCardinality(3)
      ->setDisplayOptions('view', [
        'type' => 'default',
        'weight' => $weight,
      ])
      ->setDisplayOptions('form', [
        'type' => 'image_image',
        'weight' => $weight,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
// ----------------------------------------------------------------------------
    $weight++;
    $fields['file'] = BaseFieldDefinition::create('file')
      ->setLabel(t('File'))
      ->setSettings([
        'file_extensions' => 'pdf',
        'file_directory' => 'sel',
        'description_field' => TRUE,
      ])
      ->setDisplayOptions('view', [
        'type' => 'file',
        'weight' => $weight,
      ])
      ->setDisplayOptions('form', [
        'type' => 'file',
        'weight' => $weight,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
// ----------------------------------------------------------------------------
    $weight++;
    $fields['link'] = BaseFieldDefinition::create('link')
      ->setLabel(t('Link'))
      ->setDisplayOptions('view', [
        'type' => 'link',
        'weight' => $weight,
      ])
      ->setDisplayOptions('form', [
        'type' => 'link_default',
        'weight' => $weight,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
// ----------------------------------------------------------------------------

And the corresponding form looks like this:

I would like to have the 'file' and the 'link' field in something like the 'Picture' field...
I updated buildForm :
public function buildForm(array $form, FormStateInterface $form_state)
  {
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;
    $form['link']['widget']['0']['#type'] = 'details';
    return $form;
  }

And I got this:

How can I do the same for the 'File' field (have it surrounded in some 'Details')?

I did it this way (thanks to @4K4 to put me on the right direction):

$form['fileDetails'] = array(
  '#type' => 'details',
  '#title' => $this->t('File'),
  '#weight' => 8,
);
$form['file']['#group'] = 'fileDetails';

$form['link']['widget']['0']['#type'] = 'details';

And I get this:


How to remove all users from a role? How to remove all users and their content from a specific role programmatically ?

Here are some quick code examples that I have used to add or remove user roles in Drupal 6. This can be very helpful if you are building a module for a specific site that has to manipulate user roles. Using this technique is not the most flexible solution as it limits itself to the roles configured on a specific site (based on role id and role name). However, you could easily add a database table and an administration section and make this more flexible if needed.

Here is an easy way to add a role:

//you will need to enter the uid of the user here, I am just using user 1

$user = user_load(1);

//first we check if the user has the role in question (using the rid of the role)

if (!isset($user->roles[7])) {
    //if not we add the role and set the role name based on what is entered
    //in the drupal role administration section
    $user->roles[7] = 'role name seven';
}

Here is an easy way to remove a role:

//you will need to enter the uid of the user here, I am just using user 1

$user = user_load(1);

//first we check if the user has the first role in question

if (isset($user->roles[8])) {

  //if so, we unset the role
  unset($user->roles[8]);

  $edit = array('roles' => $user->roles);
  user_save($user, $edit);
}

Here is an easy way to do a role swap:

//you will need to enter the uid of the user here, I am just using user 1

$user = user_load(1);

//first we check if the user has the first role in question

if (isset($user->roles[8])) {

  //if so, we unset the role
  unset($user->roles[8]);

  //now we check to see if they have the role we want to swap for
  if (!isset($user->roles[7])) {

    //if not we add this role
    $user->roles[7] = 'role name seven';
  }

  $edit = array('roles' => $user->roles);
  user_save($user, $edit);
}

check this link for more info my post
 How to remove all roles from a user?


How to link a view output to its node? I'm wondering if there is a simple way to link the whole view item output without modifying the template files. It is easy to link some fields to the node but I would like the whole view output to work as a link. Any suggestions?

Thank you very much.

If yo don't want to modify the template file you may implement it using js, some thing like this,

$('.title-class').parent().parent().click(function(){
      var url = $(this).find(".title-class").attr('href');
      windows.location = url;
});

BUT YOU MUST BE SURE THAT THE DIV DISPLAY MUST BE SET TO INLINE-BLOCK IN ORDER TO BE AS LARGE AS ITS CONTENT


Translating a taxonomy term does not populate content into fields When translating a node into another language it does the following:

automatically populates all fields with content from the source node on the edit form
ensures the two nodes are linked as translations
defaults to the second language (if only two enabled)

When you press 'translate' on a taxonomy term it loads a blank form (as if you are creating a new term).

How do I duplicate the behaviour of the node 'translate' link for taxonomy term 'translate' - to create the same one-click functionality?

I have found one compromise solution that needs Replicate & Replicate UI modules:

Go to relevant taxonomy term and click 'replicate'
Edit replicated taxonomy term as necessary and switch language
Create a new 'translation set' to link the two taxonomy terms as
translations of each other

This solution isn't suitable for my end-users because of the third step. The 'translate' feature for nodes automatically links the two pieces of content as translations.


Change Views Handler for entity schema field I want to have a numeric value in my db treated as boolean by drupal.

the field is defined in the hook_schema like this

    'myfield'  => array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => FALSE,
    'default' => NULL,
    'description' => "a field",

So Drupal Views module rightfully detects and displays it as a number.
However i want it to be a Boolean, so in my hook_entity_info i have

'views controller class' => 'StrutturaViewsController',

and then

class StrutturaViewsController extends EntityDefaultViewsController {

  public function views_data() {
    $data = parent::views_data();

    $data['struttura']['myfield']['field']['handler'] = 'views_handler_field_boolean';

    return $data;
  }
}

'struttura' is the name of the entity that i created, and the name of the table with the 'myfield' coloumn

My problem is that Drupal is still treating the value as numeric.

Am i missing something?

Sure. Adding a new answer to clarify.

To my knowledge (and by that i mean my "very limited Drupal Knowledge") there are 2 ways of mapping the information between schemas and Druapl handlers: by using a custom view controller as i tried to do in the first post, and by implementing the hook_entity_property_info_(). I still don't know why the former approach didn't work but the solution for me was to go with the latter. That is, i had to write

'myfield' => array(
  'type'  => 'boolean',
  'label' => t('clever label'),
  'description' => t('clever description'),

  // Map here the field from hook_schema().
  'schema field' => 'insert_name_of_schema_field_here',
),

Mind that you will have to map EVERY AND EACH of your fields in the schema once you start with this approach.

I also noticed that sometimes doing stuff (like changing ajax config) on the view rendering my entity seems to break the mappings, and i have to clear all caches to bring back my settings.

You can find more information Here


How to use panels_bootstrap_layouts? I am using the bootstrap theme together with panels_bootstrap_layouts.
The bootstrap layouts option does show up and I can successfully add my content (2 views) to my panel with boostrap layout (2 colums stacked): one view in the left column and one view in the right column.

My problem is that when I save and view the page, the views are displayed one on top and one on the bottom but never left and right as they are suppose to be even when the browser is at full screen size. The theme seems to correctly be informed of the viewport size because when I resize the browser window to smaller width, then the main menu changes aspect as it is supposed to for smaller screens. My panel however does not change aspect, my views are always top/bottom and never change to left/right.

Is there a setting somewhere I should change in order for panels_bootstrap_layouts to correctly follow the fluid design and rearrange panels according to viewport width?

There a few reason this might be happening

1st is your using a bootstrap 3 theme with bootstrap 2 panel layouts.

The 2nd is your not setting panels with the bootstrap grids width.

After you have choosen the bootstrap stack layout.

1.Click on "Save and update"

2.Then click on the little gear you will see a drop down menu

3.then click on option that say's "Change"

4.Then select the bootstrap layout option

5.Then you will be able to select the column width of the layout

6.Then save.

Then do the same for the other right or left column and now your column will be right or left. You can see example how to do this here

If you want to hide some panels from on a mobile or desktop display, then you
need to use bootstrap hide  and show classes which you can find here

1.goto panels gear
2.Select css
3.add the "hidden-lg" class to panels on desktop you want to hide or "hidden-sm hidden-xs" to panels you want to hide on mobile or tablet

I hope that helps


How often is settings.php called? And is $user available to it? I'm thinking about adding some handling to the settings.php code, to set the ini_set('session.gc_maxlifetime', 2880); value based on the role of the logged it (or not logged in) user.

i.e. for admin role, moderator role, I'd set a real long value so as to basically not ever get logged out due to idling too long, while writing a long article, or whatever, while for "lesser" roles, like a regular member, they'll get a regular, shorter maxlifetime.

My 2 questions:

1) Is the Global $user var available within settings.php, so I can check it for the user's roles?

2) How often does it get called? Only once during initial site load? Or every time a user loads a page? I don't want to be (re)setting the value every time a page loads.

The settings.php file is included on the first bootstrap phase (DRUPAL_BOOTSTRAP_CONFIGURATION), while the global $user is initialized on DRUPAL_BOOTSTRAP_PAGE_CACHE or DRUPAL_BOOTSTRAP_SESSION, which are both later bootstrap phases.

The settings.php file is included each times Drupal bootstraps, which means every time Drupal serves a page, including the ones served from its cache. As such, the settings.php file can use plain PHP functions or a restrict set of Drupal functions; in both the cases, the code cannot access the user variable. It is not even possible to initialize it using the database, since the database connection is initialized after the file has been included. (The obvious reason is that the database settings are contained in the settings.php file.)

Reference

drupal_bootstrap()


How do I hide an area in a template or layout if multiple regions have no content? I am able to set this up using a single check for a content in a region, but what if say 3 regions must all have content before the area is displayed?

Here's what I use in my templates when checking for a single region:

<?php if ($content['region-1']): ?>

Region 1 Content

  <?php print render($content['region-1']); ?>
<?php endif; ?>

But for checking multiple regions, Something like this?

<?php if ($content['region-1']['region-2']['region-3']): ?>

Region 1 Content

  <?php print render($content['region-1']); ?>

Region 2 Content

  <?php print render($content['region-1']); ?>

Region 3 Content

  <?php print render($content['region-1']); ?>
<?php endif; ?>

Your solution will work, but I think the best practice will be to make this check by preprocess 'theme_preprocess_page' and pass the result ( e.g. 'isRegionsEmpty') to the template. Then, in the template you only check one variable.


How to show a view of content types on another content type I have one content type 'class' and I have another content type 'lesson' and I want to easily display all lessons that belong to a class on the view of a 'class.' Is this possible and if so, how?

I would take a look at the "Panels" module, which allows you to create custom pages that can display multiple Views displays in one page.

-

Alternatively, instead of creating multiple content types, consider utilizing taxonomy terms to differentiate your classes and lessons.

For instance, create a list of terms for a new vocabulary "Class", which differentiates the different types of class.

Then, for each of your "Lesson" content type nodes, apply the specific class taxonomy term which applies.

Finally, you can create a View which displays Lessons content nodes, and have it filter the results to those Lessons which are tagged with a specific "Class" taxonomy term.


Cache-Control: no-cache despite allowing cache for anonymous users We have a D7 site I'm trying to cache with Varnish. The assets are caching fine but for some reason every page is served with this header:

Cache-Control:  no-cache, must-revalidate, post-check=0, pre-check=0

The pages are quite heavy to render and end users aren't authenticated, so I'd really like to find a solution. How can I find out if a module is preventing caching? What else could cause this? We have a similar site that plays completely nice with Varnish but I haven't been able to spot the difference yet.

Edit: I checked the site with http://www.isvarnishworking.com/ and it says Varnish is working - "sort of". That is, the age is smaller than one, meaning something is preventing the page from being cached. Below are the full response headers as reported by the service.

Server: Apache
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:  Mon, 27 Apr 2015 17:11:55 GMT
Cache-Control:  no-cache, must-revalidate, post-check=0, pre-check=0
ETag:   "1430154715"
Content-Language:   en
X-Generator:    Drupal 7 (http://drupal.org)
Content-Type:   text/html; charset=utf-8
Content-Length: 45567
Accept-Ranges:  bytes
Date:   Mon, 27 Apr 2015 17:11:56 GMT
X-Varnish:  1868715414
Age:    0
Via:    1.1 varnish
Connection: keep-alive
X-Varnish-Cache:    MISS

Inspect your HTTP headers and see if session or other cookies are being set. This is the most common cause of Varnish "not working." Also make sure you are not logged in, and you can test using http://www.isvarnishworking.com/ to see what headers are outputted. If you could paste the headers would be helpful.


Enter one thing but save the other I try to construct a field and I wonder how should I implement this process via Field API:

User enter some data to the field. Let's say, the data entered is a node title.
User hits the "Save" button, but what is actually saved in the database is the node ID of the node whose title has been entered by the user.

Something like this happens with the Entity Reference module: I enter the title of the entity (as I 'm getting assistance through autocomplete), but the module saves target_id, not the title I have actually entered.

How can I gain such behavior?

Create a module for example module name is rose. In that module implement  hook_node_validate

function rose_node_validate($node, $form, &$form_state) {
       //Check to see if this is the node form data you want to change
    if ($form['#form_id'] == 'contentType_node_form') {
        //based on the value provided in
        $form_state['input']['field_name']['und'][0]['value'];
        $new_info_data = 'some logic'; //get the data you would like to save .
        variable_set('new_info', $new_info_data); //Save the data in a variable.
    }
}

Then implement a hook_node_presave. As per our example

function rose_node_presave($node) {
    //check if the node type is the one you want to change the value
    if ($node->type == 'content_type') {
        $new_info = variable_get('new_info'); //get the value which was set in validation variable_set()
        $node->field_name['und'][0]['value'] = $new_info;
    }
}

I have implemented this on Drupal 7. A user enters instagram user name and I get the instagram id from instagram api and save it. Let me know if more explanation is required.

In this implementation users enters only address I get the Lat and Lng based on the address provided and save it in the database.


How to add others libraries such as Zenpen to WYSIWYG profiles? I would like to use an editor for Drupal like Zenpen. Is it possible to add that library (Zenpen) to WYSIWYG profiles?

You'll need to write a WYSIWYG module plugin. Here is an example module you could follow.

Here is a simple .inc from the WYSIWYG module itself. Wrap your Zenpen one in a module like Ueditor (above) and you're done.


How to get "Add another item" option for fields based on taxonomy terms The goal is to allow an autocomplete field that uses taxonomy terms, and which allows multiple entries from the same taxonomy list – for example a list of names & contact info for a field that allows "add all that apply." This works for a text field configured for autocomplete and "unlimited" values. It also works when the source is the User list. However with taxonomy term lists, the "unlimited values" choice does not produce the usual "add another item" option. Is there a way to resolve this?   (We want to be able to draw from a taxonomy list, to avoid inconsistencies in how a user might enter names and contact info.)

Problem solved by installation of the Taxonomy Single Tag module and the patch from #6 of this thread. Answer provided by "Poieo" on drupal.org. I have applied this and it is working as desired. However I noticed that without the patch, I was getting errors not only with the new field where the "Single tag autocomplete text field" widget was applied, but also with other fields allowing multiple-item adding – even though they were neither autocomplete nor based on taxonomy terms.


Is it possible to have pre-load elements in webforms? I have to add two elements (checkbox, texfield) in the creation process of the webform. This is because I want a simple terms and conditions inside all webforms. How can I do this?

You could pre-load the elements in a hook_ENTITY_TYPE_create hook:

mymodule.module:

  /**
   * Implements hook_ENTITY_TYPE_create() for webform entities.
   */
  function mymodule_webform_create(\Drupal\webform\WebformInterface $webform) {

    $elements = [
      'name' => [
        '#type' => 'textfield',
        '#title' => 'name',
      ],
      'other' => [
        '#type' => 'textfield',
        '#title' => 'other',
      ],
    ];

    $webform->setElements($elements);
  }


How to enable modules through configuration? I am trying to enable modules by adding them to core.extension.yml file without getting involved with Features, Configuration Installer or similar modules or profiles. The modules are enabled but their default configuration under module_folder/config/install or module_folder/config/optional are not imported. Is there a way to do this?

This will not works because you are only saying to Drupal that your module is installed, but when you install a module there are other process that need to runs to import the configs and execute the .install functions.

But you can create a new module that will install all the other modules, create a .install file and add this inside:

/**
 * Implements hook_install().
 */
function MY_MODULE_install() {
  $modules_list = [
    'nbsp',
    'typogrify',
    'other_module',
  ];
  \Drupal::service('module_installer')->install($modules_list);
  drupal_flush_all_caches();
}

And then you only need to install this module that will install all the other modules.


How to bypass/skip payment after checkout in Ubercart? I've tested Ubercart with Sagepay sandbox and it's very inconvenience to enter every time the payment. Another disadvantage is that when working on internal hosts, the redirection URL from external payment gateways never works, therefore when testing, payment is never completed.

How it's possible to bypass payment after checkout and make the order completed for testing purposes? Is there any option or module?

One way to do this using the combination of ubercart custom payment module and ubercart discount coupon module, i.e creating a coupon of 100% discount and to bypass the payment process you will need the ubercart custom payment module (by default it provides the rule that can use it).
Ubercart Discount Coupons: Coupons can apply either a fixed price discount or a percentage discount to the order subtotal or to selected product prices.

Coupons are configured at Store administration > Coupons. Global settings for the module are configured at Store administration > Configuration > Coupon module settings.

Ubercart Custom Payment module:

provides a "Free Order" payment method, and a default Rules configuration is provided to enable this.


How do I Send a single mail with Rules and VBO? I have a view of nodes that I edit with VBO. I filter this nodes by author. When I edit this nodes I send a mail to author with a rule but I have a problem when I edit more than one nodes with VBO. In fact Rule sends as many email as they are the nodes.

How I can do to send only a single email to the author that I have filtered in the views?

I use Drupal 7.

UPDATE: I've added the rule that I'm using but not works

{ "rules_send_mail_to_owner" : {
"LABEL" : "Send Mail to Owner",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_i18n" ],
"ON" : { "node_update--prenotazione" : { "bundle" : "prenotazione" } },
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "list\u003Cuser\u003E" },
      "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
    }
  },
  { "list_add" : {
      "list" : [ "variable-added" ],
      "item" : [ "node:field-proprietario" ],
      "unique" : "1"
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "variable-added" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "mail" : {
            "to" : "giupenni78@gmail.com",
            "subject" : "Prova notifica LCS",
            "message" : "Questa \u00e8 una prova\r\n[node:field-proprietario]\t",
            "from" : "info@lowcostsicilia.it",
            "language" : [ "" ]
          }
        }
      ]
    }
  }
]
}
}

Here is a blueprint to do what you're asking about:

Create a new variable, which you define as a "list of users" (so that you can use this list later on to "loop through this list").
Replace the "send an eMail" (within your existing Rule) by an action to  "Add an item to a list" (using the list you created via that new variable). When doing so, you make sure to set "ENFORCE UNIQUENESS" to true, so that you "only add the item to the list if it is not yet contained" (see where I'm going?).
In the end, the value of the new variable will contain a list of unique users. So just add another Rules loop (at the end?), to iterate over each of the users in that list. And guess what you can then do in this additional Rules loop ... indeed: send an email to each of those users. And since each user is only contained 1 time in that list, they will only receive 1 eMail.

Easy, no?


How to create multi level subgroups in organic groups? I Need to create multi level of subgroups in organic groups like

like a tree. I don't know how to create using organic groups. Can anyone suggest.

Apparently, there is a module for this: Subgroups for Organic groups

According to the module description,

  This module enables a user with the proper permissions to build group
  hierarchies (or tree) by nesting groups under other groups. Simple or
  complex group hierarchies can be easily created.


How do I force rebuilding/generation of files generated by an imagecache preset? I edited the actions on one of my imagecache presets, but it has only generated a few pictures (instead of hundreds) of pictures.

I am using the preset to in a view to show thumbnails that belong to nodes of a specific content type with the help of a module called teaser thumbnail. All the thumbnails on the first page of the view have been generated correctly, but beyond that, none of the thumbnails have been generated.

I am using Drupal 6.25 with public file system on a shared hosting server.

So the main question is how do forcefully rebuild/re-generate the pictures associated with preset?

Edit : I have already used the 'Flush' function on the preset.

Imagecache images are generated on the fly when a browser requests them, rather than when you create the preset or flush the images.

Basically, this is how the process works.

When a URL 404s, the request gets punted to /index.php and handled by Drupal.

The imagecache module has a hook_menu() entry that handles all of the requests to sites/default/files/imagecache (or whatever file_directory_path() returns for your site).

The callback for this checks for the requested filename.  If the file exists (ie, the derivative has been generated and exists in the filesystem), it gets served up.  Otherwise, the module makes the derivative, saves it to the filesystem, and then serves it up.

So, the net result is that you don't need to explicitly generate the derivatives.  When a page that has them on it is requested, they will be automacically generated.

If you would like to pre-generete them for performance reasons, then my suggestion would be to write a bash script to find all of the images in your sites/default/files directory, and then wget them with the proper imagecache preset path name.

If you are looking at a page and the thumbnails aren't being shown, then you have another problem.  Checking the system report would be the first place to check.  Typically, the webserver can't write to the filesystem or your image toolkit is messed up.


How to download Database results as PDF or in EXCEL I have a custom query to fetch the details from database (oracle). The results are generating properly as expected. Now i need to download these results either a PDF or an EXCEL file. Any way to achieve this

By Views PDF module you can output a View as a PDF.

  With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

Since you have your custom query, by Custom query in Views you can alter the results of the View. The print the output of view is PDF using the above module.

UPDATE

Since you created a node and fetch database result via that node you must use Printer, email and PDF versions module

  This module allows you to generate the following printer-friendly versions of any node:

  Printer-friendly version (webpage format) (at www.example.com/print/nid)
  PDF version (at www.example.com/printpdf/nid)
  EPUB version (at www.example.com/printepub/nid)
  Send by email (at www.example.com/printmail/nid)

where nid is the node id of content to render.

so by www.example.com/printpdf/nid you can create a  PDF output of the node.


Programmatically (via php code) create content of a specified type In drupal 8 I have created a bespoke content type... I now would like to create content of the bespoke content type via Php through user interaction.  For example, the user clicks a button and it triggers a function in my module which I am creating.

I have used the following code:

$node = Node::create([
  'type'        => 'article',
  'title'       => 'My title',
   ]);
   $node->save();

Which does create content in the content area of the admin panel, but... The content type column is empty?

Am sure someone will all ready have done this type of thing before so any help will be most welcomed.

Thanks Ivan Jaros and Kevin ... Once I placed the machine name of the content type (rather than it's human readable title) as the type value the content created successful and was of the required type e.g.

$node = Node::create([
    'type'        => 'the machine name associated with the content type',
    'title'       => 'My title',
   ]);
 $node->save();


Drupal 7: Edit/delete is not working on the custom module I am a newbie to drupal. I am working to create a custom module in the name "course". I have read about the list of hooks to create a custom module. So, what's my problem is that i cant able to see the edit form for the module configure but i can do add management and its working fine.
I've used Existing contact modules as a reference.

Below are my code:
In course.module

function course_menu() {
  $items['admin/structure/course'] = array(
    'title' => 'Academy\'s courses',
    'description' => 'Create a system contact form and set up categories for the form to use.',
    'page callback' => 'course_list',
    'access arguments' => array('administer contact forms'),
    'file' => 'course.admin.inc',
  );
  $items['admin/structure/course/add'] = array(
    'title' => 'Add Courses',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('course_edit_form'),
    'access arguments' => array('administer contact forms'),
    'type' => MENU_LOCAL_ACTION,
    'weight' => 1,
    'file' => 'course.admin.inc',
  );
  $items['admin/structure/course/edit/%course'] = array(
    'title' => 'Edit Courses',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('course_edit_form',4),
    'access arguments' => array('administer contact forms'),
    'file' => 'course.admin.inc',
  );

  return $items;
}

and in course.admin.inc:

function course_edit_form($form, &$form_state, array $course = array()) {
  // If this is a new course, add the default values.

  $course += array(
    'name' => '',
    'course_id' => NULL,
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Course Name'),
    '#maxlength' => 255,
    '#default_value' => $course['name'],
    '#description' => t("Example: 'Available Course Names'."),
    '#required' => TRUE,
  );

  $form['course_id'] = array(
    '#type' => 'value',
    '#value' => $course['course_id'],
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}

function course_edit_form_submit($form, &$form_state) {

  if (empty($form_state['values']['course_id'])) {
        db_insert('courses') // Table name no longer needs {}
        ->fields(array(
          'name' => $form_state['values']['name'],
          'course_url' => $form_state['values']['name']
        ))
        ->execute();
    //drupal_write_record('courses', $form_state['values']);
  }
  else {
     db_insert('courses') // Table name no longer needs {}
        ->fields(array(
          'name' => $form_state['values']['name'],
          'course_url' => $form_state['values']['name']
        ))
        ->condition('course_id', $form_state['values']['course_id'])
        ->execute();
    //drupal_write_record('courses', $form_state['values'], array('course_id'));
  }

  drupal_set_message(t('Course %name has been saved.', array('%name' => $form_state['values']['name'])));
  watchdog('contact', 'Course %name has been saved.', array('%course' => $form_state['values']['name']), WATCHDOG_NOTICE, l(t('Edit'), 'admin/structure/course/edit/' . $form_state['values']['course_id']));
  $form_state['redirect'] = 'admin/structure/course';
}

I can't able to find the exact problem, why add is working but not edit & delete? Help me on this.

Below image tells you what exactly i am asking for(Red mark).

If anything additional needed in this please let me know.

You are using an Auto-Loader Wildcard in your menu item definition for admin/structure/course/edit/%course. This wildcard defines the prefix for the load function of your module. In your case course_load() will be called which returns a course object from a datasource.

If the function is not found it will fallback in any of your parent menu items. In your case it is admin/structure/course.

This could be an example of you load function

function course_load($course_id)
{
    return db_query("SELECT * FROM {course} WHERE course_id = :course_id", array(
        ':course_id' => $course_id
    ))->fetchObject();
}

Your course_edit_form doesn't receive an array of courses but 1 course object as third argument.

function course_edit_form($form, &$form_state, $course)
{
     // $course is here your Course object


Import or Programmatically create nodes with Videos I'm working on a new drupal site which I need to migrate from an existing non-drupal site. I need to be able to import the old blog posts as Article nodes (either through some standard import mechanism or I can write some php to programmatically create the nodes).

However, I'm not sure how to handle creating Image and Video data in a node, especially with the need for transcoding video after creation of the node. So, two questions:

1) How can I programmatically create nodes with binary Image and Video data?

2) When I do create a node with Video data, will the post-create transcoding job be started? I'm using Zencoder to do my transcoding.

I am not using the local filesystem for drupal, I'm storing all of my files in Rackspace Cloud Files, however, I can handle it if I need to use the local filesystem temporarily during import and then manually move things over to Cloud Files. This is only a one-time event.

Your best bet is to use the Migrate module. It's got a kinda steep learning curve but plenty of documentation available.

The Migrate Extras module provides integration with the Media module, which could help with the video field specifically.


Multi site cron set up I am doing some updates on existing drupal multi site set up and am unable to set up cron for subsites. Subsites are accessed in a different way (example.com/site1 example.com/site2 )
From browser accessing example.com/site1/cron.php runs the cron but its not running from crontab.

45 11 * * * /usr/bin/lynx -source http://example.com/site1/cron.php
45 11 * * * /usr/bin/wget -O - -q -t 1 http://example.com/site1/cron.php
45 11 * * * curl --silent --compressed http://example.com/site1/cron.php

Tried all these but its not triggering cron functions.

It was not resolving the host names. Added an entry to /etc/hosts and it worked fine.


Default Breadcrumb is not working in bootstrap drupal 8? I have rendered the breadcrumb in page.html.twig

{# Breadcrumbs #}
    {% if breadcrumb %}
      {% block breadcrumb %}
        {{ breadcrumb }}
      {% endblock %}
    {% endif %}

and default breadcrumb block is available in the block layout. And then I have assigned in the block in Highlighted region.

When I debugging the breadcrumb, its not working properly.

Please help me , how to sort out this issue?

The twig code doesn't work and you don't need it for the breadcrumb block to be available in the block layout. It's the other way, first you assign the breadcrumb block in for example the Highlighted region. Then you print the region with the breadcrumbs in page.html.twig:

{{ page.highlighted }}

In D8 it's not possible to access the breadcrumbs in the page template directly. You have to use a Drupal block. See https://www.drupal.org/node/2410773.

BTW Twig Blocks are not connected to Drupal blocks. They are used to extend templates:

  Blocks are used for inheritance and act as placeholders and
  replacements at the same time. They are documented in detail in the
  documentation for the extends tag.


Drupal 7 ckeditor relative path setup issue We are developing a site using drupal 7
So we created drupal site with name of myapp, so the url is http://localhost/myapp

Also another developer is working for same site in his development machine with the name of myapp2
so its http://localhost/myapp2

I have installed ckeditor for rich content and configured relative path for inserting images.

When I insert an image in myapp site the relative path comes like 'myapp/sites/all/files/images/img1.jpg' instead of 'sites/all/files/images/img1.jpg'

hense when I share my database with my other team member uses myapp2 they are not able view the inserted images. their path looks like this 'myapp2/myapp/sites/all/files/images/img1.jpg'

I have used pathologic to setup the two users urls in Text Format setting page
like http://localhost/myapp and http//localhost/myapp2 but not works as expected.

any one help me what else I can do to solve the issue.

Pathologic will solve your problem, in the configuration of the filter put both http://localhost/myapp & http://localhost/myapp2 and the filter should work everything out


Google docs style drupal site Ive been searching around drupal and google to find some awnsers but get lost and fustrated and came here for some help.

What i want to do is have a drupal site which is not public, and has the functionality of google docs, calendar and drive...yes i know i could just use what google have already made but im a little paranoid in this world and would like to have TOTAL control over my documents as this will also be on a dedicated server.

So are there modules/ways out there where i can upload/download + edit text documents and spreadsheets? I know i could use a WYSIWYG but could i then download the page/node as a .doc file for example?

Sorry if it doesnt make much sense,
Many Thanks in Advance
Russel

An all in one solution I think is hard to find/make for drupal.
There's a module, where you can import and edit spreadsheets. I've testet it briefly for a project, that never go further than prototyping, but the module simply worked:
http://drupal.org/project/sheetnode

There might be similar projects for word processors. Or you might have it made :)

For a Google drive alternative, where you are in control, have a look at http://owncloud.org. They have calendar, contacts, and many other things, but I don't think they have editors.


Private files return 404 not found I have a problem whereby any files uploaded into the private directory cannot be viewed - returning a 404 not found error. The images upload ok and get placed in sites/default/files/private directory. The image path when trying to view is in the form /system/files/image.jpg which I believe is correct.

Firstly I found that there are conflicts with the Fast 404 module. Disabling this module makes the private files now work on my staging server, but not on our live server.

Could there be any server-side settings that could be affecting this?

What else should I be checking?

Merely disabling the Fast 404 module isn't enough if you are calling fast_404_ext_check(); in settings.php.  Be sure you've removed the Fast 404-related settings from settings.php.

Due to the way private files are implemented in Drupal, you will never be able to use private files with the extension-checking features of Fast 404.


Fatal error: Call to undefined function quiz_type_access_load() Getting the following error after switching servers. The setup is multisite on a linux box. The troublemaker is on subdomain.
So far:
disabled quiz and quiz submodules,
cleared the cache, nothing really works.

Fatal error: Call to undefined function quiz_type_access_load() in /path/to/drupal/includes/menu.inc on line 411

Try to find and delete records in "menu_links" and "menu_router" tables of your database which have "quiz_type_access_load" occurrences.

Be careful: backup the database first!


What's the correct way to make it so that node_load both loads and caches additional, custom data? For example, I'd like node_load to load the path alias of the node, and cache it for future node_load calls (just like node_load caches all of the data, i think). I assume this is done in a module, but I haven't been able to find examples of this.

The hook you're after is called hook_node_load(). I think the example from that page is probably the easiest to understand:

function hook_node_load($nodes, $types) {
  $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
  foreach ($result as $record) {
    $nodes[$record->nid]->foo = $record->foo;
  }
}

The example loads some custom data from a table, based on the ids of the nodes passed into the function. It then loops through the query results, and adds the custom data to the relevant node objects.

When you call node_load() or node_load_multiple() for nodes that haven't been cached yet, your hook_node_load() function will be called and the custom data added.

Next time you call those functions for the same nodes your hook won't be called, but the node objects returned from the static cache will already have your custom data attached to them.


How to create a list of file fields with checkboxes selector? We all know that by default drupal allows the users to create Lists consists of (float, integer, decimal and text) field types that can be useful for webforms element,
but this kind of list can't be very useful and haven't enough efficiency in content type (of course this is my personal opinion only) However,
I think this kind of list can be more flexible and powerful if combine with other types of field like Link and especially in the case of Files.
Because these kind of fields (Link & File) consists of two components Title (can be equal to field label For more convenience) that can be Stable and Value that can be Unstable.
for example I have a predefined, stable and limited list of title, List(text) and against of it there is a list of unstable and changeable of file fields in my custom content type, for this reason I decide to combine the power of lists (like default drupal list(text)) with file upload fields and create new and more powerful field type like List(file) something like below:

Advantages of this field:

Not have to change the Description (Title or label of the link) of file field eachtime that you want to upload or update a new file
Not have to change ugly file names like '102-32.exe' to something
can be more human readable.(If you want to use generic display format)
Get rid of any change or add more complexity to template files.

Add 4 file fields to your content type with desired labels (ex. "Win 64bit"),
Then you will have this 4 fields in your add content form.

Now it's time to make them optional, first of all using hook_form_alter you can add 4 new elements of class "checkbox" to your form like this:

$form['dependent']['win64'] = array(
  '#type' => 'checkbox',
  '#title' => t('Win 64bit'),
);

and then for your fields add a #states like below :

$form["win 64 file field"]= array(
  '#states' => array(
    'visible' => array(
      ':input[name="dependent[win64]"]' => array('checked' => TRUE),
  ),
);


In which folder should I install Composer on a shared linux server? The "Questions that may already have your answer" do give various instructions on how to install Drush and/or Composer, but they don't address my question. I did come across this comment:

Q: drush - which folder for install on VPS / root server (newbie):
A: "You can install Drush in the folder of your choice. Preferably outside www-directory."

My question: I'm not sure if this is applicable to Composer as well?
And if it is applicable to Composer as well, why do people give specific folders into which Composer must be installed into?

The reason for my concern into which folder I install Composer is because I want to run it without problems (in any case with as little as possible).

I'm listing the different options:

mdir bin, cd bin, install Composer in [~/bin] directory.
Install in /home/username/bin
Install in [~/bin] and move to /usr/local/bin
Install in the /usr/local/bin folder
That is a hidden folder, I can access it if I say "cd /usr/local/bin" in my terminal, but it doesn't show in the file manager of cpanel. How does that relate to /home/username/bin (or doesn't it)?
Install in the public_html folder (home/username/public_html)
One article says that Drupal is installed in the /var/www/drupal folder.
Another articles says that Drupal is installed in domains/websitename.com/htdocs/www

It seems to me that the [~/bin] directory is the preferred one?

TL;DR My recommendation would be /usr/local/bin

It doesn't really matter as long as the directory is in the PATH of all users, and as long as it is not one of the locations which the OS wants full control over (those would be primarily /usr/bin and /bin).  For most situations, a reasonable location is /usr/local/bin because it should already be in the system's default PATH and it is intended precisely for this purpose -- local installations which are not part of the OS proper.

For Linux, you might want to refer to the LHS entry; this standard codifies usage inherited from the original Unix.

If it's convenient for you, installing in $HOME/bin and then moving to a system-wide location is fine.  In fact, most make install etc facilities expect you to be doing something like this.


job schedule skip a job In job schedule module, I have bunch of jobs that works, What I want to do is give the admin the ability to stop a certain job as he desires.

The only way I could do is that I could remove the job all together from the table with this:

  JobScheduler::get($job['name'])->remove($job);

and I would recreate it again.

But isnt there a way to skip the job instead of deleting and recreating it again? Rules maybe?

I ended up deleting the job and recreating it again.

here is how just incase.

// job_id = the job id in job_schedule table.
// $import_status = weather we want to delete or create a job.
// $importer_type = I had 2 types of importers to switch between.
// $original value = only recreating a job if it was deleted first.

function schedule_conrtol($job_id, $import_status, $importer_type, $original_value) {
  if ($import_status === 1) {
    // Deleting a job
    $job = array('name' => 'job_name',
                 'type' => $importer_type,
                 'id'   => $job_id
                );
    JobScheduler::get($job['name'])->remove($job);
  }

if ($import_status === 0 && $original_value === "1") {
    // Inserting a job
    $job = array(
    'name'     => 'job_name',
    'type'     => $importer_type,
    'id'       => $job_id,
    'period'   => 1800,
    'periodic' => TRUE,
    );
    JobScheduler::get($job['name'])->set($job);
  }

}

and you can control this using hook_node_presave

hope this helps.


referenced node in primary tabs I am looking for a way to show a referenced node into the primary tabs menu.

I created a content type "fact box" that is referenced to an article.
Now i like to have the content type title of the fact box node in the primary tabs menu.

I tested the Quicktabs Module and References Tabs, but they don`t use the primary tabs menu.

What`s the right way to reference a node into the primary tabs menu?

Is this for Drupal 7?

If so you can create a custom module using hook_menu_local_tasks_alter, maybe in the hook get the arg for the nid for the current page. Then do a node load on the current pages nid to check a reference is set, then from this reference field which will contain the nid... do another node load to get its title. Finally the title local menu tab.


Getting an fatal error message when trying to render custom blocks on my node twig template I'm trying to render or print my custom blocks on my node twig template and currently receiving a fatal error message.

Argument 1 passed to Drupal\block\BlockViewBuilder::view()

Here is the snippet of code I'm working on my .theme file

function iom_preprocess_node(&$variables) {

    $block = \Drupal\block\Entity\Block::load(917);
    $block_content = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
}

$block returns NULL when I try to do a dump($block)

$block = \Drupal\block\Entity\Block::load(917);
dump($block);

Tried using twig tweak also to resolve the issue instead of having to pre-process it but no luck

{{ drupal_block('twitterfeed') }}

You can print blocks directly using Twig Tweak

  {# No need to configure this block on "admin/structure/block" page. #}

Block:

{{ drupal_block('system_branding_block', {label: 'Branding', use_site_name: false}) }}

  {# Bypass block.html.twig theming. #}

Block (without wrapper):

{{ drupal_block('system_branding_block', wrapper=false) }}

Source: Cheat sheet

Do not use the block's machine name, enable the devel and in block configuration click on Devel tab to get the Plugin ID.

For example, the Site Branding Block has machine name of sitebranding, but the plugin ID is system_branding_block


Prevent email from being sent using hook_mail? I'm trying to implement an access check (a 'do-not-send' list query) just before emails are sent.
I see how to modify the message, but how do I stop a message?.

HOOK_mail ($key, &$message, $params) {
   if (TRUE) {
      // -- Stop Message From Being Sent Here -- //
   }
}

Is break; adequate?

You can do the access check from hook_mail_alter instead of hook_mail (let it prepare the default message based on parameters, and alter it later) by something like:

function HOOK_mail_alter(&$message) {
  // can add additional check for particular mails here,
  // by checking the value in $message['id']
  if (TRUE) {
    $message['send'] = FALSE;
  }
}

Note: You should clear the cache in order to make the changes effective.


How to run PHP code only once on node creation? I'm using Drupal 7, and the Computed Field module.
I want to run code just once, when the node is created.

Is there any specific function?

If you want to run code just once when a node is created, the Rules module may be a better choice.

Using Rules, you can do the following:

Create a new rule that acts on the event "After saving new content."
As the action, "Set a data value" and target the field you want to modify (this would be a standard field rather than a computed field in this case).
As the "Value", input your PHP code in php tags.

This way the code will be evaluated only once.


Form with throbber not responding to validate or submit methods I have the following form built with Form API. Its method is GET. I try to validate or submit, but it does not work. I have checked the method names, etc., and are correct, in fact I see an "attempt" of validation in some cases. I guess that there is something weird for the way I use the select autofilling field. It is a "car models" select whose values are filled by selection of "car brand" select, and I think that the code somehow interferes with the normal use of Form API.

function mymodule_search_form(){
    $brands = get_brands();
    $brand = get_default_brand();

    $form['product'] = array(
      '#type' => 'textfield',
      '#title' => t('Product'),
      '#autocomplete_path' => 'product-busq/productos/all',
      '#attributes' => array("placeholder" => t('Product'), ) // 'class' => array('auto_submit')
     );

     $form['brand'] = array(
       '#type' => 'select',
       '#title' => t('Brand'),
       '#options' => $brands,
       '#default_value' => $brand,
       '#ajax' => array(
           'callback' => 'mymodule_models_update',
           'wrapper' => 'models_wrapper',
           'progress' => array(
           'message' => '',
           'type' => 'throbber',
          ),
         ),
        );

    $form['model'] = array(

      '#type' => "select",
      '#title' => t('Model'),
      '#required' => FALSE,
      '#multiple' => YES,
      '#attributes' => array("placeholder" => t('Model'), ), // 'class' => array('auto_submit')

       '#prefix' => '
',
       '#suffix' => '
',
       '#disabled' => TRUE,
      );

  $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Submit'),
      '#name' => ""
 );

   $form["#action"] = $base_url . "/" . $language->language . "/" .   drupal_get_path_alias("node/3");
  $form["#method"] = "get";

  return $form;
} // function

And now the autofilling function which may be causing the problems, especially the last sentence. The code is copied from a tutorial somewhere:

function mymodule_models_update($form, &$form_state) {
   unset($form_state['input']['model'], $form_state['values']['model']);
   $brand = $form_state['values']['brand'];
   $brand_desc = "";
   $results = db_query("SELECT description FROM {taxonomy_term_data} tax WHERE tax.tid = :tid", array(":tid" => $brand));
    foreach($results as $row) $brand_desc = $row->description;

    if($brand_desc != "") $form['model']['#options'] =      _hook_list_models($brand_desc);
    unset($form['model']["#attributes"]['disabled']);
   $form['model']['#disabled'] = FALSE;
   $form["model"]["#attributes"]["id"] = "edit-model";
   return form_builder($form['#id'], $form['model'], $form_state);
 } // function

According to the Drupal official documentation on drupal_build_form.

  method: The HTTP form method to use for finding the input for this form. May be 'post' or 'get'. Defaults to 'post'. Note that 'get' method forms do not use form ids so are always considered to be submitted, which can have unexpected effects. The 'get' method should only be used on forms that do not change data, as that is exclusively the domain of 'post.'

I would recommend you using POST method rather then GET method, so please remove the line $form["#method"] = "get";

Also, you should rewrite your ajax callback.

function hook_models_update($form, &$form_state) {
   unset($form_state['input']['model'], $form_state['values']['model']);
   $brand = $form_state['values']['brand'];
   $brand_desc = "";
   $results = db_query("SELECT description FROM {taxonomy_term_data} tax WHERE tax.tid = :tid", array(":tid" => $brand));
    foreach($results as $row) $brand_desc = $row->description;

    if($brand_desc != "") $form['model']['#options'] =      _hook_list_models($brand_desc);
    unset($form['model']["#attributes"]['disabled']);
   $form['model']['#disabled'] = FALSE;
   $form["model"]["#attributes"]["id"] = "edit-model";

   $form_state['rebuild'] = TRUE;
   return $form['model'];
}

IMPORTANT NOTE:

If you can, I would suggest you rename your function or module name to avoid using hook_ prefix. It would cause unexpected function name conflict in future, because hook_ prefix is reserved for building hook API in Drupal.


How to customize commerce order layout I'd like to modify the current order layout visible at user/[uid]/orders/[order_id]

Specifically, I'd like to list the billing and shipping info before the line item detail:

billing and shipping
List item detail
subtotals

I know that the the line item detail is a View that can be edited, but I'm not sure how to control placement/sequence of items not in this view.

Thanks in advance for any tips or advice.

For reference there are a couple answers depending on the situation. The order of the field display can be controlled by going to store->configuration->order settings->Manage Display which I believe would solve the OP question.

If you are looking to setup a custom .tpl.php file I wasn't able to successfully use the template suggestions which are:

commerce_order
commerce_order__commerce_order
commerce_order__commerce_order__customer
commerce_order__OID (where OID is the order ID)

I found these in template_preprocess_entity in $variables['theme_hook_suggestions']

However, since an order is an entity I was able to use http://drupal.org/node/1238606 (tutorial on theming custom entities) and use a template of my own choosing.

template.php

/**
* Process variables for MYTEMPLATE--order.tpl.php.
*/
function MYTHEME_preprocess_MYTEMPLATE(&$variables) {
  // This is the generic entity preprocessor
  template_preprocess_entity($variables);
}

/**
 * Implements hook_entity_view_alter to alter the entity theme used by
 * commerce_order.
 */
function MYTHEME_entity_view_alter(&$build, $type) {
  if('commerce_order' == $type){
    $build['#theme'] = 'MYTEMPLATE';
  }
}

From there you can use: sites/all/modules/entity/entity.tpl.php as a template for your template.

Hope this helps someone.

Cheers,

Rob


Saving a Form with Custom Button I am trying to create a custom button that modifies a field in a form then saves the form in the same way as the default save button. The following code creates the button but I am having trouble finding where/how to perform the operation that clicking the default save button executes, with validation and updating every field before executing my submit code.

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

     if ($form_id == 'submission_node_form') {
         $form['actions']['final_submit'] = array(
            '#type'   => 'submit',
            '#value'  => t('Submit'),
            '#submit' => array('mymodule_form_final_submit')
         );
     }

}

function mymodule_form_final_submit($form, &$form_state) {

}

A simple way is calling drupal_form_submit  in your custom module

function mymodule_form_final_submit($form, &$form_state) {

  drupal_form_submit('submission_node_form', $form_state);

}


Remove disabled attribute/state during submission I would like to find a way to remove the disabled attribute from webform fields inside a custom Handler.

The disabled attribute is currently being applied to webform elements during user input via conditions/states with the UI and I would like to remove this attribute after clicking submit so that these webform fields will submit their values.

I've been looking through the available functions from the WebformhandlerBase: https://git.uwaterloo.ca/drupal-org/webform/blob/8.x-5.9/src/Plugin/WebformHandlerBase.php, but can't find where this attribute exists, and don't see an approach to alter/remove it.

public function validateForm() {} seems like a good moment in time to alter, but I can't find this attribute.

Noting I have success doing this with jQuery but would prefer doing this in my custom Handler

How do you remove a form field attribute (disabled) with a custom Handler after a user clicks submit?

Once you submit a form, you are not able to retrieve disabled inputs (https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set). That said:

You cannot modify input's attributes from server-side since the submission data is already posted.
Developing your solution with jQuery on .submit() function is a good idea (far away from bad practices).
You can also make another work around: instead of disabling you could use readonly="readonly" attribute (https://www.w3.org/TR/REC-html40-971218/interact/forms.html#h-17.12.2)


Auto-filling a form field with the sender page title Basically, the user clicks on a "Book" button, which is in a "Trip" node; the user then is redirected to a booking form (Webform) where he will fill in basic info for the reservation. I need to auto-fill a field in the form with the title of the node from where the user was redirected.

I tried to use the Rules module and I successfully made the redirection process, but I'm stuck on how to prepopulate the field with the title of the sender page.

I've never developed a custom module, I'm new to Drupal but I have programming experience, so if there is a straight way to accomplish this (contrib modules) that would be great. Alternatively, I'm not afraid of digging into code.

You could find the referring page by using $_SERVER['HTTP_REFERER'] in PHP and then lookup the node by using drupal_lookup_path and menu_get_object. At that point you then have the node object from the previous page and you can use "$node->title" to get the title you want.

$request_url =  $_SERVER['HTTP_REFERER'];
$host = $_SERVER['HTTP_HOST'] . "/";
$request_uri = explode($host,$request_url);
$path = drupal_lookup_path("source", $request_uri[1]);
$node = menu_get_object("node", 1, $path);

As far as how you put this into the webform, you could alter the submission using a hook or a specific component. I'm not aware of a module that lets you put PHP into a webform component. Potentially the Computed Field module (https://drupal.org/project/computed_field) could be of help.

Help from: How to get a node by its url alias?


How can I upload photos from iphone/Android to Drupal? I know that I can build iphone/Android apps with frameworks like phonegap and titanium.

I wonder if there is an easier way? Aurigma Up seems like an interesting idea. Has anyone used this or similar apps?

phonegap and titanium are probably considered easier than for example, developing a separate native app for iOS and Android.

However, if you are looking for something even easier, perhaps you could explore using an existing application that uploads images to a service such as Flickr. A query for iPhone apps on Flickr's App Garden provides plenty of results. You could then use an app such as this one to upload images and then use Flickr's API to create image galleries in Drupal. Plus, you can make calls to Flickr from Drupal and receive data in different formats including JSON and XML. It really doesn't get easier than that.

The Flickr contrib module could then provide you with plenty of examples of how to query Flickr's API.

The fact that your images would be hosted by a third party could be seen as good or a drawback, depending on how you analyze it.


Programmatically displaying a view into a colorbox Love the module. My use case is to take programatically take the result of a view and load it into a colorbox. I can use views_get_view or views_embed_view to get a result array or a large html string. But how can I pass that to the colorbox?

Any help is greatly appreciated.

https://drupal.org/node/1991948

Put your view into a div with a wrapper that is hidden (ie, display:none;). Then you can use the following javascript:

$.colorbox({
    'inline' : true,
    'href' : $('.views-view-my-view'),
});

You must replace the 'href' attribute with the appropriate jQuery collection representing your view. Other customisations to the way your colorbox appears can be found here.

If you need some advice on placing a view on your page, here is a clean implementation:

function MODULE_preprocess_page(&$vars) {
  $vars['page']['bottom']['my_view'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'my-view-container',
    ),
    'children' => array(
      '#markup' => views_embed_view(...),
    ),
  );
}

In this case your selector for colorbox would be #my-view-container .view


Taxonomy term via Rest API returns 406 Not Acceptable I can't get the Taxonomy terms to work with the Rest API. I've used the Rest UI module to enable the Taxonomy Term for the Rest API, and enabled all formats.

When I request http://www.domain.com/taxonomy/term/1?_format=json though, I get the message:

{"message":"Not acceptable format: json"}

Same for for hal and xml. Everything works fine for nodes, so I suspect a bug somewhere. Using 8.2.6 .

This works as expected using Drupal 8.3.x using latest Rest UI Mar 28, 2017.

I've done a clean Drupal install
Next created a term visiting  http://drupal.d8/admin/structure/taxonomy/manage/tags/add
Visited the term http://drupal.d8/taxonomy/term/1 to check it's there
Tested for a json response http://drupal.d8/taxonomy/term/1?_format=json
giving the expected {"message":"Not acceptable format: json"} as we have not yet configured Rest
Next enabled Rest UI module
Configured taxonomy term on http://drupal.d8/admin/config/services/rest
Visiting http://drupal.d8/taxonomy/term/1?_format=json again gave me the expected json output like {"tid":[{"value":1}],"uuid":[{"value":"d5e87924-5ccd-4fbe-bf1b-f1790da0d800"}],"langcode":[{"value":"en"}],"vid":[{"target_id":"tags","target_type":"taxonomy_vocabulary","target_uuid":"b1d2d8a9-0f05-49e7-abbc-137aaa9d0f64"}],"name":[{"value":"Term 1"}],"description":[{"value":null,"format":null}],"weight":[{"value":0}],"parent":[],"changed":[{"value":1491899632}],"default_langcode":[{"value":true}],"path":[]}

Note I have tested as admin and anonymous with same results. Enabling HAL and requesting the formats xml and hal_json gave the expected results too.

Disabling cookie request and enable basic_auth give a different response.

  {"message":"The used authentication method is not allowed on this route."}

Hope this helps.


Use contextual filter global null to pass values to override field result I come again with new question about Drupal Views and i hope you can help and explain me how to achieve this, I made a page view to display all my content (this works fine) with the following path:

/car/%/%/%

Now I want to get all the aliases of that path, for example: /car/2009/vw/jetta and then get %1=2009, %2=vw, %3=jetta and then use this to rewrite the output of a field to show something like this:

 [name],

and with this get my URL like: /details/2009/vw/jetta

I see that maybe this is possible with contextual filter: global: null. I tried to configure it but i only get the URL with tid's (/details/10/25/33) instead of the alias.

Can you explain me how can I configure global:null to get the values that i want without affecting my view results?

Took me a while but i solved this problem with something like this:

Added 3 Global: Null context filters and then i configured them with something like this:

For global 1:
WHEN FILTER VALUE IS NOT IN THE URL>>Provide default value>>Type:RAW value from URL>> Path Component: 1 >> Checked Use Path Alias >> Apply changes

For global 2:
WHEN FILTER VALUE IS NOT IN THE URL>>Provide default value>>Type:RAW value from URL>> Path Component: 2 >> Checked Use Path Alias >> Apply changes

For global 3:
WHEN FILTER VALUE IS NOT IN THE URL>>Provide default value>>Type:RAW value from URL>> Path Component: 3 >> Checked Use Path Alias >> Apply changes

And with that you can get the values to use them when you want to override a field output using contextual filter values.


Field Formatter Class and limit number of characters I have to insert in a field (admin/structure/types/manage/article/display) a string of classes to get a button from a text but the "Field Formatter Class" field has a character limit so I can't enter the code which I need to get the result.
I did some research but couldn't find the solution.

My Class:
btn btn-sm btn-primary stpe-outlinebutton test-util-color-primary test-util-border-primary test-util-hover-background-primary test-util-hover-color-white test-util-hover-border-primary

Any help?

Best Regards

I believe you are using the module Field Formatter Class to have this option for your fields.

The module does not set a maximum value for this field. So I believe it is using a default of 128 chars in core.

128 is a fairly long limit for a class field. But if you want to alter this you can write an alter function in your module like they have done in their module and set the #maxlength property of the field_formatter_class element.

Having said that, the following is a quick hack to get this working for you.

You can open the file field_formatter_class/field_formatter_class.module

and add a line

'#maxlength' => 256,

in the element class array in the alter function in line 44. After modification this will be like the following (view original code)

function field_formatter_class_field_formatter_settings_form_alter(&$settings_form, $context) {
  $display = $context['instance']['display'][$context['view_mode']];
  $settings = $display['settings'];
  $settings_form['field_formatter_class'] = array(
    '#type' => 'textfield',
    '#title' => t('Field Formatter Class'),
    '#maxlength' => 256,
    '#default_value' => $settings['field_formatter_class'],
  );

Do note that this is modifying a contrib module and is generally not a recommended approach. You will have to maintain this patch in a patches folder.


Why are my views arguments not being handled properly? I'm using Views 2 to rewrite the output of a specific field, which looks like this:

  [title]

The link is generated as http://www.xxxx.edu/highlights1/12499/Yes, which I is correct. The view is at /highlights1, argument 1 is 12499, and argument 2 is Yes.

But Drupal is not finding the page because its looking for the full path and NOT stripping & passing the arguments to the view named hightlights1.

These two args are defined in the referenced view, so why are they not being sent to the view?

Do you have a page display for your hightlights1 view with a path of highlights1/%/% set up?

Edit the path of your view's page display and ensure it's highlights1/%/% -- the percent signs each represent an argument for views to collect from the path and use.


Drupal 6 hook for field access I want to use my own code to determine if a user has edit access on certain fields.  hook_field_access for Drupal 7 looks right.  Is there a comparable hook for Drupal 6?

A hook with exactly the same name exists for CCK in Drupal 6, it just doesn't seem to be all that well documented.

It's invoked from the content_access() function and has the following signature:

function MYMODULE_field_access($op, $field, $account = NULL, $node = NULL) {

}


change action link on views exposed form I have created a views exposed form. How can I change the action link, or the "Submit" button.

I use Drupal 7.

You can alter the value of the submit button inside the view:
Advanced -> Exposed From -> Exposed form style -> Settings -> Submit button text.
From http://drupal.org/node/109604:
The documentation for Views 2 and Views 3 for Drupal 6 and Drupal 7 is contained within Views module!
Install the Advanced Help module to access it.


Rules - Use data from webform field in new entity type I currently have a webform with the following fields:

Your Email
Your Name
Your Idea

Alongside this I have setup a rule that when a webform is submitted it creates a new node of a new content type I have created 'Idea'. A view then pulls in all these 'Ideas' to display.

The title of the node pulls in the Your Idea field using the value [data:your_idea-value] which works fine.

But I am trying to set the author of the node as the Your Name field but I am struggling, it doesn't allow a value to be used and can't figure it out.

I've managed to get it working where it sets it to Anonymous and then I setup another action on the rule to rename the author:name but it does it for all of the content, not just the new node.

I'm sure I'm just missing something simple, would be great if someone could assist.

Currently setup to set author as anonymous for the time being.

Below is something I learned about using webform data in Rules, which may help you to get this to work (assuming your question is about D7) ...

You have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

So try to use similar tokens.

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.


user register from overflow In my register form email address description is overflow. I know that I have to change theme, but I would like to know where to theme it.

Thanks,

I don't know your themes output but maybe you could try to edit the style of

#user-register-form {

}

It would be helpful to see the website with the user-register-form.


Display a message to user for empty user fields User's have a field called "Location" (uses the Address module).

I would like to show a message (or enable a block) to users that have not filled out this field.

Specifically, this message should be shown when they log in, view their profile, or when they view their dashboard.

I am attempting to do this with Rules, but no luck yet. Any guidance would be appreciated.

This solution may be less performance happy than preprocessing (or not, it's difficult to say depending on caching etc), but I thought I'd be good to throw it out there since it's a "no-code" solution.

Create a Views with Block display listing users
Filter according to Location field Is empty to show only users who don't have it filled in
Add a Contextual filter for the user ID and set it to the current user, Hide Views if it doesn't validate
Add Custom text field and enter your message to be shown
Add the No results behaviour, this may need some thinking around how to handle the cases when the uses do have the Location field filled in
Place the block in as many regions of your theme as you need, and configure each Block visibility so it makes sense for your cases
Don't forget to also configure the Block contextual filter settings


Restore missing main menu I have managed to hide/lose the main menu bar - drupal 7.x.

overview of work I was doing:

I added mediaelements.js
I began adding videos to the site with add content
I attempted to make a Videos menu in the main menu

It was during some point of this process that I noticed the main menu bar was missing.
I have searched SE for solutions similar to  mine and have not had success with what was presented as solutions (having main menu in block and appearance settings toggled).
I have, so far, tried to go through each setting and compared them against settings in dev environment.
Are their other troubleshooting tasks I should follow which may point to a resolution?

thank you

resolved - I had restricted the main menu block to specific content types. Removing the restriction restored main menu block across all content types.


How do I define a JavaScript library? In Drupal 8 some JavaScript changes were introduced: All JavaScript scripts should be defined using hook_library_info() and added to the page only with #attached attribute of the render array.
What should I do to define external libraries? Should I create a libraries directory and upload the library there, or should they be managed by the module using Composer?

Since you posted this question, hook_library_info was replaced with *.libraries.yml files.

An example of a simple library declaration looks like this:

jquery.form:
  remote: https://github.com/malsup/form
  version: 3.39
  js:
    assets/vendor/jquery-form/jquery.form.js: {}
  dependencies:
    - core/jquery
    - core/jquery.cookie

Once declared, this library can be attached to a render array like this:

$element['#attached']['library'][] = 'core/jquery.form';

Now Drupal should take care of adding the library and all required dependencies to the page. Even though the library declaration can contain a remote url, Drupal will not automatically download the library for you.

If I'm not mistaken, you will always need a module or a theme with a .libraries.yml file to act as the provider of your library. However a module can be really simple, you only need a .info.yml file to declare a module.


How to alter form password and add current password in user_profile_form How to alter form password and add current password like in this image?

Take a look on Password Separate Form module.

The Password Separate Form module provides the separate password change form.

By default it comes with user account page that little bit confusing for end
users. This module would help to make this form as a separate form to help end users, there is no need to change these fields every time if you are editing some other fields on user account page.