Jump to content
EyeDentify

Change Template file via PW API (SOLVED)

Recommended Posts

Hello Fellow PW Fans and Gurus.

I have run into a problem where i have created a template without a template file associated with it.
Now i would like to HAVE a template file associated with it, not an alternate but as the main template file.

So i thought, that's easy, I upload the template file and change it in template settings but I only get the Alternate template file setting?

Ok so maybe i can change it via the API , so i wrote some code for this.

<?PHP
function changeTemplate($pages = null, $templates = null) {
    /* get the pages to change template on */
    $logItems = $pages->findMany('template=tmp_log_item');
	
  	/* get the template object for our desired template */
  	$Template = $templates->get('tmp_new_log_item');
  
    foreach($logItems AS $key => $logData) {
        
        /* use template object $Template to set template */
      	$logData->template = $Template;
        
        /* save page item */
        $logData->save();
    }
}

/* do the magic change */
changeTemplate();
?>

Needless to say, PW was not happy about this, It throw up an error message:

Error: Exception: Invalid value sent to Page::setTemplate (in /home/virtual/mydomain/public_html/wire/core/Page.php line 1782)


Now from what i understand i gave $logData->template the wrong type of value.
So what should the value be to correct this?

When I read the docs at: https://processwire.com/api/ref/page/

the value can be "string" or "Template".

So i gave it a string and it went haywire.

How should I approach this cause I realy dont want to manually change template file on över 50 plus pages :)

Maybe I should use the Template class to create the value that the API wanted, but I am unsure how to use it.

Thank you for any info you can give me on this.

If you want more info to help me, ask and I will try my best to give it to you.

Updated and Solved
I solved the problem and have updated the code to reflect this.

Essentialy i used the get() method of $templates to get the template object for my template i wanted to use using the template name.
I gave the Object to the $logData->template property and all went well.

We learn something new every day. :)

One Note:

The template file you want to use must have been uploaded and added as a template in the Template section in the Admin for this code to work as expected.

Edited by EyeDentify
Updated the post to correct som variable/property namnings and make it more readable.

Share this post


Link to post
Share on other sites

I realise this was a one-off but just wanted to point out that calling the get() inside the foreach loop is not very efficient. It is better to do that (once) outside the foreach since it is the same template you are retrieving each time. 

Edited by kongondo
  • Like 1

Share this post


Link to post
Share on other sites
2 minutes ago, kongondo said:

I realise this was a one-off but just wanted to point out that calling the get() inside the foreach loop is not very efficient. It is better to do that (once) outside the foreach since it is the same template you are retrieving each time. 

You are absolutly right. I was thinking of this but i forgot at the last minute. 😊

Share this post


Link to post
Share on other sites
1 hour ago, EyeDentify said:

I have run into a problem where i have created a template without a template file associated with it.
Now i would like to HAVE a template file associated with it, not an alternate but as the main template file.

Maybe I'm misunderstanding the situation here, but it isn't necessary to do anything in the PW admin or via the API to associate a template file with a template - you just add a file named the same as your template to /site/templates/. So if you created a template named "my_template" then you add a file "my_template.php".

You don't have to create the template and the template file at the same time. You could create a template last week and add the file today and it is automatically associated with the template if the name is the same.

  • Like 1

Share this post


Link to post
Share on other sites
5 minutes ago, Robin S said:

Maybe I'm misunderstanding the situation here, but it isn't necessary to do anything in the PW admin or via the API to associate a template file with a template - you just add a file named the same as your template to /site/templates/. So if you created a template named "my_template" then you add a file "my_template.php".

You don't have to create the template and the template file at the same time. You could create a template last week and add the file today and it is automatically associated with the template if the name is the same.

You are talking about the Alternate template file functionality. Then Yes, you can have a file uploaded and it would get used by the template that has a alternate template assigned with the same name as the one you uploaded.

But in my case i hade Created a Template without a file in Admin, but later i wanted it to have a file for views, but not an alternate file.
So my code fixes this by using a Template that i added with a associated file to go with it.

Share this post


Link to post
Share on other sites
10 hours ago, EyeDentify said:

You are talking about the Alternate template file functionality.

No, I'm not referring to the Alternate template file feature. I'm just saying that if you create a template without a file, and later decide you want to add a file for it, all you need to do is put that file (named the same as the template it relates to) into /site/templates/. Maybe you never tried it that way before but give it a go and you'll see what I mean.

  • Like 2

Share this post


Link to post
Share on other sites
On 2017-06-06 at 0:29 AM, Robin S said:

No, I'm not referring to the Alternate template file feature. I'm just saying that if you create a template without a file, and later decide you want to add a file for it, all you need to do is put that file (named the same as the template it relates to) into /site/templates/. Maybe you never tried it that way before but give it a go and you'll see what I mean.

Oh. Ok i see what you mean. I have tried what you are talking about, but i need to associate the file with a Template, and to remove the file from list of files without a Template that gets shown when you click "new template" in admin.

then i have to change every Template manually in the tree for every page.

There is no option in admin when you edit a Template to change the Orignal associated file (if any) or associate a new one if no one was chosen when creating the Template without a file.

Therefore i needed the code.

I don´t see the Automatic association you are talking about.

Maybe i misunderstood you.

On 2017-06-06 at 0:29 AM, Robin S said:

No, I'm not referring to the Alternate template file feature. I'm just saying that if you create a template without a file, and later decide you want to add a file for it, all you need to do is put that file (named the same as the template it relates to) into /site/templates/. Maybe you never tried it that way before but give it a go and you'll see what I mean.

Anyway, i have resolved the issue. i Thank you all for your input.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By ngrmm
      I have a page with a table. Each table row has a page-reference field and a checkbox.
      The Page sends emails to all users (page-refrence->email-field) and change the value of the checkbox in a row to 1.
      It works with this:
      <?php // event ID fron url query $eventID = $input->get('eventID','int'); // get event-page $event = $pages->get($eventID); // config $fromEmail = $event->event_mail_from; $fromName = $event->event_mail_from_name; $emailSubject = $event->event_subject; // email html body ob_start(); include('./_inc/emailbody.inc'); $emailBody = ob_get_clean(); // make event-page editable $event->of(false); // loop through table and send out emails foreach($event->event_clients_list as $event_table_row) { // get client page $clientPage = $event_table_row->client_name; // get client email $clientEmail = $clientPage->email; // if client isn't invited yet (checkbox not checked) if($event_table_row->client_invited == '') { // send email $m = new WireMail(); $m->to($clientEmail); $m->from($fromEmail, $fromName); $m->subject($emailSubject); $m->bodyHTML($emailBody); $m->send(); // mark client as invited $event_table_row->client_invited = 1; $event->save('event_clients_list'); } } ?> But i have to use a variable in my emailbody.inc which i'm able to get in the table-loop.
      So i do the including of the body inside my loop. But this doesn't work anymore. Page sends out the emails but is unable to change the value of the checkbox.
      I get no errors!
      I'm using ProTable
      <?php // event ID fron url query $eventID = $input->get('eventID','int'); // get event-page $event = $pages->get($eventID); // config $fromEmail = $event->event_mail_from; $fromName = $event->event_mail_from_name; $emailSubject = $event->event_subject; // loop through table and send out emails foreach($event->event_clients_list as $event_table_row) { // get client page $clientPage = $event_table_row->client_name; // get client email $clientEmail = $clientPage->email; // email html body ob_start(); include('./_inc/emailbody.inc'); $emailBody = ob_get_clean(); // make event-page editable $event->of(false); // if client isn't invited yet (checkbox not checked) if($event_table_row->client_invited == '') { // send email $m = new WireMail(); $m->to($clientEmail); $m->from($fromEmail, $fromName); $m->subject($emailSubject); $m->bodyHTML($emailBody); $m->send(); // mark client as invited $event_table_row->client_invited = 1; $event->save('event_clients_list'); } } ?>  
    • By Vigilante
      In general, is there an easy way to know which method should be used to access the API?
      For example, when _ini.php is used in the theme, it would seem you have to use wire()->addHookBefore(...). But on other sites where they used ready.php, I've seen it go straight to just doing $this->addHookAfter() even though there is no class or namespace set up in the ready.php file.
      So how do I know when I can do $this, or $wire, or wire() to access things? And any other variables I'm not aware of.
      Thanks!
    • By VeiJari
      Hello forum,
      This is really a weird one, because front end editing works in a earlier website we did to a customer. 
      When I check the source code for current website it does initiate front end edit: 
      <span id=pw-edit-1 class='pw-edit pw-edit-InputfieldPageTitle' data-name=title data-page=1021 data-lang='1017' style='position:relative'><span class=pw-edit-orig>Tekijät</span><span class=pw-edit-copy id=pw-editor-title-1021 style='display:none;-webkit-user-select:text;user- select:text;' contenteditable>Tekijät</span></span>  But when I double click nothing happens (yes I'm 100% sure I'm superuser and logged in)
      I also tried to apply the front end with other methods than:
      $page->edit('title'); But didn't work either.
      We are using jquery 2.2.4, so it should not be a problem.
      Is this a bug related to current master or something else?
      Someone else having this problem as well?
    • By jom
      Hi everyone
      It seems that I don't fully understand the wireTempPath() function and I need some help.
      I use wireTempPath() to create a new location in assets/cache/WireTempDir and than copy a pdf from the assets/files/page folder to the new folder. I want the file to be accessible only for a limited time, that's why I use wireTempPath.
      The file seems to be copied to the right location, but gets deleted right afterwards, according to 
      As mentioned in the topic above, 
      $wireTempDir->setRemove(false); prevents the file to be deleted. But I like the file to be automatically deleted after a few days. So, how can I do that?
      My code so far (everything works, but the automatic removal of the tempDir folder):
      //generate and show download link $folder = time(); // timestamp as temporary folder $maxAge = (int) $settings->options_downloadlink_valid_hours * 3600; //tempDir wants maxAge as seconds $options = array( 'maxAge' => $maxAge ); $wireTempDir = wireTempDir($folder, $options); $wireTempDir->setRemove(false); $src_file = $page->ebook_download->filename; // Create a new directory in ProcessWire's cache dir if(wire('files')->mkdir($wireTempDir, $recursive = true)) { if(wire('files')->copy($src_file, $wireTempDir)){ //get subdirs from tempDir: $pos = strpos($wireTempDir, "WireTempDir"); $subdir = substr($wireTempDir, $pos, 100); $out .= "<p><a href='" . wire('pages')->get('template=passthrough')->httpUrl . "?file=" . $subdir . $page->ebook_download->basename . "' target='_blank'>$page->title</a></p>"; } } I appreciate any ideas - thanks!
      Oliver
    • By VeiJari
      Hello forum, this is my first security related post, so I'm a bit of a newbie.
      I understand that when I have direct front-input from user I should sanitize the input, but how about when I use a secret key for showing a API for a third-party supplier? Should I sanitize the input->get() key?
      I've tested this issue and I tried ?key=<?php echo $page->field; ?> And without adding any sanitization it comes back: /?key=<?php%20echo%20$page->field;%20?>
      So can I rely on this, or should I still use $sanitizer just in case?
       
      Thanks for the help!
×
×
  • Create New...