I have what might be called the basic formit2resource snippet working, but it doesn’t create an alias in the new document. I wanted to create a custom alias from the page title field and make sure there aren’t duplicates. So I cobbled together the information from this old forum thread.
However when I add in the code for creating the alias and adding number to the end I just get a blank page when submitting the form and nothing is created.
Here is the full code I have now.
<?php
$doc = $modx->getObject('modResource',array('id'=>$hook->getValue('resource_id')));
if (empty($doc)){
$doc = $modx->newObject('modResource');
$doc->set('createdby', $modx->user->get('id'));
}
else{
$doc->set('editedby', $modx->user->get('id'));
}
$allFormFields = $hook->getValues();
foreach ($allFormFields as $field=>$value)
{
if ($field !== 'spam' && $field !== 'resource_id'){
$doc->set($field, $value);
}
//we need to parse the title into the alias
if($field == 'pagetitle'){
//replace spaces with -
$alias = preg_replace('/[\' \']/' , '-' , $value);
//remove non alpha and a common injection string
$alias = preg_replace('/[^a-z0-9\.\x0B\-]/i' , '' , $alias);
//this is the standard revo regexp
// \0\x0B\t\n\r\f\a&=+%#<>"~:`@\?\[\]\{\}\|\^'\
}
}
//Check if alias already exists,and if it does it appends a number //in the end(eg already existing alias Maria becomes Maria2)
if($modx->getCount(modResource, array('alias'=>$alias))!= 0) {
$count = 2;
$newAlias = $alias;
while($modx->getCount(modResource, array('alias'=>$newAlias))!= 0) {
$newAlias = $alias;
$newAlias .= '-' . $count;
$count++;
}
$alias = $newAlias;
}
// now set the alias
$doc->set('alias', $alias);
$doc->set('template', '99');
$doc->set('parent', '1234');
$isnew = $doc->isNew();
if ($doc->save()) {
if ($isnew) {
$doc->set('alias', $doc->get('alias' . '-' . $doc->get('id')));
$doc->save();
}
}
$doc->save();
foreach ($allFormFields as $field=>$value)
{
if ($tv = $modx->getObject('modTemplateVar', array ('name'=>$field)))
{
/* handles checkboxes & multiple selects elements */
if (is_array($value)) {
$featureInsert = array();
while (list($featureValue, $featureItem) = each($value)) {
$featureInsert[count($featureInsert)] = $featureItem;
}
$value = implode('||',$featureInsert);
}
$tv->setValue($doc->get('id'), $value);
$tv->save();
}
}
$modx->cacheManager->refresh(); // suggested by gallenkamp
return true;
If I remove the following code from the middle it will post like normal and create the page, but the alias field still isn’t filled in. Any idea what is crashing the code or why the alias field isn’t being filled in?
//Check if alias already exists,and if it does it appends a number //in the end(eg already existing alias Maria becomes Maria2)
if($modx->getCount(modResource, array('alias'=>$alias))!= 0) {
$count = 2;
$newAlias = $alias;
while($modx->getCount(modResource, array('alias'=>$newAlias))!= 0) {
$newAlias = $alias;
$newAlias .= '-' . $count;
$count++;
}
$alias = $newAlias;
}