Currently I am working on a new traveling website, but am having problems with 1 thing:
I have a list with all the country's, regions and city's i want to publish. How do I quickly create a page for all of them like this:
Every page should be a subpage like: country/region/city
Every page should have a certain page template
Please let me know, thanks in advance for your time and information!
You can do something like this.
<?php
// $country_list = get_country_list(); // returns list, of the format eg. array('India' => 'Content for the country India', 'Australia' => 'Content for the country Australia')
// $region_list = get_region_list($country); // Get the list of regions for given country, Assuming similar format as country.
// $city_list = get_city_list($region); // Get the list of cities for given region, Assuming similar format as country
/* Code starts here...*/
$country_list = get_country_list();
foreach($country_list as $country_title => $country_content) {
$country_template = 'template_country.php';
$country_page_id = add_new_page($country_title, $country_content, $country_template);
// validate if id is not 0 and break loop or take needed action.
$region_list = get_region_list($country_title);
foreach($region_list as $region_title => $region_content) {
$region_template = 'template_region.php';
$region_page_id = add_new_page($region_title, $region_content, $region_template, $country_page_id);
// validate if id is not 0 and break loop or take needed action.
$city_list = get_city_list($region_title);
foreach($city_list as $city_title => $city_content) {
$city_template = 'template_city.php';
add_new_page($city_title, $city_content, $city_template, $region_page_id);
}
}
}
function add_new_page($title, $content, $template_file, $post_parent = 0) {
$post = array();
$post['post_title'] = $title;
$post['post_content'] = $content;
$post['post_parent'] = $post_parent;
$post['post_status'] = 'publish'; // Can be 'draft' / 'private' / 'pending' / 'future'
$post['post_author'] = 1; // This should be the id of the author.
$post['post_type'] = 'page';
$post_id = wp_insert_post($post);
// check if wp_insert_post is successful
if(0 != $post_id) {
// Set the page template
update_post_meta($post_id, '_wp_page_template', $template_file); // Change the default template to custom template
}
return $post_id;
}
Warning: Make sure that the is executed only once or add any validation to avoid duplicate pages.
Related
I'm working on an extension that's depending on cal base. I fetch events from other sources by crawling their websites.
I'm slowly converting to extbase and I'd like to know if or how it is possible to access cal base events from my extension.
I know that I could just access the tables using mapOnProperty. But then I would have to rewrite the whole logic, too.
I wonder if it's possible to just use the objects of calendar base.
I tried to write a test:
<?php
class CalEventTest extends \TYPO3\CMS\Core\Tests\BaseTestCase {
/**
* #test
*/
public function anInstanceOfCalEventCanBeConstructed() {
$calEventService = & \TYPO3\CMS\Cal\Utility\Functions::getEventService ();
// $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Object\ObjectManager');
// $calEventService = $objectManager->get('TYPO3\CMS\Cal\Service\EventService');
// $calEventService = new TYPO3\CMS\Cal\Service\EventService();
// $events = $calEventService->findAll(array(1));
}
}
You see different attempts commented out. They all failed in one or the other way. CalEventService looked promising but it also doesn't work. The error for the last approach is.
Call to a member function isLoggedIn() on null in /var/www/clients/client4/web47/web/typo3conf/ext/cal/Classes/Service/NearbyEventService.php on line 27
I wonder if this approach is possible at all before trying some more (the mentioned error seems connected to the test environment context).
I'm using Typo3 6.2.27 and cal 1.10.1.
Not jet tested, but as the Manual says you should access the EventService like this:
$storagePageID = 123;
/** #var \TYPO3\CMS\Cal\Service\EventService $eventService **/
$eventService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstanceService('tx_cal_phpicalendar', 'cal_event_model');
$events = $eventService->findAll($storagePageID);
I found the cal API which looks promising
/**
* #test
*/
public function calApiCanBeAccessed() {
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Object\ObjectManager');
$calAPIPre = $objectManager->get('TYPO3\CMS\Cal\Controller\Api');
$this->assertInstanceOf(TYPO3\CMS\Cal\Controller\Api::class, $calAPIPre);
$this->assertObjectHasAttribute('prefixId', $calAPIPre);
$pidList = "1095, 80";
$calAPI = $calAPIPre->tx_cal_api_without($pidList);
$this->assertInstanceOf(TYPO3\CMS\Cal\Controller\Api::class, $calAPI);
$this->assertObjectHasAttribute('prefixId', $calAPI);
$this->assertInstanceOf(TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::class, $calAPI->cObj);
}
and successfully returns an event object
/**
* #test
*/
public function calEventCanBeFoundThroughApi() {
$pidList = "1095, 80";
$eventUid = '2670';
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Object\ObjectManager');
$calAPI = $objectManager->get('TYPO3\CMS\Cal\Controller\Api')->tx_cal_api_without($pidList);
$event = $calAPI->findEvent($eventUid, 'tx_cal_phpicalendar', $pidList);
$this->assertInstanceOf(TYPO3\CMS\Cal\Model\Eventmodel::class, $event);
}
internally it seems to use the approach of simulating a TSFE context (if no cObj is present, I didn't try the tx_cal_api_with(&$cObj, &$conf) method using an existing cObj).
Having read an old thread from 2012 (https://forum.typo3.org/index.php/t/192263/) I implemented that in my Typo3 6.2 setting:
<?php
class CalEventTest extends \TYPO3\CMS\Core\Tests\BaseTestCase {
/**
* #test
*/
public function anInstanceOfCalEventCanBeConstructed() {
$rightsObj = &\TYPO3\CMS\Cal\Utility\Registry::Registry ('basic', 'rightscontroller');
$rightsObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstanceService('cal_rights_model', 'rights');
$rightsObj->setDefaultSaveToPage();
$modelObj = &\TYPO3\CMS\Cal\Utility\Registry::Registry('basic','modelcontroller');
$modelObj = new \TYPO3\CMS\Cal\Controller\ModelController();
$viewObj = &\TYPO3\CMS\Cal\Utility\Registry::Registry('basic','viewcontroller');
$viewObj = new \TYPO3\CMS\Cal\Controller\ViewController();
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Object\ObjectManager');
$configurationManager = $objectManager->get('TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface');
$controller = &\TYPO3\CMS\Cal\Utility\Registry::Registry('basic','controller');
$controller = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Cal\\Controller\\Controller');
$cObj = &\TYPO3\CMS\Cal\Utility\Registry::Registry('basic','cobj');
$cObj = $configurationManager->getContentObject();
$cObj = new TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer();
$GLOBALS['TSFE'] = new \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController($GLOBALS['TYPO3_CONF_VARS'], $pid, '0', 1, '', '', '', '');
$GLOBALS['TSFE']->cObj = $cObj;
$GLOBALS['TSFE']->sys_page = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Page\\PageRepository');
$storagePageID = "1095, 80";
$eventService = & \TYPO3\CMS\Cal\Utility\Functions::getEventService ();
if ($eventService) {
$events = $eventService->findAll($storagePageID);
\TYPO3\CMS\Core\Utility\GeneralUtility::devLog('2', $this->getDebugId()."-".__FUNCTION__, -1, array($events, $eventService->getServiceKey ()) );
}
}
}
This works but it I find it extremely ugly. I'll try the cal api next.
(this has been an edit to my question but it's actually an answer)
Looping to save each column field picture1pic6:
Please help, i using cake php version 2.0, try to do looping to save each column, but only the first row data save, the data should be save like attached picture1.Hope someone can help, i tried to figure out 2 weeks. V_COUNT i hardcode the number to 23.
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
$this->IPI->setSource($table_name);
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$this->request->data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$this->request->data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$this->request->data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$this->request->data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->create();
$this->IPI->save($this->request->data);
}
}
try this
if($this->IPI->save($this->request->data))
{
$table_name = 'IPI_V';
for($i=1;$i<=$this->request->data['IPI']['V_COUNT'];$i++)
{
$data = array();
if($i<10){$i = '0'. $i;}
if(($this->request->data['IPI']['Quantity'.$i])!=NULL)
{
$data['IPI']['Type_Defect'] = $this->request->data['IPI']['Type_Defect'.$i];
$data['IPI']['CAT'] = $this->request->data['IPI']['CAT'.$i];
$data['IPI']['Defect'] = $this->request->data['IPI']['Defect'.$i];
$data['IPI']['Quantity'] = $this->request->data['IPI']['Quantity'.$i];
$this->IPI->setSource($table_name);
$this->IPI->create();
$this->IPI->save($data);
}
}
I have just stumbled upon very strange behaviour. In my code I am saving new node with some fields. I must say this used to work perfectly well. However now it just stopped working. I use the devel module to print out the content of objects and variables and this is my code:
dsm($node);
node_save($node);
dsm($node);
The first dsm() function displays node object as I created it and as it is supposed to be. The second dsm() function displays entirely correct node object with nid populated, fields content, etc... However, none of the fields is saved in database although there is new record in {node} table. Also, node_save does not generate any kind of error.
Any idea what is happening here?
This is the function storing the node:
function manhattan_incident_save($data) {
if ($data['nid']) {
$node = node_load($data['nid']);
manhattan_compare_changes($node, $data);
}
else {
$node = new stdClass();
$node->type = 'incident';
node_object_prepare($node);
$node->title = manhattan_create_incident_id();
$node->language = LANGUAGE_NONE;
}
$node->field_incident_popis[$node->language][0]['value'] = $data['field_incident_popis'];
$node->field_incident_popis[$node->language][0]['safe_value'] = check_plain($data['field_incident_popis']);
$node->field_incident_agent[$node->language][0]['uid'] = isset($data['field_incident_agent'])?intval($data['field_incident_agent']):NULL;
$node->field_incident_zdroj[$node->language][0]['tid'] = intval($data['field_incident_zdroj']);
$node->og_group_ref[$node->language][0]['target_id'] = $data['field_incident_oblast']?intval($data['field_incident_oblast']):variable_get('manhattan_public_form_default_area_nid', NULL);
$node->field_incident_riesitel[$node->language][0]['uid'] = isset($data['field_incident_riesitel'])?intval($data['field_incident_riesitel']):NULL;
$node->field_incident_typ[$node->language][0]['tid'] = intval($data['field_incident_typ']);
$node->field_incident_doplnenie[$node->language][0]['nid'] = intval($data['field_incident_doplnenie']);
$node->field_incident_sposob_kontaktu[$node->language][0]['value'] = $data['field_incident_sposob_kontaktu'];
$node->field_incident_dovod_vzniku[$node->language][0]['tid'] = intval($data['field_incident_dovod_vzniku']);
if ($data['field_incident_suvisiaci_zaznam']) {
foreach ($data['field_incident_suvisiaci_zaznam'] as $file) {
$result = manhattan_save_files($file);
if ($result) {
$node->field_incident_suvisiaci_zaznam[$node->language][] = array('nid' => $result);
}
}
}
// now create/save the customer
if (function_exists('customer_customer_save')) {
$customer = $data;
$customer['nid'] = $data['field_incident_customer'];
$result = customer_customer_save($customer);
if ($result) {
watchdog('upvs', $result['message'], array(), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('There was a problem with saving customer %nid'), array('%nid' => $data['nid']), WATCHDOG_ERROR);
}
}
// now we store nid of saved customer to the node object
$node->field_incident_customer[$node->language][0]['nid'] = $result['nid'];
dsm($node);
node_save($node);
dsm($node);
if ($data['nid']) {
watchdog('upvs', t('Incident number %title has been succesfully saved.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
else {
watchdog('upvs', t('Incident number %title has been succesfully created.'), array('%title' => $node->title), WATCHDOG_NOTICE);
}
return $node;
}
This function adds custom post 'event' data into a Salesforce db. I've tested the function outside of Wordpress and it works flawlessly. When I test it inside Wordpress by adding a new event, no error is generated and a the data is not inserted into the SF db. I've also tested this by printing out the $_POST and saw that the data is being collected. How can I get this display some errors so that I can trouble shoot this?
function add_campaign_to_SF( $post_id) {
global $SF_USERNAME;
global $SF_PASSWORD;
if ('event' == $_POST['post-type']) {
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(CD_PLUGIN_PATH . 'Toolkit/soapclient/enterprise.wsdl.xml');
$mySFlogin = $mySforceConnection->login($SF_USERNAME, $SF_PASSWORD);
$sObject = new stdclass();
$sObject->Name = get_the_title( $post_id );
$sObject->StartDate = date("Y-m-d", strtotime($_POST["events_startdate"]));
$sObject->EndDate = date("Y-m-d", strtotime($_POST["events_enddate"]));
$sObject->IsActive = '1';
$createResponse = $mySforceConnection->create(array($sObject), 'Campaign');
$ids = array();
foreach ($createResponse as $createResult) {
error_log($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
error_log($mySforceConnection->getLastRequest());
error_log($e->faultstring);
die;
}
}
}
add_action( 'save_post', 'add_campaign_to_SF');
I would use get_post_type() to check for "event" posts. Use error_log() to write to the PHP error log for additional debugging - check the status of your Salesforce login, etc.
Keep in mind that save_post will run every time a post is saved - created or updated - so you might want to do some additional checking (like setting a meta value) before creating a new Campaign in Salesforce, otherwise you will end up with duplicates.
function add_campaign_to_SF( $post_id ) {
$debug = true;
if ($debug) error_log("Running save_post function add_campaign_to_SF( $post_id )");
if ( 'event' == get_post_type( $post_id ) ){
if ($debug) error_log("The post type is 'event'");
if ( false === get_post_meta( $post_id, 'sfdc_id', true ) ){
if ($debug) error_log("There is no meta value for 'sfdc_id'");
// add to Salesforce, get back the ID of the new Campaign object
if ($debug) error_log("The new object ID is $sfdc_id");
update_post_meta( $post_id, 'sfdc_id', $sfdc_id );
}
}
}
add_action( 'save_post', 'add_campaign_to_SF' );
I want to add a "field collection" dynamically. But I'm not familiar with Field API or Entity API. New Entity API in Drupal is very poorly documented.
Here is my code, until now:
$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_book_text'));
$field_collection_item->setHostEntity('node', $node);
// Adding fields to field_collection
$field_collection_item.save();
"Field Collection" module use function "entity_form_submit_build_entity" which I cannot use because there is no form in my case.
I would appreciate if you can tell me how can I add fields?
Based on some code I used in a live project:
// Create and save research field collection for node.
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_article_references'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->field_reference_text[$node->language][]['value'] = 'ABCD';
$field_collection_item->field_reference_link[$node->language][]['value'] = 'link-val';
$field_collection_item->field_reference_order[$node->language][]['value'] = 1;
$field_collection_item->save();
Anyone using the above code samples should consider using the entity_metadata_wrapper function from the Entity API to set the values of fields on an entity instead of using an assignment operator. So, the code from the "more complete example" above would be:
if ($node->field_collection[LANGUAGE_NONE][0]) {
// update
$fc_item = reset(entity_load('field_collection_item', array($node->field_collection[LANGUAGE_NONE][0]['value'])));
}
else {
// create
$fc_item = entity_create('field_collection_item', array('field_name' => 'field_collection'));
$fc_item->setHostEntity('node', $node);
}
// Use the Entity API to "wrap" the field collection entity and make CRUD on the
// entity easier
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc_item);
// ... set some values ...
$fc_wrapper->field_terms->set('lars-schroeter.com');
// save the wrapper and the node
// Note that the "true" is required due to a bug as of this time
$fc_wrapper->save(true);
node_save($node);
A more complete example:
if ($node->field_collection[LANGUAGE_NONE][0]) {
// update
$fc_item = reset(entity_load('field_collection_item', array($node->field_collection[LANGUAGE_NONE][0]['value'])));
}
else {
// create
$fc_item = entity_create('field_collection_item', array('field_name' => 'field_collection'));
$fc_item->setHostEntity('node', $node);
}
// ... set some values ...
$fc_item->field_terms[LANGUAGE_NONE][0]['value'] = 'lars-schroeter.com';
// save node and field-collection
$node->field_collection[LANGUAGE_NONE][0] = array('entity' => $fc_item);
node_save($node);
You don't need to call node_save($node) when using entity_metadata_wrapper. It will ensure that only the entity's data and the reference to the host are saved without triggering any node_save, which is a good performance boost.
However, you would still need node_save() if you have any node_save-triggered actions that use this field collection (e.g. a rule that sends emails when the node is edited).
use the wrappers, they are your friend:
// Create an Entity
$e = entity_create('node', array('type' => 'CONTENT_TYPE'));
// Specify the author.
$e->uid = 1;
// Create a Entity Wrapper of that new Entity
$entity = entity_metadata_wrapper('node',$e);
// Specify the title
$entity->title = 'Test node';
// Add field data... SO MUCH BETTER!
$entity->field_FIELD_NAME->set(1111);
// Save the node.
$entity->save();
You can find Entity API documented in Entity API Tutorial at Drupal.org.
There you can find some useful examples, especially check for Entity metadata wrappers page.
Here is example based on your variables:
$node = node_load(1);
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_book_text')); // field_book_text is field collection
$field_collection_item->setHostEntity('node', $node);
$cwrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
// Adding fields to field_collection
$cwrapper->field_foo_text->set("value");
$cwrapper->field_foo_multitext->set(array("value1", "value2"));
$cwrapper.save();
Here is another example using field collections from above docs page:
<?php
// Populate the fields.
$ewrapper = entity_metadata_wrapper('node', $node);
$ewrapper->field_lead_contact_name->set($contact_name);
$ewrapper->field_lead_contact_phone->set($contact_phone);
$ewrapper->field_lead_contact_email->set($contact_email);
// Create the collection entity and set it's "host".
$collection = entity_create('field_collection_item', array('field_name' => 'field_facilities_requested'));
$collection->setHostEntity('node', $node);
// Now define the collection parameters.
$cwrapper = entity_metadata_wrapper('field_collection_item', $collection);
$cwrapper->field_facility->set(intval($offset));
$cwrapper->save();
// Save.
$ewrapper->save();
?>
Here is more advanced example of mine which for given entity it loads taxonomy term references from field_rs_property_features, then for each secondary term which has a parent term, adds its term name and its parent term name into field_feed_characteristics_value by grouping them together into title (parent) and value (child). It's probably more difficult to explain without seeing the code. So here it is:
/**
* Function to set taxonomy term names based on term references for given entity.
*/
function MYMODULE_refresh_property_characteristics(&$entity, $save = FALSE) {
try {
$w_node = entity_metadata_wrapper('node', $entity);
$collections = array();
foreach ($w_node->field_rs_property_features->getIterator() as $delta => $term_wrapper) {
if ($term_wrapper->parent->count() > 0) {
$name = $term_wrapper->name->value();
$pname = $term_wrapper->parent->get(0)->name->value();
if (array_key_exists($pname, $collections)) {
$collections[$pname]->field_feed_characteristics_value[] = $name;
} else {
// Create the collection entity, set field values and set it's "host".
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_feed_characteristics'));
$field_collection_item->setHostEntity('node', $w_node->value());
$collections[$pname] = entity_metadata_wrapper('field_collection_item', $field_collection_item);
$collections[$pname]->field_feed_characteristics_title = $pname;
$collections[$pname]->field_feed_characteristics_value = array($name);
}
}
}
if ($save) {
$w_node->save();
}
} catch (Exception $e) {
drupal_set_message(t('Error setting values for field collection: #title, message: #error.',
array('#title' => $w_node->title->value(), '#error' => $e->getMessage())), 'error');
watchdog_exception('MYMODULE', $e);
return FALSE;
}
return TRUE;
}