Pass Eloquent Model As An Closure Argument In PHP - eloquent

I'm using Laravel Illuminate/Database outside of laravel application. I'm trying to pass the Eloquent model as my closure argument but its throwing an error. May be I'm passing it wrongly. My code is as following:
// Create a dummy subject (This is working absolutely fine)
SubjectModel::create(array(
'title' => 'Mathematics',
'description' => 'Math Subject',
'slug' => 'math',
'ka_url' => 'http://khanacademy.org/math'
));
$scrapper = new SubjectScrapper();
$scrapper->setUrl('');
This is not working. SubjectModel is not being passed in the following closure
$scrapper->runScrapper(function($subjects) use ($scrapper, SubjectModel $subjectModel) {
if(!empty($subjects))
{
foreach ($subjects as $subject) {
$urlParts = explode('/', $subject['url']);
$slug = end($urlParts);
$subjectModel::create(array(
'title' => $subject['subject_name'],
'slug' => $slug,
'ka_url' => $scrapper->getBaseUrl().$subject['link'],
));
}
}
});
Could anybody please tell me how to accomplish this task.

Try this. No need to pass object in closure
$scrapper = new SubjectScrapper();
$scrapper->setUrl('');
$scrapper->runScrapper(function($subjects) use ($scrapper, $output) {
SubjectModel::create(array(
'title' => 'Math',
'slug' => 'math',
'ka_url' => 'http://math'
));
$output->writeln('<info>Total Subjects Scrapped:: '.count($subjects).'</info>'.PHP_EOL);
});

Related

Error test upload php unit symfony2

Im following the tutorial from symfony's website to make my phpunit's test for my controller.
Im trying to test an upload on a form and i have 3 fields on this form : title,description and file.
I use :
public function testScenarioAdd() {
$client = static::createClient();
$x_wsse = 'UsernameToken Username="username#fai.fr", PasswordDigest="aeirugbjcUbfmùJK", Nonce="OTMzOGMwYzFkYTk2MzJmYzBh", Created="2013-11-12T10:22:15+01:00"';
//X_Wsse is for the connection systeme on my application.
$image = new UploadedFile(
'/past/to/your/images.jpg',
'images.jpg',
'image/jpeg',
100000
);
$crawler = $client->request('POST', '/ad/create', array('ad_form' => array('title' => 'test', 'description' => 'Test description')),array(), array('CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'HTTP_X-WSSE' => $x_wsse));
$response = $client->getResponse()->getContent();
$json_response = json_decode($response);
print_r($response);
}
When i launch it I have an error saying :
{"app_error":{"success":500,"result":[{"message":"Array to string conversion",...
Am i doing something wrong ? or missing something in my code ?
Thanks for your help :)
Edit :
Thanks but, what ive done there is working on another test without upload, i still tried it and its not working. I still have the error array to string... I think it come from the fonction UplaodedFile or maybe from my controller itself because when i try the other solution from symfony's web site with
$photo = array(
'tmp_name' => '/path/to/photo.jpg',
'name' => 'photo.jpg',
'type' => 'image/jpeg',
'size' => 123,
'error' => UPLOAD_ERR_OK
);
With putting the
$crawler = $client->request('POST', '/ad/create', array('ad_form[title]' => 'test', ad_form[description] => 'test description'),array('file' => $image),array('CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'HTTP_X-WSSE' => $x_wsse));
The important part of my controller is :
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid())
{
$Ad->preCreate();
$odm->persist($Ad);
$odm->flush();
$odm->clear();
$data = $this->listAction($request, 1, 5);
Tags::setEvent($request, $this->container, 'member.create.ad', $user->getId(), $Ad->getId());
return $data;
} else {
$data = Errors::formatJson($form, $this->container);
}
}
}
return new JsonResponse(array('ad_create' => $data));
Im kinda new in symfony, i really dont know where this error can come from...
Client::Request method expects you to provide it with one-dimensional array of data. So try this code:
<?php
//...
$crawler = $client->request('POST', '/ad/create',
array('ad_form[title]' => 'test',
'ad_form[description]' => 'Test description'),
array(),
array('CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'HTTP_X-WSSE' => $x_wsse));

Drupal custom form and autocomplete issue

Some how I managed to get it work. But still the result is not coming along with the autocomplete.
Posting my latest code now,
the textfield code
$form['town'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#autocomplete_path' => 'hfind/town/autocomplete',
);
menu function code
function hfind_menu() {
$items = array();
$items['hfind/town/autocomplete'] = array (
'title' => 'Autocomplete for cities',
'page callback' => 'hfind_town_autocomplete',
'access arguments' => array('use autocomplete'),
'type' => MENU_CALLBACK
);
return $items;
}
the callback function code
function hfind_town_autocomplete($string){
$matches = array();
$result = db_select('towns', 't')
->fields('t', array('town_name'))
->condition('town_name', '%' . db_like($string) . '%', 'LIKE')
->execute();
foreach ($result as $row) {
$matches[$row->city] = check_plain($row->city);
}
drupal_json_output($matches);
}
I hope this may the final edit.
The current situation is, autocomplete is working
The url is hfind/town/autocomplete/mtw
but it is not able to find any data from the database. I found why and unable to fix it.
It is because in the last function I've added above the $string needs to be the 'search query' but it is always querying the database as 'autocomplete'. I mean the $string variable always having the value 'autocomplete' instead of user typed value.
One more problem is, even after providing the permission to all types of user to access search autocomplete on the forms, guests users are not able to use the feature.
Please please someone help me..
`drupal_json_output()` instead of `drupal_to_js` and remove `print` .
<code>
hook_menu() {
$items['cnetusers/autocomplete'] = array(
'title' => 'Auto complete path',
'page callback' => 'cnetusers_employees_autocomplete',
'page arguments' => array(2, 3, 4, 5),
'access arguments' => array('access user profiles'),
'type' => MENU_CALLBACK,
);
return $item;
}
// my autocomplete function is like this
function cnetusers_employees_autocomplete() {
// write your sql query
$matches["$record->ename $record->elname [id: $record->uid]"] = $value;
}
if (empty($matches)) {
$matches[''] = t('No matching records found.');
}
drupal_json_output($matches);
}
$form['disc_info']['approval'] = array(
'#type' => 'textfield',
'#title' => t('Approval By'),
'#autocomplete_path' => 'cnetusers/autocomplete',
);
</code>

Cake PHP custom validation rule

I got a problem with a custom validation rule in Cake 2.X
I want to check if the entered zipcode is valid and therefore a function in the class zipcode is called from the class post.
But the validation returns false all the time.
Appmodel in class post (rule-3 is it):
'DELIVERYAREA' => array(
'rule-1' => array(
'rule' => array('between', 5, 5),
'message' => 'Bitte eine fünfstellige Postleitzahl eingeben'
),
'rule-2' => array(
'rule' => 'Numeric',
'message' => 'Bitte nur Zahlen eingeben'
),
'rule-3' => array(
'exists' => array(
'rule' => 'ZipExists',
'message' => 'Postleitzahl existiert nicht!'
)
)
),
Appmodel in class zipcode:
class Zipcode extends AppModel {
var $name = 'Zipcode';
var $validate = array(
'zipcode' => array(
'length' => array(
'rule' => array('maxLength', 5),
'message' => 'Bitte einen Text eingeben'
),
'exists' => array(
'rule' => array('ZipExists'),
'message' => 'Postleitzahl existiert nicht!'
)
)
);
function ZipExists($zipcode){
$valid = $this->find('count', array('conditions'=> array('Zipcode.zipcode' =>$zipcode)));
if ($valid >= 1){
return true;
}
else{
return false;
}
}
I hope it´s something stupidly easy?
Thanks in advance
I think this:
'Zipcode.zipcode' =>$zipcode
...needs to be this:
'Zipcode.zipcode' =>$zipcode['zipcode']
Careful what you expect inside the validation rule. Use debug() etc to find out what exactly is coming in. $data is always an array here.
public function zipExists($data) {
$zipcode = array_shift($data); // use the value of the key/value pair
$code = $this->find('first', array('conditions'=> array('Zipcode.zipcode' =>$zipcode)));
return !empty($code);
}
try this for only model validation.
function ZipExists(){
$valid = $this->find('count', array('conditions'=> array('Zipcode.zipcode' =>$this->data['Zipcode']['zipcode'])));
if ($valid >= 1){
return true;
}
else{
return false;
}
I found the solution.
Cake wants the custom validation rules to be in the certain class where the rule is called. So, when you call a custom rule in class post, the custom function has to be written down in class post, otherwise cake won´t find it and validate it to false everytime.
The magic to do here is to import the appmodel-class you want to use in the class you call the validation-function. That works with the following statement:
$Zipcode = ClassRegistry::init('Class to use - in my case "Zipcode"');
But if your tables are associated with each other with hasAny or belongsTo and stuff, the custom function works without that. Another important point you mustn´t miss is, that all validation functions has to be introduced with "public function xyz" otherwise cake won´t find them too.

Module Forms - Store Value of addField to a Variable

I have something like in my custom module:
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $order_id)),
'value' => 'Magento Blog',
'after_element_html' => '',
));
And as you can see from the code, I am trying to link that field to the Order Tab in the back-end. I'm having trouble getting the ID though. I'm planning to just save the Order ID in the database, and then using the addField I could have the correct url.
But how can I save an addField value to a variable?
I want to store the value in "$order_id".
Is it possible?
I am not sure in which context you are using this fieldset but if it is used for example for creating or editing object you can try something like that:
In controller:
public function editAction()
{
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('module/model')->load($id);
Mage::register('model_name', $model);
}
and then in the block:
protected function _prepareForm()
{
$model = Mage::registry('model_name');
// add fieldset to form
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $model->getOrderId())),
'value' => 'Magento Blog',
'after_element_html' => '',
));
//rest of the elements
}
Answering my own post again. (src: https://magento.stackexchange.com/questions/682/module-forms-store-value-of-addfield-to-a-variable)

Get all parameters after action in Zend?

When I call a router like below in Zend:
coupon/index/search/cat/1/page/1/x/111/y/222
And inside the controller when I get $this->_params, I get an array:
array(
'module' => 'coupon',
'controller' => 'index',
'action' => 'search',
'cat' => '1',
'page' => '1',
'x' => '111',
'y' => '222'
)
But I want to get only:
array(
'cat' => '1',
'page' => '1',
'x' => '111',
'y' => '222'
)
Could you please tell me a way to get the all the params just after the action?
IMHO this is more elegant and includes changes in action, controller and method keys.
$request = $this->getRequest();
$diffArray = array(
$request->getActionKey(),
$request->getControllerKey(),
$request->getModuleKey()
);
$params = array_diff_key(
$request->getUserParams(),
array_flip($diffArray)
);
As far as I know, you will always get the controller, action and module in the params list as it is part of the default. You could do something like this to remove the three from the array you get:
$url_params = $this->getRequest()->getUserParams();
if(isset($url_params['controller']))
unset($url_params['controller']);
if(isset($url_params['action']))
unset($url_params['action']);
if (isset($url_params['module']))
unset($url_params['module']);
Alternatively as you don't want to be doing that every time you need the list, create a helper to do it for you, something like this:
class Helper_Myparams extends Zend_Controller_Action_Helper_Abstract
{
public $params;
public function __construct()
{
$request = Zend_Controller_Front::getInstance()->getRequest();
$this->params = $request->getParams();
}
public function myparams()
{
if(isset($this->params['controller']))
unset($this->params['controller']);
if(isset($this->params['action']))
unset($this->params['action']);
if (isset($this->params['module']))
unset($this->params['module']);
return $this->params;
}
public function direct()
{
return $this->myparams();
}
}
And you can simply call this from your controller to get the list:
$this->_helper->myparams();
So for example using the url:
http://127.0.0.1/testing/urls/cat/1/page/1/x/111/y/222
And the code:
echo "<pre>";
print_r($this->_helper->myparams());
echo "</pre>";
I get the following array printed:
Array
(
[cat] => 1
[page] => 1
[x] => 111
[y] => 222
)
How about this?
In controller:
$params = $this->getRequest()->getParams();
unset($params['module'];
unset($params['controller'];
unset($params['action'];
Pretty clunky; might need some isset() checks to avoid warnings; could jam this segment into its own method or helper. But it would do the job, right?