Drupal: Running Feeds Importer Programatically - Where to Put Code - drupal-7

When running a feeds importer using Cron, the importer times out resulting in an incomplete import. I'm trying to use a script to execute the importer and I've come across this code a few times:
<?php
function MODULE_NAME_cron() {
$name = 'FEED_NAME';
$source = feeds_source($name);
$source->import();
}
?>
However, when executing this I get an error saying there's no feeds_source() function, which leads me to believe that I just don't know where to put this code (a separate php file just isn't working for me). Can anyone help me out here? Thanks in advance!

I think you need to call $source->startImport(); method instaed of $source->import();

I just posted an answer to a similar question over here: https://drupal.stackexchange.com/questions/90062/programmatically-execute-feed-import/153434#153434 , which might help. in short, in the a form submit hook if your using the batch api, or dont use the batch api if you're doing it non browser (install hook , install profile)
so in your case
function load_data(){
// Files to import in specific order.
$files = array(
'challenge_importer' => 'data/challenges.csv',
);
$file_location_base = drupal_get_path('module', 'challenge');
foreach ($files as $feed => $file) {
$feedSource = feeds_source($feed);
// Set the file name to import
$filename = $file_location_base.'/' . $file;
if (!file_destination($filename, FILE_EXISTS_ERROR)) {
$config = $feedSource->getConfig();
$config['FeedsFileFetcher']['source'] = $filename;
$feedSource->setConfig($config);
$feedSource->save();
while (FEEDS_BATCH_COMPLETE != $feedSource->import());
}
}
}
could be called from the cron , or use the scheduled execution from the feeds importer

Related

Error: field is required

I have done a code, in which i create events. When i create event there was a field named "detailed_address" which i have removed now, from database, from model,from the edit page, from every where.
Creating an event works fine. but when i edit that event and save it, there is error as:
The detailed address field is required.
I have checked my code for at-least 5 times there is no word detailed address now used.
controller methods:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
return redirect('event');
}
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
return view('event.create');
}
Can any one tell what will be my problem?
As #manix suggested, try running php artisan clear-compiled, then i'd suggest running php artisan cache:clear as well just to make doubly sure it's not a cache issue.
Something that could also be worth looking into is your requests folder (app\http\requests), if you weren't validating the input on the controller it was likely being done via requests which might still be checking for input that isn't coming through.
Is the field also still registered as mass assignable on the model?
Can't see why it'd throw a validation error but it's worth making doubly sure it's gone from there too

How to save doctrine database schema in a Symfony controller?

I'm using Symfony 2.3 and Doctrine 2 and i need that an user save the schema of a Doctrine Database to a file (*.sql). I need it into an action method and then send the file to the user
You need to execute following command:
.app/console doctrine:schema:create --dump-sql >schema.sql
And here's the answer how to run Command from Controller: How can I run symfony 2 run command from controller
Just to get you started, this should work in concept. I didn't get to run it, so I assume it might need a little tweaks from your side.
<?php
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Doctrine\Bundle\DoctrineBundle\Command\Proxy\CreateSchemaDoctrineCommand;
// your controller
public function myAction()
{
$command = new CreateSchemaDoctrineCommand();
$command->setContainer($this->container);
$input = new ArrayInput(array('--dump-sql' => true));
$output = new NullOutput();
$schema = $command->run($input, $output); //This is your schema
// Write it to a file if you want
file_put_contents('path/to/schema.sql', $schema);
}
References:
Similar question
PHP file_put_contents()
Symfony2 FileSystem

Debugging SQL in controller

I am trying to debug my sql but I am having a hard time. I know I can use this:
<?php echo $this->element('sql_dump'); ?>
to dump the sql but this doesnt (or at least I dont know how to use it) work if I am doing an ajax call. Because the page is not reloaded, the dump does not get refreshed. How can I run my command and debug the sql? Here is the code I have in my controller:
public function saveNewPolicy(){
$this->autoRender = false;
$policyData = $this->request->data["policyData"];
$numRows=0;
$data = array(
'employee_id' => trim($policyData[0]["employeeId"]),
'insurancetype_id'=> $policyData[0]["insuranceTypeId"],
'company' => $policyData[0]["companyName"],
'policynumber' => $policyData[0]["policyNumber"],
'companyphone' => $policyData[0]["companyPhone"],
'startdate'=> $policyData[0]["startDate"],
'enddate'=> $policyData[0]["endDate"],
'note' => $policyData[0]["notes"]
);
try{
$this->Policy->save($data);
$numRows =$this->Policy->getAffectedRows();
if($numRows>0){
$dataId = $this->Policy->getInsertID();
$response =json_encode(array(
'success' => array(
'msg' =>"Successfully Added New Policy.",
'newId' => $dataId
),
));
return $response;
}else{
throw new Exception("Unspecified Error. Data Not Save! ");
}
}catch (Exception $e){
return $this->EncodeError($e);
}
}
The problem is that if the company field in my array is empty, empty, the insert will fail without any error. I know it has failed, though, because of the numrows variable I use. I know the field accepts nulls in the database. It seems like the only way for me to debug this is to look at what SQL is being sent to MySql. Anyone know how to debug it? I am using CakePhp 2.4
I use this approach. I added this method in my AppModel class:
public function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
and then in any controller you call this like:
debug($this->{your model here}->getLastQuery());
Rather than trying to hack around in CakePHP, perhaps it would be easier to just log the queries with MySQL and do a tail -f on the log file? Here's how you can turn that on:
In MySQL, run SHOW VARIABLES; and look for general_log and general_log_file entries
If general_log is OFF, run SET GLOBAL general_log = 'ON'; to turn it on
In a terminal, run a tail -f logfile.log (log file location is in the general_log_file entry) to get a streaming view of the log as it's written to
This is very helpful for these circumstances to see what's going on behind the scenes, or if you have debug off for some reason.

PHPAGI USING CakePHP SHELL

I recently needed to build an asterisk based IVR for an application built using cakePHP.
I wanted to use cakes' (fat) models, so I wouldn't have to re-write business logic.
I wanted to create a cakePHP shell which would be called from the asterisk dialplan.
Here's what I did.
Downloaded phpagi to vendors/phpagi.
Modified phpagi.php from
function AGI($config=NULL, $optconfig=array())
to:
function AGI($config=NULL, $optconfig=array(), $stdin, $stdout)
so I can set stdin and stdout. Around line 167 I changed
$this->in = defined('STDIN') ? STDIN : fopen('php://stdin', 'r');
$this->out = defined('STDOUT') ? STDOUT : fopen('php://stdout', 'w');
To
$this->in = $stdin;
$this->out = $stdout;
In my shell in vendors/shells I added
App::import('Vendor', 'AGI', array('phpagi/phpagi.php'));
I also added
var $agi;
//redirect output through agi conlog
function err($message,$newlines = 1){
$this->agi->conlog($message);
}
function out($message, $newlines =1){
$this->agi->conlog($message);
}
//disable default message
function startup(){
}
and the application code is in
function main(){
$this->agi = new AGI(NULL, array(), $this->Dispatch->stdin,$this->Dispatch->stdout);
$this->agi->answer();
//do stuff here
}
and to run this in the dialplan all you need to do is
exten => s,n,AGI(${full/path/to/cake.php},${shellname},-app,${var/www/html/{appname}/app},-console,var/www/html/{appname}/cake/console/)
Make sure to fix permissions on the cake dirs.
I was wondering if anyone had any other ways to do this?
Here is a class that will handel all the work for you. It is maintained by FreePBX - the most popular Asterisk GUI, and used extensively throughout FreePBX.

CakePHP - spitting out XML for webservice

What is the best way to spit out XML for webservice in CakePHP?
I have it like the following but it's displaying an empty page.
Sample call /service/config.xml
In Controller
var $helpers = array('Xml');
function config() {
$this->autoRender = false;
$obj = array("response" => array("config" => array(...)));
$objXmlHelper = new XmlHelper();
$objXml = $objXmlHelper->header();
$objXml .= $objXmlHelper->serilize($obj);
echo $objXml;
}
That gives empty page. However, if I echo json_encode($obj); that actually prints out json.
Thanks,
Tee
You probably have an error in your code. My guess is you are not including the XML helper.
Check you CakePHP (app/tmp/logs/) and PHP logs. In addition you may need to set the DEBUG flag to a higher level ( i.e. > 0).
I'd also recommend considering moving such things to a model. Web Services are typically data access layers and that belongs in the Model.

Resources