ImportCustomFieldValues

From Request Tracker Wiki
Jump to navigation Jump to search

import-custom-field-values

I use this script to populate a "select one from many" custom field from a text file generated from a database query.

   #!/usr/bin/perl
   
   use warnings;
   use strict;
   
   use lib qw(/opt/rt3/local/lib /opt/rt3/lib);
   use Getopt::Long;
   
   use RT;
   RT::LoadConfig();
   RT::Init();
   
   my %args;
   
   GetOptions(\%args, 'field=s', 'update','replace' ,'help', 'verbose');
   
   
    if ($args{'help'} || !($args{'update'}||$args{'replace'})  ){
      help();
      exit;
    }
   
   my @lines = <STDIN>;
   
   map {chomp} @lines;
   
   my $cf = RT::CustomField->new(RT->SystemUser);
   
   $cf->Load( $args{'field'} );
   unless ( $cf->id ) {
      die "Couldn't find that custom field\n";
   }
   
   if ( $args{'replace'} ) {
      my $values = $cf->Values;
      my %map;
   
      while ( my $value = $values->Next ) {
          unless (grep {$value->Name} @lines) {
           print STDERR "Deleting " . $value->Name . "\n" if ($args{'verbose'});
              $value->Delete();
          }
   
      }
   }
   
   if ( $args{'update'} || $args{'replace'} ) {
      my $values = $cf->Values;
      my @current;
   
      while ( my $value = $values->Next ) {
   
          push @current, $value->Name;
      }
   
      foreach my $entry (@lines) {
          unless ( grep { $entry eq $_ } @current ) {
              print STDERR "Adding " . $entry . "\n" if ($args{'verbose'});
              my ( $ret, $val ) = $cf->AddValue( Name => $entry );
          }
      }
   
   }
   
   print STDERR "Done\n" if ($args{'verbose'});
   
   
   
   sub help {
   
   print <<EOF
   
   $0 is a simple RT tool to add values to a custom field.
   It takes several arguments:
   
   
    --field    The id or name of the custom field you'd like to work with
    --update   Add values to this field, but do not prune unused files
    --replace  Make the custom field contain only the values listed
    --verbose  Show progress messages
   
   This script expects a list of potential custom field values,
   one per line to be fed to STDIN.
   
   Example:
   
   $0 --field "My CF Name" --update < list_of_values
   
   EOF
   
   }
   

The replace switch seems to update on version 3.8.7. (SJN)