I could find a proper solution in the forum for my problem.
In my Laravel nova I have some Course Categories and if the user wants to delete some of them I
create an action to delete the data but before that I
check if these course categories have some courses in it.
This works everything fine. I'll go trough a foreach loop for every checked
Categorie but if some are deletable and some not the foreach breaks out and stops.
I think its because the return statements. But how can i get this return
`Action::message('Deleted!');`
OR
Action::danger('The Course Category "'.$model->name.'" could not be deleted, it may contains some Courses!');
done without breaking out of the loop and continue ?
Set a variable before the loop - let's call it "alldeleted".
$alldeleted = true;
And also set a blank array for categories that cannot be deleted :
$undeletedcategories = array();
If, during the loop, one of the categories cannot be deleted, note that by setting alldeleted to be false, adding the category name to the array, and using continue to go to the next element in the loop :
$alldeleted = false;
$undeletedcategories[] = $model->name;
continue;
Then, at the end of the process, look at whether $alldeleted is true or not and compose your response accordingly :
if($alldeleted) {
// return your "all deleted alright" status message here.
} else {
// Return the "these categories weren't deleted" status message here.
}
Thanks for the fast help Giles, I was able to solve my issue. I added another foreach to fill all the Category names in the Message.
$alldeleted = true;
$undeletedcategories = [];
$categorie = [];
foreach ($models AS $model)
{
$course = Course::where('category_id', $model->id)->count();
if($course === 0)
{
$model->delete();
}
else {
$alldeleted = false;
$undeletedcategories[] = $model->name;
}
}
if($alldeleted === true) {
return Action::message('Deleted all selected Courses successfully!');
} else {
foreach($undeletedcategories AS $cat)
{
$categorie[] = $cat;
}
return Action::danger('The following Course Category "'.implode(", ",$categorie).' " could not be deleted, it may contains some Courses!');
}
Related
How to allow only one set of data from an array in Laravel-5.4 controller:
foreach(Cart::content() as $cartitem) {
if($cartitem->id === $id){
do something....
}
}
I want to take only the set of data from $cartitem when $cartitem->id === $id ($id is coming from request) and reject all other set of data from $cartitem. Set of data can be found anywhere (in any index) from the array.
You can use where() of eloquent to achieve the same.
Cart::content()->where('id', $id);
I would recommend that in the request you already query for that specific id from cart. This way you don't need this foreach loop.
foreach(Cart::content() as $cartitem) {
if($cartitem->id === $id){
$cartitem; // this is your item
break; // break from loop you found it already so stop looping
}
}
From the documentation you can use: (returns all items with id = 1)
$cart->search(function ($cartItem, $rowId) {
return $cartItem->id === 1; // this will return all items with id = 1
});
Or get by rowId
$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; // this is just demo code
Cart::get($rowId);
Here my problem is when i go for updating the values already stored in the database is getting deleted and only the newly added values are getting
here is my code
<script>
$(document).ready(function() {
if(destId=='bar3' || sourceId=='bar3') {
var itemvalue2 =Array();
$('ul#bar3 li').each(function() {
itemvalue2.push($(this).attr("value"));
});
document.getElementById("bar3-output").value=itemvalue2;
}
});
</script>
here is my view
<ul id="bar3" class="block__list block__list_tags">
<input type="hidden" id="bar3-output" name="all_active_menu3" class="form-control"
value="<?php if(!empty($team_info->members)) {
$tagsArray = explode(',', $team_info->members);
$tagsLinksArray = array();
foreach($tagsArray as $tag) {
$tagName = trim($tag);
$tagsLinksArray[]=$tagName;
}
$tagsLinks = implode(',', $tagsLinksArray);
echo $tagsLinks;}?>
">
</ul>
Here is my control
public function save_team($team_id = NULL)
{
$profile_data=$this->Teams_model->array_from_post(array('team_name'));
$this->Teams_model->_table_name = 'tbl_teams'; // table name
$this->Teams_model->_primary_key = 'team_id'; // $id
if (!empty($team_id)) {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data, $team_id);
} else {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data);
}
if (!empty($team_id)) {
$message = ('Team Info Updated');
} else {
$message = ('Team Info Saved');
}
$type = 'success';
set_message($type, $message);
redirect('admin/team/team_list'); //redirect page
}
the value in the database is not becoming stable i had used many ideas but didn't reached destination.hope your help please help me
I'm not certain how your code works but here is what my guess is and what is going wrong: You're just replacing the old value in both cases.
This seems to be the relevant code fragment.
$profile_data=$this->Teams_model->array_from_post(array('team_name'));
//...
if (!empty($team_id)) {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data, $team_id);
} else {
$profile_data['members']=$this->input->post('all_active_menu3');
$this->Teams_model->save($profile_data);
}
The first assignment of $profile_data reads the current team data from the existing team. Your naming is a bit confusing as you're not actually reading any POST data it seems. The assignment within the if block that would fulfill the condition !empty($team_id) should update the team members and the false block should create a new team. Did you verify that $team_id gets set successfully?
I'm not certain about the structure of the team information but rather than a straight assignment using = in the true block you should be using += or manually combine the new and old data and do the assignment afterwards.
Using something like array_merge or a loop to create an intermittent object to hold the combined data should work here.
I'm trying to make an interface where I can edit some of the metadata attached to a lineitem. I've tried using update_post_meta() on the line item itself, however that returns bool(false). How can I update the line item meta data manually?
Thanks!
so I managed to figure it out. I wrote a small function that's below. So, all you need to do is load up the order using the API, parse through each line item and you can call wc_update_order_item_meta. The only thing is, you need to know the variation ID of the item being sold if you only want to update a specific item.
function update_order_item_meta($orderID, $variationID, $metaID, $metaValue) {
$order = returnWC_API()->get_order($orderID)->{'order'};
if(!$order) {
return false;
}
if($variationID == "all") {
foreach ($order->{'line_items'} as $line_item) {
if(!wc_update_order_item_meta($line_item->{'id'}, $metaID, $metaValue)) {
return false;
}
}
return true;
}
foreach ($order->{'line_items'} as $line_item) {
if($line_item->{'product_id'} == $variationID) {
return wc_update_order_item_meta($line_item->{'id'}, $metaID, $metaValue);
}
}
}
I need to loop all Moodle registered users and get their usernames, in order to compare their values with the data I extracted from https://clip.unl.pt/sprs?lg=pt&year=2013&uo=97747&srv=rsu&p=1&tp=s&md=3&rs=8145&it=1030123459
The data that I want is the values inside Identificador.
The Requires:
require_once('../../config.php');
require_once('../../lib/accesslib.php');
require_once($CFG->libdir.'/adminlib.php');
require_once($CFG->dirroot.'/'.$CFG->admin.'/user/lib.php');
require_once('lib.php');
require_login();
if (!isset($SESSION->bulk_users)) {
$SESSION->bulk_users = array();
}
function buildURL($year, $period, $typeperiod,$course)
{
return 'https://clip.unl.pt/sprs?lg=pt&year='.$year.'&uo=97747&srv=rsu&p='.$period.'&tp='.$typeperiod.'&md=3&rs='.$course.'&it=1030123459';
}
function doRequest_with_FileGetContents($url)
{
return file_get_contents($url);
}
This is getting me the values inside Identificador tags
function processXML($xmlContent){
$xmlObj= new SimpleXMLElement($xmlContent);
foreach($xmlObj->unidade_curricular->inscritos->aluno as $aluno){
$result= $aluno->identificador."<br/>";
return $result;
}
This gets me all Moodle users
function getallUsers(){
global $DB;
$users= $DB->get_records('user');
foreach($users as $user){
$allusers= $user->username."<br/>";
return $allusers;
}
}
Test values:
$year='2013';
$period='1';
$typeperiod='s';
$course='8145';
I need to compare their usernames with the values inside Identificador. Only the matchable ( on Moodle) will be enrolled,in bulk, on Moodle course page, without any sort of form.
I've tried to build the idea, but not sure if i'm heading on the right track.
$url=buildURL($year,$period,$typeperiod,$course);
$content_b=doRequest_with_FileGetContents($url);
$results = array();
$allUsers= array();
$allUsers= getallUsers(); //getting all users on Moodle
$dataClip= array();
$dataClip= processXML($content_b); //getting all identificadores from xml file ?
$courseid= required_param('id', PARAM_INT);
$context= get_context_instance(CONTEXT_COURSE, $courseid);//Getting students who are already enrolled
$students= get_role_users(5,$context);
// comparing usernames(identificador values) between Clip and Moodle
if(is_array($dataClip)){ //eliminates warnings of Invalid Argument in foreach
foreach($dataClip as $newdata){
$duplicate=false;
if(is_array($allUsers)){
foreach($allUsers as $dataMoodle){
// if there is a match
if($newdata===$dataMoodle){
// if student not enrolled yet on moodle course page.
if(!$students){
$duplicate=false;
$temp_object= clone $dataMoodle;
$results= $temp_object;
/*
* some code from user_bulk.php
*/
foreach($results as $userid) {
if ($userid == -1) {
continue;
}
if (!isset($SESSION->bulk_users[$userid])) {
$SESSION->bulk_users[$userid] = $userid;
}
}
}
// if there is a match and student already enrolled on moodle course page
$duplicate=true;
continue;
}
//no match. student not on moodle
$duplicate= false;
continue;
}
}
}
}
//after processing redirects back to course page
$urltogo = new moodle_url('/course/view.php', array('id'=>$courseid));
redirect($urltogo);
And this doesn't work. I have developer mode On and no errors/warnings. And no enrolled students neither.
Hey guys !
Well I was trying out codeigniter but it seems to me that I have made some kind of mess while trying to retrieve and display the data from the tables
here is the code snippet.
I want to retrieve all the articles stored in my article table along with that I need to pull out all the tags associated with each article from the relationship table and the tag table called articleTagRelation and tags respectively
Table structure :
Article table : articleID, articleContent, date
Tags table : tagID, tagName
articleTagRelation : aricleID,tagID {Combination of both is my primary key}
CI model :
article_model.php
public function getAllTags($postId){
$this->db->select('articleTagRelation.tagId as tagId, articleTagRelation.postId as postId, article.tagName as tagName,');
$this->db->from('articleTagRelation');
$this->db->join('Tags','Tags.tagId = articleTagRelation.tagId');
$this->db->where('ArticleTagRelation.articleId',$postId);
$qTag = $this->db->get();
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
return $tag;
}
}
}
public function getAllArticles(){
$this->db->select('*');
$this->db->from('Article');
$this->db->order_by('date','desc');
$query=$this->db->get();
if($query->num_rows()>0){
foreach ($query->result() as $row) {
$data['row'] = $row;
$data['articletags'] = $this->getAllTags($row->articleId); // I'm trying to get get a array of all the associate tags.
$post=array($data['row'],$data['articletags']);
}
}else{
echo 'nothing found !';
}
return $post;
}
my controller file
article.php
I'm calling this function in the index function
$data['rows'] = $this->blog_model->getAllArticles();
and then loading the view by passing the data array
now the part where things get messy
in my view
echo $r->articleId // works fine
echo $r->articletags->tagId //gives me a error message
Can any one help me out in printing those tagIds
First you don't need the foreach at all to get the tag information, it comes back from a query_result.
like this...
if($qTag->num_rows() > 0){
return $qTag->result();
}
else {
return array(); //return empty array if no tags
}
Then to build your article, do this with getAllArticles()
public function getAllArticles(){
// removed uneccessary select and from
// the below accomplishes the same thing
$this->db->order_by('date','desc');
$query = $this->db->get('Article');
if ( $query->num_rows() > 0 ) {
// store the result in a variable you will end up returning
$articles = $query->result();
// make sure you foreach by reference so that changes you make
// to the interated $article will be made to the actual article
// result
foreach ($articles as &$article) {
// create a new property of your article "tags" and save an
// array of tags in it
$article->tags = $this->getAllTags( $article->articleId );
}
} else {
echo 'nothing found !';
}
return $articles;
}
The last thing to note is that when you now reference $r->tags that is an array, so you can foreach it to process all tags, OR reference an index like $r->tags[3]->tagId
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
$tags[] = $tag; //this create the array with the result
}
return $tags;
}
"$r->articletags->tagId" only works if you return results as an object, use "$r->articletags['tagId']" instead.