?
Solved

php  populate locked Word template form

Posted on 2011-09-03
14
Medium Priority
?
599 Views
Last Modified: 2012-05-12
I have a ms Word doc template that is locked via password so I can't get to the field properties.  I don't have access to the password either.

I want to be able to populate the fields via a PHP form so I can capture the field data into a MySQL database and then also produce the word document but with the fields filled out so I can then print it.

Let me just say that LiveDocX is not a viable option because of security concerns for the content of the form.  All processing has to stay in our intranet.
0
Comment
Question by:yoshcomputers
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 4
  • 2
14 Comments
 

Author Comment

by:yoshcomputers
ID: 36479212
Here is the actual file I want to be able to populate via PHP.  I have saved it as an XML file and can get to the field names, but not sure how to populate it back with values. OCFS-8018-Service-Summary-Form.dot
0
 
LVL 76

Accepted Solution

by:
GrahamSkan earned 2000 total points
ID: 36479979
I don't know PHP, but if you can use COM and hence the Word Object Model, you don't need to remove forms protection to fill in the forms.

In VBA, it is:
objDoc.FormFields("Text1").Result = "Some Text"
and
objDoc.FormFields("Check1").CheckBox.Value = True

If you don't know the field names, you could use the numerical index instead:
objDoc.FormFields(1).Result = "Some Text"

And you could list the names as in this VBA macro

Sub ListFormFieldNames
    Dim i as Integer
    Dim ffld as FormField

    For i = 1 to ActiveDocument.FormFields.Count
         Debug.print i, ffld.Name
    Next i
End Sub

Finally, because forms protection is a convenience and not a security measure, you can get an unprotected copy of the document. In the Word application, create a blank document and 'Insert' the form document. In Word 2007, that is done by:
Insert tab> Text group> Object > Text from file...
As I recall, in earlier Word versions, you go via the Insert menu item on the standard toolbar.




 
0
 
LVL 31

Expert Comment

by:Helen Feddema
ID: 36480645
Here is some code that works with a document made from a partially locked template, unprotects the appropriate section to update doc properties filled from VBA Automation code, and then reapplies protection  If there is a password, it is set using the Password argument:
With appWord
   .Visible = True
   .Selection.WholeStory
   .Selection.Fields.Update
   Debug.Print "Going to save as " & strSaveNamePath
   .ActiveDocument.SaveAs strSaveNamePath
   .Activate
   .Selection.HomeKey unit:=wdStory
   If strWordTemplate = "Needs Protection.dotx" Then
       doc.Sections(1).ProtectedForForms = False
   End If
End With

If strWordTemplate = "Needs Protection.dotx" Then
   'Protect section with form fields for user data entry
   doc.Sections(1).ProtectedForForms = True
   doc.Protect Password:="", Type:=wdAllowOnlyFormFields
   doc.Sections(2).ProtectedForForms = False
End If

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 31

Expert Comment

by:Helen Feddema
ID: 36480649
This particular document had both DocProperty fields filled from Access, and form fields, to be filled in by the user.
0
 

Author Comment

by:yoshcomputers
ID: 36481242
I was able to unprotect the document and can get to the bookmarked names of the fields.  But I still don't know how to populate them with PHP.  I would need examples for PHP, not VBA.  I would prefer not to use a COM because it is very likely the servers I am dealing with won't have Microsoft Office installed.  But even if all I could get was a COM example, I would be happy.

Here are 5 of the Bookmarknames for the fields:
Text1, Text2, Text3, Check17, Check18

An example to include populating the fields and having Check17 and Check18 mark as true and save the file with a new filename would award you all the points.
0
 

Author Comment

by:yoshcomputers
ID: 36481308
OK...moving right along.  I figured out how to edit the Text fields via a COM interface (still not my preference)...but I haven't been able to get checkboxes to show they are checked.  I have tried values of true, checked, and even 'X' but it just displays text next to the checkbox instead of showing the checkbox is checked.

I wonder if it is a factor of the document has to be in unprotected mode to be able to edit the fields.  However if I put it in protected mode, I get an error saying I can't access the fields because the document is protected.
0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 36481378
I think that everyone is on a learning curve here. There definitely shouldn't be any restriction on updating form fields while protection is on. That is the whole point of forms protection. In fact it is better to keep protection on when updating the form field contents: when protection is re-enabled there is a specific argument to keep the previous form field contents.

Does PHP have an equivalent of the VB boolean values of True and False? Perhaps you should show the code that you are using, so that any PHP as well as Word experts can pool resources and see what methods you are trying.
0
 

Author Comment

by:yoshcomputers
ID: 36481401
Fair enough comment form Graham.  I am including the code for accessing the file and then writing the Text values.  I have a suspicion that the Range->Text is the problem with making a checkbox checked instead of putting the textual value next to it.  But I don't know what term to try.  I have tried Range->Value and Range->Checked but it reports an error 'Unable to lookup `Checked' or 'Value'

com_load_typelib('Word.Application');

$word = new COM("word.application") or die("Unable to instantiate Word");

// use like this. Place your's word file in C drive
$word->Documents->Open('C:/Files/Form1818_g.doc');
echo $current_date = date("m/d/Y");

$tim= date("Y-m-d");

$info_array=array(  "Text1"      => "Yosh",
                    "Text2" => "$tim" ,
                    "Text3"   => "sparsh" ,
                    "Check17"   => True,
                    "Check18"   => 'Checked') ;

foreach($info_array as $bookmarkname => $re)
    {
        $objBookmark = $word->ActiveDocument->Bookmarks($bookmarkname);
		echo $bookmarkname."<br>";
        $range = $objBookmark->Range;
	echo $range->Text = $re ;
    }

$new_file = "C:/Files/Form1818_newedit.doc";

$word->Documents[1]->SaveAs($new_file);

$word->ActiveDocument->Close(false);

$word->Quit();
$word = null;

Open in new window

0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 36481477
Hmm.

Even VB programmers are tempted to use the form field's bookmark and try to extract the data from it.

However the .Result method of the formfield object is actually designed to get the relevant information. This is because the text of range of its bookmark includes extra unneeded text that would have to be stripped off with a complex algorithm.

Thought I'm sure that it is possible, I can't see how the PHP code does exactly what we would do in VB. For instance, in VB, the For Each construct walks through the whole collection, and not through a particular named subset.

This my best guess at shoehorning my code into PHP. I've used an asterisk-> 'FormFields(*)' to wildcard the list, so that it will include all items.

foreach($ffld)
    {
        $ffld = $word->ActiveDocument->FormFields(*);
            echo $ffld.Name"<br>";
      echo $ffld->Result = $re ;
    }
0
 

Author Comment

by:yoshcomputers
ID: 36482010
Well,
I figured it out myself and here is the workaround code I have in place for now.
In order to access a Checkbox state you have to access it via the FormFields Object, not the Bookmarks Object.

If the Type is 'TextInput' You can access the 'Results' property to keep the data in an input field or you could use 'Range->Text' to just display the data.
For Type is CheckBox you have to then access the CheckBox Value state to toggle it from True or False.

The following code is using the $info_array to capture the name of the Field/Bookmark and its value as described in the prior code example above.
foreach($info_array as $bookmarkname => $re)
    {
        $objFormFields = $word->ActiveDocument->FormFields($bookmarkname);
		echo "<br>".$bookmarkname." = ".$objFormFields->Type;
		if ($objFormFields->Type == 70){ //Type 70 is 'TextInput' , Type 71 is 'CheckBox'
			echo $objFormFields->Result = $re ;
		} else {
			echo $objFormFields->CheckBox->Value = $re;
		}

    }

Open in new window

0
 

Author Comment

by:yoshcomputers
ID: 36482032
I've requested that this question be closed as follows:

Accepted answer: 0 points for yoshcomputers's comment http:/Q_27290437.html#36482010

for the following reason:

I ultimately had to dig through Microsofts MSDN library to find the answer I needed<br /><a href="http://msdn.microsoft.com/en-us/library" target="_blank">http://msdn.microsoft.com/<wbr />en-us/libr<wbr />ary</a>
0
 

Author Comment

by:yoshcomputers
ID: 36482033
On second review of the support answers, I realize that GrahamSkan had the right terminology but because it was in VBA and didn't specify I was using the wrong Object (the Bookmark object)  I didn't realize he was showing me the correct object to use (the FormFields object).  I just thought it was a different term for VBA vs PHP.

GrahamSkan should get 300 points.  I would have been able to award all of it had it been more clear about which object to use and that the protection problem I was having was because I was trying to access the Bookmark->Range->Text data instead of the FormFields->Results.  Also didn't address the CheckBox value issue I discovered on my own.
0
 

Author Closing Comment

by:yoshcomputers
ID: 36482035
Keep in mind the code that I finally ended up using at the bottom of the results is correct for PHP
0
 
LVL 76

Expert Comment

by:GrahamSkan
ID: 36483360
Thanks. Yes, it is sometimes hard to know what to be explicit about, and what to take as read.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Ever visit a website where you spotted a really cool looking Font, yet couldn't figure out which font family it belonged to, or how to get a copy of it for your own use? This article explains the process of doing exactly that, as well as showing how…
The viewer will learn how to make their project stand out over others by learning how to change colors and shapes, add spaces, change directions, and add bullets to their charts.
This video shows where to find templates, what they are used for, and how to create and save a custom template using Microsoft Word.
Suggested Courses

719 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question