Jump to content
louisstephens

[Solved] Adding Multiple pages to Page field via API from select field

Recommended Posts

Posted (edited)

Going through my long quest to get better with ajax and utilizing the api, I have hit yet another roadblock. I currently have a form with an image field (thanks to flydev for getting that sorted), "title" text input, and a select field set to multiple. In my ajax call, I added in:

tags = $("#select-tags").val();
form_data.append('tags', tags);

$.ajax({
	type: 'POST',
	data: form_data,
	contentType: false,
	processData: false,
	url: '/ajax/upload-preview/',
	success: function(data) {
		console.log("Woo");
	},
	error: function(xhr, ajaxOptions, thrownError) {
		alert(xhr.responseText);
	}
});

And in the ajax template: 

$tags = $sanitizer->text($_POST['tags']);
$image = $sanitizer->text($_POST['image']);
$p = new Page();
$p->template = "preview";
$p->parent = $pages->get("/previews/");
$p->name = $title;
$p->title = $title;
$p->tags = $tags;
$p->save();

If I select a "tag" from the select input and submit, it does indeed add it to the Page Reference field in the backend. However, this does not work with an array being passed to it of multiple options.

47858297_ScreenShot2019-06-12at10_31_42AM.png.f3e6677b57cf8986202249a05a23b06b.png

So it does appear that my ajax call is trying to submit multiple options, but I am really just unsure how to get these two added in. I saw in other forums posts of add($page) and even add(array()). Do I need to handle this js array differently or do  I need to foreach through the $tags to add it like:

  foreach($tags as $tag) {
        $p->tags->add($tag);
        $p->save();
    }

I tried this approach, but apparently I am still missing something.

 

Edit:

I was doing some tweaking, and I know I can split the js array out like:

for (i = 0, len = tags.length; i < len; i++) {
	console.log(tags[i]);
}

However, I am not sure then how to handle the POST in php if I were to split it out.

Edited by louisstephens
finally figured it out

Share this post


Link to post
Share on other sites
4 hours ago, louisstephens said:

$tags = $sanitizer->text($_POST['tags']);

My guess is that this might be the culprit. If you submit multiple tags, that likely returns something like "array-2".

You might need to do something like this:

$rawTags = $input->post->tags;
$tags = array_map(
	function($tag) use($sanitizer) {
		return $sanitizer->text($tag);
	},
	is_array($rawTags) ? $rawTags : [$rawTags]
);

 

Share this post


Link to post
Share on other sites

Thanks Bitpoet. I gave it a shot and I am getting: 

#0 /MAMP/htdocs/development/wire/core/Selectors.php(460): ProcessWire\Selectors->create('hello', '', '')
#1 /MAMP/htdocs/development/wire/core/Selectors.php(142): ProcessWire\Selectors->extractString('the-4th-of-july')
#2 /MAMP/htdocs/development/wire/core/Selectors.php(128): ProcessWire\Selectors->setSelectorString('hello,the-4th-o...')
#3 /MAMP/htdocs/development/wire/core/PagesLoader.php(221): ProcessWire\Selectors->init('hello,the-4th-o...')
#4 /MAMP/htdocs/development/wire/core/Pages.php(246): ProcessWire\PagesLoader->find('hello,the-4th-o...', Array)
#5 /MAMP/htdocs/development/wire/core/Wire.php(386): ProcessWire\Pages->___find('hello,the-4th-o...', Array)
#6 /MAMP/htdocs/development/wire/core/WireHooks.php(733): ProcessWire\Wire->_callMethod('___find', Array)
#7 /MAMP/htdocs/development/wire/core/Wire.php(442): ProcessWire\WireHooks->runHooks(Object(ProcessWire\Pages), 'find', Array)
#8 /MAMP/htdocs/development/wire/core/PagesLoader.php(430): ProcessWire\Wire->__call('find', Array)
#9 /MAMP/htdocs/development/wire/core/Pages.php(390): ProcessWire\PagesLoader->get('hello,the-4th-o...', Array)
#10 /MAMP/htdocs/development/wire/modules/Fieldtype/FieldtypePage.module(700): ProcessWire\Pages->get('hello,the-4th-o...')
#11 /MAMP/htdocs/development/wire/modules/Fieldtype/FieldtypePage.module(563): ProcessWire\FieldtypePage->sanitizeValuePageArray(Object(ProcessWire\Page), Object(ProcessWire\Field), Array)
#12 /MAMP/htdocs/development/wire/core/Page.php(1072): ProcessWire\FieldtypePage->sanitizeValue(Object(ProcessWire\Page), Object(ProcessWire\Field), Array)
#13 /MAMP/htdocs/development/wire/core/Page.php(932): ProcessWire\Page->setFieldValue('tags', Array, true)
#14 /MAMP/htdocs/development/wire/core/Page.php(1825): ProcessWire\Page->set('tags', Array)
#15 /MAMP/htdocs/development/site/templates/ajax.php(64): ProcessWire\Page->__set('tags', Array)
#16 /MAMP/htdocs/development/wire/core/TemplateFile.php(287): require('/Volumes/ArtDep...')
#17 /MAMP/htdocs/development/wire/core/Wire.php(380): ProcessWire\TemplateFile->___render()
#18 /MAMP/htdocs/development/wire/core/WireHooks.php(733): ProcessWire\Wire->_callMethod('___render', Array)
#19 /MAMP/htdocs/development/wire/core/Wire.php(442): ProcessWire\WireHooks->runHooks(Object(ProcessWire\TemplateFile), 'render', Array)
#20 /MAMP/htdocs/development/wire/modules/PageRender.module(514): ProcessWire\Wire->__call('render', Array)
#21 /MAMP/htdocs/development/wire/core/Wire.php(383): ProcessWire\PageRender->___renderPage(Object(ProcessWire\HookEvent))
#22 /MAMP/htdocs/development/wire/core/WireHooks.php(733): ProcessWire\Wire->_callMethod('___renderPage', Array)
#23 /MAMP/htdocs/development/wire/core/Wire.php(442): ProcessWire\WireHooks->runHooks(Object(ProcessWire\PageRender), 'renderPage', Array)
#24 /MAMP/htdocs/development/wire/core/WireHooks.php(834): ProcessWire\Wire->__call('renderPage', Array)
#25 /MAMP/htdocs/development/wire/core/Wire.php(442): ProcessWire\WireHooks->runHooks(Object(ProcessWire\Page), 'render', Array)
#26 /MAMP/htdocs/development/wire/modules/Process/ProcessPageView.module(206): ProcessWire\Wire->__call('render', Array)
#27 /MAMP/htdocs/development/wire/core/Wire.php(383): ProcessWire\ProcessPageView->___execute(true)
#28 /MAMP/htdocs/development/wire/core/WireHooks.php(733): ProcessWire\Wire->_callMethod('___execute', Array)
#29 /MAMP/htdocs/development/wire/core/Wire.php(442): ProcessWire\WireHooks->runHooks(Object(ProcessWire\ProcessPageView), 'execute', Array)
#30 /MAMP/htdocs/development/index.php(55): ProcessWire\Wire->__call('execute', Array)
#31 {main}

I guess I shouldnt be tryping to still pass $tags the same way I was with $p->tags = $tags? Sorry, I have never used array_map before so I wasnt sure of the desired output etc. I do appreciate the help

Share this post


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

I guess I shouldnt be tryping to still pass $tags the same way I was with $p->tags = $tags?

Yes, loop over $tags and call $page->tags->add() for each like in the snippet you posted. Of course, you can just call $sanitizer->text for every $tag inside the loop in your third code snippet and go without the array_map. array_map is just a function that calls the passed function for every entry in the array given to it and returns a new array with the results.

  • Like 1

Share this post


Link to post
Share on other sites

Thanks again @BitPoet, I moved everything out into a new template so I could just test out the page reference field, and for some reason this is still blowing up in my face. I dont get the error like before, but it doesnt seem like anything is working. I simplified my php to:

$rawTags = $input->post->tags;
$tags = array_map(
	function($tag) use($sanitizer) {
		return $sanitizer->text($tag);
	},
	is_array($rawTags) ? $rawTags : [$rawTags]
);

$p = $pages->get(1092);
$p->of(false);

foreach($tags as $tag) {
	$p->tags->add($tag);
	bdump($tag);
}
$p->save();

The bdump shows that $tag = "2018,2019" (which is what I selected from the options field on the frontend", but it does not seem like it is actually adding anything to the field in the backend. 😓

Share this post


Link to post
Share on other sites
14 minutes ago, louisstephens said:

The bdump shows that $tag = "2018,2019"

Are these page names or page ids? For $p->tags->add to work, anything numeric must be a valid page id. And, duh, I have to say sorry. I just took a look into PageArray.php and saw that you can actually pass an array of pages to PageArray::add and it will call itself recursively, thought the same rules apply then. If it looks numeric, it needs to be a page id.

Share this post


Link to post
Share on other sites

Ah, they are indeed page names:

<select id="select_tags" name="select_tags" multiple="multiple">
	<?php $tags = $pages->find("template=tag"); ?>
    	<option value="">Select Your Tags</option>
    <?php foreach ($tags as $tag) : ?>
        <option value="<?= $tag->name; ?>"><?= $tag->title; ?></option>
	<?php endforeach; ?>
</select>

And my Tag structure is set up like:

Tags
-Years
--2018
--2019
-Months
--January
--February
--Etc

Sorry, I should have posted that earlier in my original post. So the url for the tag "2018" looks like "/tags/years/2018/" . I did change the output to be "ids" and then tried it out and it still isnt saving them. I really appreciate your help with this. If it is indeed recursive, I have no idea why " $p->tags->add($rawTags);" want work.

Share this post


Link to post
Share on other sites

Well, a little bit of an update. I just saw in my logs that I am getting an exception: "Page 1102 is not valid for tags ( Page 1102 does not have required parent 1015)"..

I am wondering if my tag structure is messing up the Page field somehow as my select field on the front end is really only displaying:

<select id="select_tags" name="select_tags" multiple="multiple">
	<option value="">Select Your Tags</option>
	<option value="1102">2018</option>
	<option value="1104">2019</option>
	<option value="1105">January</option>
	<option value="1106">February</option>
	<option value="1109">March</option>
	<option value="1110">April</option>
	<option value="1111">May</option>
</select>

I "omitted" the "Years", "Months" etc as I have them set to the template "parent-tag" while the actual "2019, January" are set to the template "tags".. I tried the "fix" from the following, but that doesnt seem to solve the issue either. It is odd to me that I can select via the admin and everything works fine.

**Update**

Using

$rawTags = $input->post->tags;

$p = $pages->get(1092);
$p->of(false);
bdump($rawTags);
$p->dev_test->add($rawTags); //created a new page field without a "parent", just set the template

This seems to add 1 page at a time now. However, it will not add multiple. I even tried to foreach through them to no avail.. Page fields obviously hate me today.

Share this post


Link to post
Share on other sites

I don't mean to keep this post going too long, but I am at a complete loss here and have no clue what else to do:

$rawTags = $input->post->tags;
tags = array_map(
	function($tag) use($sanitizer) {
    	return $sanitizer->text($tag);
	},
    is_array($rawTags) ? $rawTags : [$rawTags]
);

bdump($tags);
bdump($rawTags);

$p = $pages->get(1092);
$p->of(false);

foreach($tags as $tag) {
	echo $tag;
	$p->tags->add($tag); // add another page by id
}
$p->save();

The above will only add one item even though I am foreach'ing through the array and the array (in testing) has 2 items in it. It also only works when 1 item is selected. If I select 2 items from the options field, it will not add either of the items. Is there a fundamental piece I am missing here, or am I going about this the completely wrong way? I am at my wits end with this🤬

 

I did find 

so I tried 

$p = $pages->get(1092);
$p->of(false);
$p->dev_test->add(array($tags));
bdump($tags);
//add(array(1023,1026))
//bdump($Test->id);
$p->save();

It works if just input 1102,1103 directly into the array like ->add(array(1102,1103)) , but not by passing my array to it.

Share this post


Link to post
Share on other sites

Well, I was really dumb here. All it took was me taking a break and coming back with some fresh eyes. After another failed attempt to get it working, I decided to bdump $rawTags and $tags and then it hit me. 

$rawTags bdump: (which were the select values posted by the form): "1102,1103,1104,1105"

$tags bdump (what BitPoet wrote me): array(1) 0 => "1102,1103,1104,1105"

I was essentially passing an array with 1 item with all the ids. After using

$tagsArray = explode(',', $rawTags);

I get: array(4) 0=>"1102"  1=>"1103" 2=>"1104" 3=>"1105" and then it succesfully works with ->add(array($tagsArray)); 

I appreciate everyone's help with this and patience. I can finally put this to bed.

  • Like 1

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 louisstephens
      I have been messing around with creating pages from ajax requests, and it has gone swimmingly thus far. However, I am really struggling with creating a page and saving an image via ajax. 
      The form:
      <form action="./" role="form" method="post" enctype="multipart/form-data"> <div> <input type="text" id="preview" name="preview" placeholder="Image Title"> </div> <div> <input type="file" id="preview-name" name="preview-name"> </div> <div> <select id="select-tags" name="select-tags"> <?php $tags = $pages->find("template=tag"); ?> <option value="">Select Your Tags</option> <?php foreach ($tags as $tag) : ?> <option value="<?= $tag->name; ?>"><?= $tag->name; ?></option> <?php endforeach; ?> </select> </div> <div> <button type="button" id="submit-preview" name="submit" class="">Upload Images</button> </div> </form>  
      The ajax in my home template:
      $('#submit-preview').click(function(e) { e.preventDefault(); title = $("#preview").val(); image = $("input[name=preview-name]"); console.log(title); console.log(image); data = { title: title, image: image //not sure if this is actually needed }; $.ajax({ type: 'POST', data: data, url: '/development/upload-preview/', success: function(data) { console.log("Woo"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); } }); }); And finally in my ajax template:
      $imagePath = $config->paths->assets . "files/pdfs/"; //was from an older iteration $title = $sanitizer->text($_POST['title']); $image = $sanitizer->text($_POST['image']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->save(); $p->setOutputFormatting(false); $u = new WireUpload('preview_image'); $u->setMaxFiles(1); $u->setOverwrite(false); $u->setDestinationPath($p->preview_image->path()); $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); foreach($u->execute() as $filename) { $p->preview_image->add($filename); } $p->save(); I can complete the file upload but just using a simple post to the same page and it it works well, but I was really trying to work out the ajax on this so I could utilize some modals for success on creation (and to keep my templates a little cleaner). When I do run the code I have, a new/blank folder is created under assets, and a new page is created with the correct title entered. However, no image is being processed. I do get a 200 status in my console. I have searched google for help, but everything seems to be slightly off from my needs. If anyone could help point me in the right direction I would greatly appreciate it. 
    • By louisstephens
      This might be a completely dumb question, but I cant seem to wrap my head around it. I have a page reference field that allows users to select "Tags". In the front end I would like to use the titles as class names for a single item. ie:
      <?php $previews = $pages->find("template=preview"); ?> <?php foreach($previews as $preview): ?> <div class="tagOne TagTwo tagThree"> <!-- use another foreach to output--> <img src="<?=$preview->preview_image->url; ?>" /> </div> <?php endforeach; ?> I am little stumped as I know I need a foreach loop to produce each tag title, but how do I insert them all into one corresponding div class with spaces?
      Whelp, that was the easiest thing, but my brain just didnt "get it". Just put the foreach in the "class" inside of the overall foreach. Ugh 😓
    • By schwarzdesign
      We recently rebuilt the Architekturführer Köln (architectural guide Cologne) as a mobile-first JavaScript web app, powered by VueJS in the frontend and ProcessWire in the backend. Concept, design and implementation by schwarzdesign!
      The Architekturführer Köln is a guidebook and now a web application about architectural highlights in Cologne, Germany. It contains detailled information about around 100 objects (architectural landmarks) in Cologne. The web app offers multiple ways to search through all available objects, including:
      An interactive live map A list of object near the user's location Filtering based on architect, district and category Favourites saved by the user The frontend is written entirely in JavaScript, with the data coming from a ProcessWire-powered API-first backend.
      Frontend
      The app is built with the Vue framework and compiled with Webpack 4. As a learning exercise and for greater customizability we opted to not use Vue CLI, and instead wrote our own Webpack config with individually defined dependencies.
      The site is a SPA (Single Page Application), which means all internal links are intercepted by the Vue app and the corresponding routes (pages) are generated by the framework directly in the browser, using data retrieved from the API. It's also a PWA (Progressive Web App), the main feature of which is that you can install it to your home screen on your phone and launch it from there like a regular app. It also includes a service worker which catches requests to the API and returns cached responses when the network is not available. The Architekturführer is supposed to be taken with you on a walk through the city, and will keep working even if you are completely offline.
      Notable mentions from the tech stack:
      Vue Vue Router for the SPA functionality VueX for state management and storage / caching of the data returned through the API Leaflet (with Mapbox tiles) for the interactive maps Webpack 4 for compilation of the app into a single distributable Babel for transpilation of ES6+ SASS & PostCSS with Autoprefixer as a convenience for SASS in SFCs Google Workbox to generate the service worker instead of writing lots of boilerplate code Bootstrap 4 is barely used here, but we still included it's reboot and grid system Backend
      The ProcessWire backend is API-only, there are no server-side rendered templates, which means the only PHP template is the one used for the API. For this API, we used a single content type (template) with a couple of pre-defined endpoints (url segments); most importantly we built entdpoints to get a list of all objects (either including the full data, or only the data necessary to show teaser tiles), as well as individual objects and taxonomies. The API template which acts as a controller contains all the necessary switches and selectors to serve the correct response in <100 lines of code.
      Since we wanted some flexibility regarding the format in which different fields were transmitted over the api, we wrote a function to extract arbitrary page fields from ProcessWire pages and return them as serializable standard objects. There's also a function that takes a Pageimage object, creates multiple variants in different sizes and returns an object containing their base path and an array of variants (identified by their basename and width). We use that one to generate responsive images in the frontend. Check out the code for both functions in this gist.
      We used native ProcessWire data wherever possible, so as to not duplicate that work in the frontend app. For example:
      Page names from the backend translate to URLs in the frontend in the form of route parameters for the Vue Router Page IDs from ProcessWire are included in the API responses, we use those to identify objects across the app, for example to store the user's favourites, and as render keys for object lists Taxonomies have their own API endpoints, and objects contain their taxonomies only as IDs (in the same way ProcessWire uses Page References) Finally, the raw JSON data is cached using the cache API and this handy trick by @LostKobrakai to store raw JSON strings over the cache API.
      Screenshots














    • By VeiJari
      Hello forum!
      I've yet again stumbled on a head-scratching situation. We have enabled the option on our articles template and events template that it skips the title adding part and goes straight to the form. This is what our customer wants. So when you add a new article or event it automatically names it temporary to "article-0000000" and same with event. Now the problem is that obviously after saving the form we want to change to page url or "name" to the title, like it's normally. 
      Now here's the code for the hook:
      wire()->addHookBefore("Pages::saved(template=tapahtuma|artikkeli)", function($hook) {
        $page = $hook->arguments(0);
        $newUrl = wire()->sanitizer->pageName($page->title); // give it a name used in the url for the page
        wire()->log->message($page->name);
        $page->setAndSave('name', $newUrl);
      });
      I get the correct page and the name and path changes when I log them, but when I try to save it. It just loads and then I get: 
      Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) This happens in sanitizer.php
      and then another error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0
       
      What is happening? Am I not suppose to use sanitizer in this way? When we made a temporary page object in out other hook, the sanitizer worked perfectly.
      Thanks for the help!
×
×
  • Create New...