How to show navigation bar options to specific users in moodle lms? - moodle

Below is my code for showing an extra option in navigation-drawer of Moodle LMS account.
function local_report_extend_navigation(global_navigation $navigation)
{
$main_node = $navigation->add(get_string('pluginname', 'local_report'), '/local/report/');
$main_node->nodetype = 1;
$main_node->collapse = false;
$main_node->force_open = true;
$main_node->isexpandable = false;
$main_node->showinflatnavigation = true;
// $main_node->icon = new pix_icon('i/settings', get_string('pluginname', 'local_report'));
$main_node->icon = new pix_icon('i/files', get_string('pluginname', 'local_report'));
}
The output for it is :
This is the navigation-drawer. I want to show the Reports option to only admin, teacher and manager
Can anyone let me know how to make this done?

You will need to create a capability in your local plugin. In local/report/db/access.php
$capabilities = array(
'local/report:canview' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array(
'manager' => CAP_ALLOW,
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
),
),
);
Then use something like this in your function.
if (!has_capability('local/report:canview', \context_system::instance())) {
return;
}

Related

Upload scorm packages in moodle course module using moodle rest api

I have already created a course using moodle RestAPI(function name : core_course_create_courses). then i want to upload a scorm package in moodle course module/activity.
i have write some code for that,this code will create a module in that course. i don't know how to upload scorm package in that course module.
here is my code
Add function core_course_create_modules in lib/db/services.php at line no : 327
'core_course_create_modules' => array(
'classname' => 'core_course_external',
'methodname' => 'create_modules',
'classpath' => 'course/externallib.php',
'description' => 'Creates modules in a course',
'type' => 'write',
'capabilities' => 'moodle/course:manageactivities',
)
Add 3 method in Courses/externallib.php file
2.1)create_modules_parameters
=> `public static function create_modules_parameters() {
$courseconfig = get_config('moodlecourse'); //needed for many default values
return new external_function_parameters(
array(
'courseid' => new external_value(PARAM_INT, 'ID of the course'),
'modules' => new external_multiple_structure(
new external_single_structure(
array(
'modulename' => new external_value(PARAM_TEXT, 'Name of the module'),
'section' => new external_value(PARAM_INT, 'Sectionnumber'),
'name' => new external_value(PARAM_TEXT, "Title of the module", VALUE_OPTIONAL),
'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
'description' => new external_value(PARAM_TEXT, 'the new module description', VALUE_OPTIONAL),
'descriptionformat' => new external_format_value(PARAM_INT, 'description', VALUE_DEFAULT),
'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_DEFAULT, $courseconfig->groupmode),
'groupmembersonly' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_DEFAULT, 0),
'groupingid' => new external_value(PARAM_INT, 'grouping id',VALUE_DEFAULT, 0)
)
)
)
)
);
}`
2.2) create_modules
`public static function create_modules($courseid, $modules) {
global $CFG, $DB;
require_once($CFG->dirroot . "/course/lib.php");
require_once($CFG->dirroot . "/course/modlib.php");
$moduleinfo = new stdClass();
$course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
// Clean the parameters.
$params = self::validate_parameters(self::create_modules_parameters(), array('courseid' => $courseid,'modules' => $modules));
$context = context_course::instance($course->id);
require_capability('moodle/course:manageactivities', $context);
foreach ($params['modules'] as $mod) {
$module = (object) $mod;
$moduleobject = $DB->get_record('modules', array('name'=>$module->modulename), '*', MUST_EXIST);
if(trim($module->modulename) == ''){
throw new invalid_parameter_exception('Invalid module name');
}
if (!course_allowed_module($course, $module->modulename)){
throw new invalid_parameter_exception('Module "'.$module->modulename.'" is disabled');
}
if(is_null($module->visible)){
$module->visible = 1;
}
if(is_null($module->description)){
$module->description = '';
}
if(!is_null($module->name) && trim($module->name) != ''){
$moduleinfo->name = $module->name;
}
$moduleinfo->modulename = $module->modulename;
$moduleinfo->visible = $module->visible;
$moduleinfo->course = $courseid;
$moduleinfo->section = $module->section;
$moduleinfo->introeditor = array('text' => $module->description, 'format' => $module->descriptionformat, 'itemid' => 0);
$moduleinfo->quizpassword = '';
$moduleinfo->groupmode = $module->groupmode;
$moduleinfo->groupmembersonly = $module->groupmembersonly;
$moduleinfo->groupingid = $module->groupingid;
$retVal = create_module($moduleinfo);
$result[] = array('id'=>$retVal->id);
}
return $result;
}`
2.3)create_modules_returns
`public static function create_modules_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'new module id')
)
)
);
}`
Parameters to call function
$module['courseid'] = 1; //course id
$module['modules'][] = array(
"section" => 2,//PARAM_INT, 'Sectionnumber'
"modulename" => "scorm",//PARAM_TEXT, 'Name of the module'
"name" => "Testing1",// OPTIONAL PARAM_TEXT, "Title of the module",
"visible" => 1,// OPTIONAL PARAM_INT, '1: available to student, 0:not available',
"description"=>"testing module using rest api", // OPTIONAL PARAM_TEXT, 'the new module description',
"descriptionformat"=>1,//PARAM_INT, 'description', VALUE_DEFAULT
//"groupmode" => "",//PARAM_INT, 'no group, separate, visible', VALUE_DEFAULT, $courseconfig->groupmode
//"groupmembersonly" => "",//PARAM_INT, '1: yes, 0: no', VALUE_DEFAULT, 0
//"groupingid" => "",//PARAM_INT, 'grouping id',VALUE_DEFAULT, 0
);
as per above code ,
its take name field as a scorm packages, in the admin side its display name as a scorm, when i was click on that its display errors:
screenshot for error
so, i don't know how to upload scorm package in course module using moodle Rest api, how can i do ?
Thank you.

Cant Create Facebook Ad via Ads API

I am trying to create a Facebook AD via their PHP SDK. The problem lies in the creation of the ad itself. If I comment out the last piece, its creates the adset. When I run this code, I get the error "a Parent ID is required"
try {
///////////////////////////// CREATE AD SET ////////////////////////////////////
$data = array(
AdSetFields::NAME => $adname,
AdSetFields::BID_TYPE => 'CPC',
AdSetFields::BID_INFO => array(
'CLICKS' => 6,
),
AdSetFields::CAMPAIGN_STATUS => AdSet::STATUS_PAUSED,
AdSetFields::DAILY_BUDGET => 500000,
AdSetFields::CAMPAIGN_GROUP_ID => $campaign_id,
AdSetFields::TARGETING => array(
'age_min' => 30,
'age_max' => 45,
'page_types' => array(
'desktopfeed',
),
'geo_locations' => array(
'countries' => array(
'US',
),
),
),
);
$adset = new AdSet(null, $account_id);
$adset->create($data);
$adset_id = $adset->id;
echo $adset_id.'-';
//////////////////////CREATE AD IMAGE ///////////////////////////////
$image = new AdImage(null, $account_id);
$image->{AdImageFields::FILENAME} = '../adimages/epsom.jpg';
$image->create();
$creative = new AdCreative(null, $account_id);
$creative->setData(array(
AdCreativeFields::TITLE => $adtitle,
AdCreativeFields::BODY => $addesc,
AdCreativeFields::OBJECT_URL => $tracking_promoted_url,
AdCreativeFields::IMAGE_HASH => $image->hash,
));
$creative->create();
echo $creative->id.'-';
/////////////////////////////// CREATE AD GROUP ////////////////////////////
$fields = array(array(
AdGroupFields::CREATIVE =>
array('creative_id' => $creative->id),
AdGroupFields::ADGROUP_STATUS => AdGroup::STATUS_PAUSED,
AdGroupFields::NAME => 'My First AdGroup',
AdGroupFields::CAMPAIGN_ID => $adset_id,
));
$ad = new AdGroup();
$ad->create($fields);
echo 'AdGroup ID:' . $adgroup->id . "-";
} catch (RequestException $e) {
echo 'Caught Exception: '.$e->getMessage().PHP_EOL
.'Code: '.$e->getCode().PHP_EOL
.'HTTP status Code: '.$e->getHttpStatusCode().PHP_EOL;
}
You're missing the parent ID parameter when you create the adgroup. The 2nd parameter should be the account ID you want to create this adgroup under:
$adgroup = new Adgroup(null, $accountId);
If you copied this from a doc, let me know and we can update.
You may reference to the latest doc: https://developers.facebook.com/docs/marketing-api/reference/ad-campaign
From there, you will need to specify the ad account id(AD_ACCOUNT_ID) and ad campaign id(CAMPAIGN_GROUP_ID)

How to edit cell Zfdatagrid

how I can make editing row using ajax with zfdatagrid, thanks
ZF 1.11 -
My Bootstrap
protected function _initZfdatagrid()
{
$this->_config = new Zend_Config_Ini(APPLICATION_PATH .'/configs/grid.ini', 'production');
Zend_Registry::set('config', $this->_config);
if ( #isset(Zend_Registry::get('config')->site->jqGridUrl) ) {
Bvb_Grid_Deploy_JqGrid::$defaultJqGridLibPath = Zend_Registry::get('config')->site->jqGridUrl;
}
}
My Controller
public function indexAction()
{
$grid1 = new Bvb_Grid_Deploy_JqGrid(Zend_Registry::get('config'));
$this->configG1($grid1);
$grid1->setDeployOptions(array
('title'=>'Grado 10A',
'subtitle'=>'School2.0 : Matematicas:'.date('Y-m-d'),
'logo'=>$this->view->baseUrl.'/zfdatagrid/public/images/logotipo.jpg',
));
$this->view->grid = $grid1->deploy();
$this->render('index');
}
public function configG1 ($grid)
{
$select = $this->_db->select()->from('Articulos', array('id', 'titulo', 'fecha','nota', 'publicar', 'dependencia'));
$grid->setSource(new Bvb_Grid_Source_Zend_Select($select));
$grid->updateColumn('id',
array('title' => '#ID', 'hide' => true));
$grid->updateColumn('_action',
array('search' => false, // this will disable search on this field
'order' => 1, 'title' => 'Action', 'width' => 100, 'class' => 'bvb_action bvb_first', 'callback' =>
array('function' => array($this, 'g1ActionBar'), 'params' =>
array('{{ID}}')), 'jqg' =>
array('fixed' => true, 'search' => false)));
$grid->updateColumn('titulo', array('title' => 'Titulo Articulo', 'width' => 260));
$grid->updateColumn('fecha', array('title' => 'Fecha', 'searchType' => "="));
$grid->updateColumn('Nota', array('title' => 'Calificacion (ucase)', 'callback' => array('function' => create_function('$text', 'return strtoupper($text);'), 'params' => array('{{District}}'))));
$grid->setDefaultFilters(array('titulo' => '1'));
$grid->setExport(array(// define parameters for csv export, see Bvb_Grid::getExports
'csv' => array('caption' => 'Csv'),
'pdf' => array('caption' => 'Pdf')));
$grid->setJqgParams(array('caption' => 'jqGrid Example', 'forceFit' => true, 'viewrecords' => false, // show/hide record count right bottom in navigation bar
'rowList' => array(10, 20, 30, 40, 50), // show row number per page control in navigation bar
'altRows' => true)// rows will alternate color
);
$grid->setJqgParam('viewrecords', true);
$grid->jqgViewrecords = true;
$grid->setBvbParams(array('id' => 'ID'));
$grid->setBvbParam('id', 'ID');
$grid->bvbId = 'ID';
$grid->bvbOnInit = 'console.log("this message will not be logged because of call to bvbClearOnInit().");';
$grid->bvbClearOnInit();
$grid->bvbSetOnInit('console.log("jqGrid initiated ! If data are remote they are not loaded at this point.");');
$grid->setAjax(get_class($grid));
}
If you haven't gotten anywhere on this, you might want to look at the jqgrid wiki. They provide information on adding inline cell editing:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:cell_editing
as well as popup form editing:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing
According to the inline cell editing page, adding the cellEdit parameter should enable cell editing. You can provide the url the data is submit to with the cellurl parameter.

Zend page caching similar to smarty?

I there a way to make zend_cache treat front end view similar to smarty? I would like to reduce load times and page caching seems the best way todo this.
Also it would need something similar to {nocache}.
Okay so I now have: Bootstrap.php
protected function _initCache() {
$this->bootstrap('locale');
$locale = $this->getResource('locale');
$front = array ( 'lifetime' => 1800,
'automatic_serialization' => false,
'caching' => true,
'cache_id_prefix' => 'ec_',
'debug_header' => true,
'default_options'
=> array ('cache_with_get_variables' => true,
'cache_with_post_variables' => false,
'cache_with_session_variables' => false,
'cache_with_cookie_variables' => false ),
);
$back = array('cache_dir' => '../data/Cache/'.$locale);
$cache = Zend_Cache::factory('Page', 'File', $front, $back);
$cache->start();
Zend_Registry::set('cache', $cache);
return $cache;
}
However, the only time my cache is hit is with code like:
$cache = Zend_Registry::get('cache');
if (!$data = $cache->load('sidebar_'.$module.'_'.$controller)) {
$data['Studio'] = Eurocreme_Studio::load_by_type(array('type' => 'sidebar', 'from' => 0, 'to' => COUNT_HIGH));
$data['Movie'] = Eurocreme_Movie::load_by_type(array('type' => 'sidebar', 'from' => 0, 'to' => 5));
$data['Gallery'] = Eurocreme_Gallery::load_by_type(array('type' => 'sidebar', 'from' => 0, 'to' => 5));
$data['Category'] = Eurocreme_Category::load_tree(0);
$cache->save($data, 'my_view_helper_sidebar_'.$module.'_'.$controller);
}
I was hoping to capture the entire views.
Does anyone have any working examples of how to implement it fully? The docs don't really go in-depth.
You may want to use Zend_Cache_Frontend_Output or Zend_Cache_Frontend_Page. From Zend Framework manual:
Zend_Cache_Frontend_Output is an output-capturing frontend. It utilizes output buffering in PHP to capture everything between its start() and end() methods.
Zend_Cache_Frontend_Page is like Zend_Cache_Frontend_Output but designed for a complete page.
You are probably looking for Zend_Cache_Frontend_Page. Please refer to Zend Cache docs for details.

Drupal Form:want to show previous form value as default_value on page

My Goal is if user is submitting this form with "Product Name" value as "YYY". On submit page should reload but this time "Product Name" should show previous valye as default as in this case "YYY".
Here is my code...
function addnewproduct_page () {
return drupal_get_form('addnewproduct_form',&$form_state);
}
function addnewproduct_form(&$form_state) {
$form = array();
$formproductname['productname'] = array (
'#type' => 'textfield',
'#title' => t('Product Name'),
'#required' => TRUE,
'#size' => '20',
);
if (isset($form_state['values']['productname']))
{
$form['productname']['#default_value'] = $form_state['values']['productname'];
}
//a "submit" button
$form['submit'] = array (
'#type' => 'submit',
'#value' => t('Add new Product'),
);
return $form;
}
You can use $form_state['storage'] in your submit handler to hoard values between steps. So add a submit function like so:
function addnewproduct_form_submit ($form, &$form_state) {
// Store values
$form_state['storage']['addnewproduct_productname'] = $form_state['values']['productname'];
// Rebuild the form
$form_state['rebuild'] = TRUE;
}
Then your form builder function would become:
function addnewproduct_form(&$form_state) {
$form = array();
$form['productname'] = array (
'#type' => 'textfield',
'#title' => t('Product Name'),
'#required' => TRUE,
'#size' => '20',
);
if (isset($form_state['storage']['addnewproduct_productname'])) {
$form['productname']['#default_value'] = $form_state['storage']['addnewproduct_productname'];
}
return $form;
}
Just remember that your form will keep being generated as long as your $form_state['storage'] is stuffed. So you will need to adjust your submit handler and unset($form_state['storage']) when are ready to save values to the database etc.
If your form is more like a filter ie. used for displaying rather than storing info, then you can get away with just
function addnewproduct_form_submit ($form, &$form_state) {
// Rebuild the form
$form_state['rebuild'] = TRUE;
}
When the form rebuilds it will have access to $form_state['values'] from the previous iteration.
Drupal will do this by default if you include:
$formproductname['#redirect'] = FALSE;
In your $formproductname array.
I prefer to save all values in one time when we are speaking about complex forms :
foreach ($form_state['values'] as $form_state_key => $form_state_value) {
$form_state['storage'][$form_state_key] = $form_state['values'][$form_state_value];
}
simply adding rebuilt = true will do the job:
$form_state['rebuild'] = TRUE;
version: Drupal 7
For anyone looking for an answer here while using webform (which I just struggled through), here's what I ended up doing:
//in hook_form_alter
$form['#submit'][] = custom_booking_form_submit;
function custom_booking_form_submit($form, &$form_state) {
// drupal_set_message("in form submit");
// dpm($form_state, 'form_state');
foreach ($form_state['values']['submitted_tree'] as $form_state_key => $form_state_value) {
$form_state['storage'][$form_state_key] = $form_state_value;
}
}
Note: added the ' as it was lost
In my case I had a couple of drop-downs. Submitting the form posted back to the same page, where I could filter a view and I wanted to show the previously selected options. On submitting the form I built a query string in the submit hook:
function myform_submit($form, &$form_state) {
$CourseCat = $form_state['values']['coursecat'];
drupal_goto("courses" , array('query' =>
array('cat'=>$CourseCat))
);
}
In the form build hook, all I did was get the current query string and used those as default values, like so:
function myform_form($form, &$form_state) {
$Params = drupal_get_query_parameters ();
$CatTree = taxonomy_get_tree(taxonomy_vocabulary_machine_name_load ('category')->vid);
$Options = array ();
$Options ['all'] = 'Select Category';
foreach ($CatTree as $term) {
$Options [$term->tid] = $term->name;
}
$form['cat'] = array(
'#type' => 'select',
'#default_value' => $Params['cat'],
'#options' => $Options
);
$form['submit'] = array(
'#type' => 'submit',
'#default_value' => 'all',
'#value' => t('Filter'),
);
return $form;
}
I usually solve this by putting the submitted value in the $_SESSION variable in the submit hook. Then the next time the form is loaded, I check the $_SESSION variable for the appropriate key, and put the value into the #default_value slot if there's anything present.
Not sure if this would work for you, but you could try adding the #default_value key to the form array
$form['productname'] = array (
'#type' => 'textfield',
'#title' => t('Product Name'),
'#required' => TRUE,
'#size' => '20',
'#default_value' => variable_get('productname', ''),
);
That way if the variable is set it will grab whatever it is, but if not you can use a default value.