Get loop text values from mform - moodle

Mmform has a 'count' textfield. When user has filled with value 3, mform should create 'Unit part' by looping the textfields
(forename, designation and filemanager). Upon mform submission, I need to display Unit part filled by the user.
Could you let me know suggestions.
<?php
require('config.php');
require_once($CFG->libdir.'/formslib.php');
class active_form extends moodleform {
function definition() {
$mform = $this->_form;
$fileoptions = $this->_customdata['fileoptions'];
$count = $mform->addElement('text', 'count', get_string('count', 'form'), array('name' => 'count[]');
$count = $mform->setType('count', PARAM_INT);
for ($i=1; $i<=$count; $i++) {
// Unit
$mform->addElement('text', 'forename', get_string('forename', 'form'), array('name'=>'forename[]'));
$mform->setType('forename', PARAM_RAW);
$mform->addElement('text', 'designation', get_string('designation', 'form'), array('name'=>'designation[]'));
$mform->setType('designation', PARAM_RAW);
$mform->addElement('filemanager', 'attachment', get_string('attachment', 'form'), null, $fileoptions);
$mform->setType('attachment', PARAM_RAW);
}
$this->add_action_buttons();
}
function validation($data, $files) {
$errors = parent::validation($data, $files);
return $errors;
}
}
$mform = new active_form(null, $customdata);
if ($mform->is_submitted()) {
$data = $mform->get_data();
for ($i=1; $i <= $data->count; $i++) {
$forename = $data->forename;
$designation = $data->designation;
$attachment = $data->attachment;
echo 'forename' . $forename. '<br>';
echo 'designation' . $designation. '<br>';
echo 'attachment' . $attachment. '<br>';
}
}
echo $OUTPUT->header();
$mform->display();
echo $OUTPUT->footer();
?>
ex: User has filled with
count: 3
forename = SVs Group
designation = Assistant Engineer
attachment = 676208496
forename = Prime Group
designation = Staff Member
attachment = 646759033
forename = Ecos Group
designation = Staff Member
attachment = 107025147
Output:
count:3
forename: SVs Group
designation: Assistant Engineer
attachment: 676208496
forename: Prime Group
designation: Staff Member
attachment: 646759033
forename: Ecos Group
designation: Staff Member
attachment: 107025147

Related

Magento 2 - Update Product stock and Price Programmatically for multiple stores

I'm getting data from the CSV file and according to SKU file load the product.
We are getting 30 products from the CSV file and update those product data in Magento.
We have set up cron every 5 minutes and after 5 minutes it will get the next 30 products and update.
The starting process script is working fine. But after the sometime script is going to be slow and it will take time to update the product.
So, the next cron is running at on the same time there are lots of scripts are running on the server, and the server load will increase.
After taking so much load on the server website going to be slow.
Can you please let me know the way so product updating process will be consistent and time will not so much vary.
public function execute()
{
$data = array of csv file data;
$sql = "Select value FROM " . $tableName . " where path='catalog/product/update_cron' and scope_id=0";
$result = $connection->fetchAll($sql);
$update_cron = $result[0]['value'];
$total_products = count($data);
if ($total_products == $update_cron) {
$this->configWriter->save('catalog/product/update_cron_status', '1', 'default', '0'); // inject Magento\Store\Model\ScopeInterface;
exit;
}
if ($update_cron != '' && $update_cron != 0) {
$data = array_slice($data, (int)$update_cron, 30);
} else {
$update_cron = 0;
$data = array_slice($data, 0, 30);
}
$current_date = date("m/d/Y");
$i = 0;
foreach ($data as $key => $value) {
/*********************************************Update Product Price********************************************************/
if ($value['Artikel'] != '') {
$product = $objectManager->create('Magento\Catalog\Model\Product');
$product_id = $product->getIdBySku($value['Artikel']);
if (!empty($product_id)) {
/************************Update Product Price for all Stores**************************************/
$price_b2b = str_replace(',', '.', (string) $value['Verkoopprijs']);
$price_b2c = str_replace(',', '.', (string) $value['Numeriek1']);
$price_club = str_replace(',', '.', (string) $value['Numeriek2']);
//$special_price_b2b = str_replace(',', '.', (string) $value['Numeriek3']);
$productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action');
$productActionObject->updateAttributes(array($product_id),
array(
'name' => $value['Artikel'],
'ean_code'=>$value['Barcode'],
'price'=>$price_b2c,
'price_wholesale'=>$price_b2b,
'price_clubs'=>$price_club,
'description'=>$value['Omschrijving Engels'],
),0
);
/* if ($value['Boolean1'] == 'True') {
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => $special_price_b2b, 'special_from_date' => $current_date), 4);
} else { */
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_b2b, 'special_price' => '', 'special_from_date' => ''), 4);
//}
$objectManager->create('Magento\Catalog\Model\Product\Action')->updateAttributes(array($product_id), array('price' => $price_club), 7);
/*********************************************Inventory Update********************************************************/
$stockRegistry = $objectManager->create('Magento\CatalogInventory\Api\StockRegistryInterface');
$sku = $value['Artikel'];
if($sku != '')
{
$qty = round(str_replace(',', '', (string) $value['Stock']));
$stockItem = $stockRegistry->getStockItemBySku($sku);
$stockItem->setQty($value['Stock']);
$stockItem->setIsInStock((int) ($qty > 0)); // this line
$stockRegistry->updateStockItemBySku($sku, $stockItem);
}
/*****************************************************************************************************/
}
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
else {
$i++;
$update_val = $update_cron + $i;
$this->configWriter->save('catalog/product/update_cron', $update_val, 'default', 0);
}
}
die('records completed');
}
}
die('stop');
}
Thanks in advance

Moodle email confirmation

When a new user register, moodle send confirmation email to user, from the language file lang/en/moodle.php with a string "emailconfirmation" by a moodle function:
function send_confirmation_email($user) {
global $CFG;
$site = get_site();
$supportuser = generate_email_supportuser();
$data = new stdClass();
$data->firstname = fullname($user);
$data->sitename = format_string($site->fullname);
$data->admin = generate_email_signoff();
$subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
$username = urlencode($user->username);
$username = str_replace('.', '%2E', $username); // prevent problems with trailing dots
$data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
$message = get_string('emailconfirmation', '', $data);
$messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
return email_to_user($user, $subject, $message, $messagehtml);
}
Moodle redirects to index.php after confirmation. How do I redirect $data->link to a custom page after confirmation:
if (send_confirmation_email($user)) {
if (AUTH_CONFIRM_OK = true) {
$urltogo = new moodle_url($CFG->wwwroot . "/coursestat/view.php", array('id' => $statid));
redirect($urltogo);
}
}
else
print_error('auth_noemail','auth_email');
Just use $data->link assuming its a string?
if (send_confirmation_email($user)) {
// Assuming $data->link is a string?
$urltogo = new moodle_url($data->link);
redirect($urltogo);
}
This line
if (AUTH_CONFIRM_OK = true) {
Doesn't make sense, AUTH_CONFIRM_OK is a constant. Also = is an assignment. I'm guessing you meant something like this:
if ($somevariable == AUTH_CONFIRM_OK) {

How to add variable to header.php controller and use it in header.tpl

I am creating a custom theme for OpenCart 2.3 and I need to show some additional information in page header (header.tpl). So I added some variable to catalog/controller/common/header.php:
$data['some_var'] = 'some_value';
And then I am trying to use this data in the header.tpl:
<?php echo $this->data['some_var']; ?>
But I am always getting this error:
Notice: Undefined index: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
If I try to use this code:
<?php echo $some_var; ?>
Then I am getting another error:
Notice: Undefined variable: some_var in /var/www/store_com/public_html/catalog/view/theme/mystore/template/common/header.tpl on line 133
And even when I do echo print_r($this->data) in header.tpl I don't even see this variable in $data array.
What am I doing wrong? Please help.
EDIT
Here is the full code of my header.php controller file. I added my custom variable at the very end of the file.
class ControllerCommonHeader extends Controller {
public function index() {
// Analytics
$this->load->model('extension/extension');
$data['analytics'] = array();
$analytics = $this->model_extension_extension->getExtensions('analytics');
foreach ($analytics as $analytic) {
if ($this->config->get($analytic['code'] . '_status')) {
$data['analytics'][] = $this->load->controller('extension/analytics/' . $analytic['code'], $this->config->get($analytic['code'] . '_status'));
}
}
if ($this->request->server['HTTPS']) {
$server = $this->config->get('config_ssl');
} else {
$server = $this->config->get('config_url');
}
if (is_file(DIR_IMAGE . $this->config->get('config_icon'))) {
$this->document->addLink($server . 'image/' . $this->config->get('config_icon'), 'icon');
}
$data['title'] = $this->document->getTitle();
$data['base'] = $server;
$data['description'] = $this->document->getDescription();
$data['keywords'] = $this->document->getKeywords();
$data['links'] = $this->document->getLinks();
$data['styles'] = $this->document->getStyles();
$data['scripts'] = $this->document->getScripts();
$data['lang'] = $this->language->get('code');
$data['direction'] = $this->language->get('direction');
$data['name'] = $this->config->get('config_name');
if (is_file(DIR_IMAGE . $this->config->get('config_logo'))) {
$data['logo'] = $server . 'image/' . $this->config->get('config_logo');
} else {
$data['logo'] = '';
}
$this->load->language('common/header');
$data['text_home'] = $this->language->get('text_home');
// Wishlist
if ($this->customer->isLogged()) {
$this->load->model('account/wishlist');
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), $this->model_account_wishlist->getTotalWishlist());
} else {
$data['text_wishlist'] = sprintf($this->language->get('text_wishlist'), (isset($this->session->data['wishlist']) ? count($this->session->data['wishlist']) : 0));
}
$data['text_shopping_cart'] = $this->language->get('text_shopping_cart');
$data['text_logged'] = sprintf($this->language->get('text_logged'), $this->url->link('account/account', '', true), $this->customer->getFirstName(), $this->url->link('account/logout', '', true));
$data['text_account'] = $this->language->get('text_account');
$data['text_register'] = $this->language->get('text_register');
$data['text_login'] = $this->language->get('text_login');
$data['text_order'] = $this->language->get('text_order');
$data['text_transaction'] = $this->language->get('text_transaction');
$data['text_download'] = $this->language->get('text_download');
$data['text_logout'] = $this->language->get('text_logout');
$data['text_checkout'] = $this->language->get('text_checkout');
$data['text_category'] = $this->language->get('text_category');
$data['text_all'] = $this->language->get('text_all');
$data['home'] = $this->url->link('common/home');
$data['wishlist'] = $this->url->link('account/wishlist', '', true);
$data['logged'] = $this->customer->isLogged();
$data['account'] = $this->url->link('account/account', '', true);
$data['register'] = $this->url->link('account/register', '', true);
$data['login'] = $this->url->link('account/login', '', true);
$data['order'] = $this->url->link('account/order', '', true);
$data['transaction'] = $this->url->link('account/transaction', '', true);
$data['download'] = $this->url->link('account/download', '', true);
$data['logout'] = $this->url->link('account/logout', '', true);
$data['shopping_cart'] = $this->url->link('checkout/cart');
$data['checkout'] = $this->url->link('checkout/checkout', '', true);
$data['contact'] = $this->url->link('information/contact');
$data['telephone'] = $this->config->get('config_telephone');
// Menu
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$data['categories'] = array();
$categories = $this->model_catalog_category->getCategories(0);
foreach ($categories as $category) {
if ($category['top']) {
// Level 2
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
$filter_data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$children_data[] = array(
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
// Level 1
$data['categories'][] = array(
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
$data['language'] = $this->load->controller('common/language');
$data['currency'] = $this->load->controller('common/currency');
$data['search'] = $this->load->controller('common/search');
$data['cart'] = $this->load->controller('common/cart');
// For page specific css
if (isset($this->request->get['route'])) {
if (isset($this->request->get['product_id'])) {
$class = '-' . $this->request->get['product_id'];
} elseif (isset($this->request->get['path'])) {
$class = '-' . $this->request->get['path'];
} elseif (isset($this->request->get['manufacturer_id'])) {
$class = '-' . $this->request->get['manufacturer_id'];
} elseif (isset($this->request->get['information_id'])) {
$class = '-' . $this->request->get['information_id'];
} else {
$class = '';
}
$data['class'] = str_replace('/', '-', $this->request->get['route']) . $class;
} else {
$data['class'] = 'common-home';
}
//CUSTOM THEME VARIABLES BEGIN
$data['some_var'] = 'some_value';
//CUSTOM THEME VARIABLES END
return $this->load->view('common/header', $data);
}
}
I need to see your controller to get the full picture and then i will give you the full answer, but take a look on your controller and make sure that you bind your data like the sample below:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/header.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/common/header.tpl', $data);
} else {
return $this->load->view('default/template/common/header.tpl', $data);
}
Thanks
I finally found the solution of my problem, but I am not sure if it is the right way to do this. I found that I need to make changes in system/storage/modification/catalog/controller/common/header‌​.php. It seems like after installing some extension via Vqmod the controller file have been copied to this folder. If I add my variables there then I can access them without any issues.

Getting a menu delivered via REST

I am trying to get a menu via REST and I've created a new module and rest resource plugin that allows for GET on /entity/restmenu/{menu_name}.
I can successfully return this example json using this function when I hit the URL.
public function get(EntityInterface $entity) {
$result = array();
for ($i = 0; $i < 10; $i++) {
$temp = array(
'title' => 'Test ' . $i,
'href' => '#/' . $i
);
array_push($result, $temp);
}
return new ResourceResponse(json_encode($result));
}
I cannot figure out how to load the menu based on $entity. If I hit my URL (http://dang.dev:8888/entity/restmenu/main?_format=hal_json) $entity's value is 'main' which is the machine name of the main menu.
I've tried using Drupal menu tree, but I am not having luck, and debugging this thing with only JSON responses is quite difficult.
How do I get menu item titles and paths based on the menu machine name?
EDIT
Ok, sort of figured it out.
public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$renderable = \Drupal::menuTree()->build($tree);
$result = array();
foreach (end($renderable) as $key => $val) {
$temp = array(
'menu_item' => $val,
'route' => $key
);
array_push($result, $temp);
}
return new ResourceResponse(json_encode($result));
}
Right now that will output:
[
{
"menu_item":{
"is_expanded":false,
"is_collapsed":false,
"in_active_trail":false,
"attributes":"",
"title":"Home",
"url":{
},
"below":[
],
"original_link":{
}
},
"route":"standard.front_page"
},
{
"menu_item":{
"is_expanded":false,
"is_collapsed":false,
"in_active_trail":false,
"attributes":"",
"title":"Communities",
"url":{
},
"below":[
],
"original_link":{
}
},
"route":"menu_link_content:139d0413-dc50-4772-8200-bc6c92571fa7"
}
]
any idea why url or original_link are empty?
This was the correct answer:
public function get($entity) {
$menu_name = $entity;
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$result = array();
foreach ($tree as $element) {
$link = $element->link;
array_push($result, array(
'title' => $link->getTitle(),
'url' => $link->getUrlObject()->getInternalPath(),
'weight' => $link->getWeight()
)
);
}
return new ResourceResponse(json_encode($result));
}

Custom Joomla 1.5 View cannot find the layout default.php file

I have been developing templates for Joomla 1.5 (obsolete one, yes I knew it. Unfortunately, I've been spending some time working with it and move on to newer version will be like starting from zero).
I tried to understand how Joomla 1.5 components work, especially for those using MVC principle, and somehow I managed to make things work, except now I have been stuck with the layout of a customized view. For unknown reason, Joomla could not read or find the layout (default.php) inside the folder com_hello2/views/viewed/tmpl and give '500 error Layout default not found'.
I tried to move the default.php file from folder to folder, looking if I could figure out where Joomla want me to put the default.php. It DOES work for the default view, located on com_hello2/views/hello2/tmpl.
Could anyone please help me with this problem?
Here are the codes from the controllers:
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');
class Hello2Controller extends JController
{
function display($tpl = null)
{
$task = JRequest::getVar('task', null, 'default', 'cmd');
switch ($task){
case 'view':
$model = &$this->getModel('Viewed');
$view = &$this->getView('viewed','html');
$mylayout = 'default';
break;
case 'newstatus':
break;
default:
$view = &$this->getView('hello2','html');
$model = &$this->getModel();
$mylayout = 'default';
break;
}
$view->setModel($model,true);
$view->setLayout($mylayout);
$view->display();
}
}
?>
I created two models, one is the default Hello2ModelHello2, the new one is Hello2ModelViewed. I seperated the two models based on the tasks in the controllers.
the Hello2ModelHello2:
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport('joomla.application.component.model');
class Hello2ModelHello2 extends JModel
{
//add CC
function getComments()
{
global $mainframe;
$db = JFactory::getDBO();
$id = JRequest::getVar('id', 0, '', 'int');
$query = 'SELECT a.*'.
' FROM #__hello1 AS a '.
' LEFT JOIN #__content AS b ON a.article_id = b.id'.
' WHERE a.state = 1';
$db->setQuery( $query );
$comments = $db->loadObjectList();
return $comments;
}
}
?>
now the Hello2ModelViewed
<?php
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport('joomla.application.component.model');
class Hello2ModelViewed extends JModel
{
function __construct()
{
parent::__construct();
$id = JRequest::getVar('id', 0, '', 'int');
$this->setId((int)$id);
}
function setId($id)
{
// Set new article ID and wipe data
$this->_id = $id;
$this->_article = null;
}
//get certain comment only.
function getSingle()
{
global $mainframe;
$db = JFactory::getDBO();
$id = JRequest::getVar('id', 0, '', 'int');
$query = 'SELECT a.*'.
' FROM #__hello1 AS a' .
' LEFT JOIN #__content AS b ON a.article_id = b.id'.
' WHERE a.id = '.$id.
' AND a.state = 1';
$db->setQuery( $query );
$comments = $db->loadObjectList();
return $comments;
}
}
?>
the view.html of Viewed View is
<?php
defined('_JEXEC') or die( 'Restricted access' );
jimport( 'joomla.application.component.view');
jimport('joomla.environment.request');
class Hello2View extends JView
{
function __construct($config = array())
{
parent::__construct($config);
}
}
class Hello2ViewViewed extends Hello2View{
function display($tpl = null)
{
$model = &$this->getModel();
$id = JRequest::getVar('id', 0, '', 'int');
$comments = $model->getSingle();
JRequest::setVar('row',$comments);
parent::display($tpl);
}
}
?>
and view.html of Hello2 View is
<?php
defined('_JEXEC') or die( 'Restricted access' );
jimport( 'joomla.application.component.view');
jimport('joomla.environment.request');
class Hello2ViewHello2 extends JView{
function display($tpl = null)
{
$model = &$this->getModel();
$comments = $model->getComments();
JRequest::setVar('rows',$comments);
parent::display($tpl);
if($this->getLayout() == 'view') {
$this->view($tpl);
return;
}
}
}
?>
It works for me to execute index.php?option=com_hello2&task=display
but gets error when execute index.php?option=com_hello2&task=view
eventhough the default.php is already inside the directory views/viewed/
any input appreciated! :)