Display Excerpts of Posts in Wordpress Blog - wordpress
I have been searching for the answer to my problem and I continually come up with replacing
<?php the_content(); ?>
with
<?php the_excerpt(); ?>
in the index.php file. However, the theme we are using does not contain this line. Anyone have any insight? Here is the code in our index.php file:
<?php $t =& peTheme(); ?>
<?php $content =& $t->content; ?>
<?php $meta =& $content->meta(); ?>
<?php get_header(); ?>
<section class="section-blog section-index" id="<?php $content->slug(); ?>">
<div class="row">
<div class="large-12 columns text-center">
</div>
</div>
<div class="row blog-main">
<div class="large-9 columns blog-left">
<?php $t->content->loop(); ?>
</div>
<?php get_sidebar(); ?>
</div>
</section>
<?php get_footer(); ?>
Source of PeThemeContent.php:
<?php
class PeThemeContent {
protected $master;
protected $loops = array();
protected $current = false;
protected $blogLoop = false;
protected $cols = 0;
public function __construct(&$master) {
$this->master = &$master;
add_filter("pe_post_thumbnail",array(&$this,"post_thumbnail_filter"));
add_filter("wp_tag_cloud",array(&$this,"wp_tag_cloud_filter"));
add_filter("widget_tag_cloud_args",array(&$this,"widget_tag_cloud_args_filter"));
add_filter("previous_post_link",array(&$this,"strip_rel_filter"));
add_filter("next_post_link",array(&$this,"strip_rel_filter"));
add_filter("the_category",array(&$this,"strip_rel_filter"));
add_filter("excerpt_more",array(&$this,"excerpt_more_filter"));
add_filter("the_content_more_link",array(&$this,"the_content_more_link_filter"));
add_filter("edit_post_link",array(&$this,"edit_post_link_filter"));
}
public function instantiate() {
}
public function loop($name = "") {
$view = new PeThemeViewBlog;
$conf = (object) array("settings" => (object) array("layout" => $name));
$conf->settings->pager = "yes";
$conf->settings->media = "yes";
$view->output($conf);
}
public function have_posts() {
if ($this->current) {
//print_r($this->current);
$res = $this->current->have_posts();
} else {
$res = have_posts();
}
return $res;
}
public function idx() {
return $this->wpq->current_post;
}
public function last() {
return $this->wpq->post_count-1;
}
public function count() {
return $this->wpq->post_count;
}
public function is_single() {
return $this->current ? false : is_single();
}
public function the_post() {
if ($this->current) {
$res = $this->current->the_post();
$GLOBALS["more"] = false;
} else {
$res = the_post();
}
return $res;
}
public function beginRow($markup) {
$cols = $this->cols;
$idx = $this->wpq->current_post;
if ($cols > 0 && ($idx % $cols) == 0) {
echo $markup;
}
}
public function endRow($markup = "</div>") {
$cols = $this->cols;
$idx = $this->wpq->current_post;
$last = $this->wpq->post_count-1;
if ($cols > 0 && (($idx == $last) || ($idx % $cols) == ($cols-1))) {
echo $markup;
}
}
public function looping($cols = 0) {
if ($this->have_posts()) {
$this->cols = $cols;
$this->the_post();
return true;
}
return false;
}
public function &wpq() {
global $wp_query;
return $wp_query;
}
public function &__get($what) {
switch ($what) {
case "wpq":
if ($this->current) {
return $this->current;
}
return $this->wpq();
case "qv":
return $this->wpq()->query_vars;
case "page":
$which = (is_front_page() && !is_home()) ? "page" : "paged";
$page = isset($this->qv[$which]) ? intval($this->qv[$which]) : 0;
return $page;
}
}
public function title() {
the_title();
}
public function titleAttribute() {
the_title_attribute();
}
public function getLink() {
$link = get_permalink();
global $post;
if (isset($post) && $post->post_type === "attachment") {
$link = $this->get_origImage();
}
return $link;
}
public function link() {
echo $this->get_link();
}
public function twitterShareLink() {
$link = "http://twitter.com/home?status=";
$link .= urlencode(get_the_title()." - ");
$link .= get_permalink();
echo esc_attr($link);
}
public function facebookShareLink() {
$link = "http://www.facebook.com/sharer/sharer.php?u=";
$link .= get_permalink();
echo esc_attr($link);
}
public function filter($tax,$sep = "",$aclass="label",$template = '%s') {
if (is_array($tax) && isset($tax[1]) && is_a($tax[1],"PeThemeDataLoop")) {
$loop = $tax[1]->main->loop;
$ids = array();
$n = count($loop);
for($i=0;$i<$n;$i++) {
$ids[] = $loop[$i]->id;
}
$terms = wp_get_object_terms($ids,$tax[0]);
} else if ($this->have_posts()) {
$ftax = in_array($tax,array('post_tag','category')) ? strtr($tax,array('post_tag'=>'tag','category' => 'category_name')) : $tax;
if (!empty($this->wpq->query[$ftax])) {
$slugs = explode(",",$this->wpq->query[$ftax]);
$terms = array();
if (!empty($slugs)) {
foreach ($slugs as $slug) {
$term = get_term_by('slug',$slug,$tax);
if (!empty($term) && !empty($term->term_id)) {
$terms[] = $term;
}
}
}
} else {
$posts =& $this->wpq->posts;
$ids = array();
$n = count($posts);
for($i=0;$i<$n;$i++) {
$ids[] = $posts[$i]->ID;
}
$terms = wp_get_object_terms($ids,$tax);
}
} else {
$terms = array();
}
$seen = array();
// to get all terms
//$terms = get_terms($tax);
$output = "";
$buffer = "";
if (is_array($terms) && count($terms) > 0) {
$buffer = apply_filters("pe_theme_filter_item",sprintf('<a class="%s active" data-category="" href="#">%s</a>%s',$aclass,__("All",'Pixelentity Theme/Plugin'),"$sep\n"),$aclass,"",__("All",'Pixelentity Theme/Plugin'));
$output = sprintf($template,$buffer);
foreach ($terms as $term) {
$id = $term->term_id;
if (isset($seen[$id])) continue;
$seen[$id] = true;
$buffer = apply_filters("pe_theme_filter_item",sprintf('<a class="%s" data-category="%s" href="#">%s</a>%s',$aclass,$term->slug,$term->name,"$sep\n"),$aclass,$term->slug,$term->name);
$output .= sprintf($template,$buffer);
}
print $output;
}
}
public function filterClasses($tax,$id = null) {
if (empty($tax)) return;
if (empty($id)) {
global $post;
$id = $post->ID;
}
$classes = wp_get_post_terms($id,$tax,array("fields" => "slugs"));
if (is_array($classes) && ($count = count($classes)) > 0) {
while($count--) {
$classes[$count] = "filter-".$classes[$count];
}
echo join(" ",$classes);
}
}
public function thumb($useFilters = true) {
global $post;
if (has_post_thumbnail()) {
$thumb = get_the_post_thumbnail($post->ID,"thumbnail");
if ($useFilters && has_filter("pe_post_thumbnail")) {
echo apply_filters("pe_post_thumbnail",$thumb);
} else {
echo $thumb;
}
}
}
public function post_thumbnail_filter($data) {
return $data;
}
public function hasFeatImage() {
global $post;
return #has_post_thumbnail($post->ID);
}
public function get_origImage($id = null) {
return wp_get_attachment_url(get_post_thumbnail_id($id));
}
public function resizedImg($w,$h,$custom = null) {
$url = empty($custom) ? wp_get_attachment_url(get_post_thumbnail_id()) : $custom;
return $this->master->image->resizedImg($url,$w,$h);
}
public function img($w,$h = null,$custom = null) {
$img = $this->resizedImg($w,$h,$custom);
echo apply_filters("pe_theme_content_img",$img ? $img : "",$w,$h);
}
public function get_thumbImage($thumb) {
if (#has_post_thumbnail()) {
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id(),$thumb);
return $thumb[0];
}
return "";
}
public function origImage() {
echo $this->get_origImage();
}
public function excerpt() {
the_excerpt();
}
public function content($text = null) {
global $post;
if (isset($post) && $post->post_type === "attachment") {
echo apply_filters("wpautop",$post->post_excerpt);
} else {
the_content($text);
}
}
public function builder() {
if (post_password_required() || !PE_THEME_PLUGIN) {
$this->content();
} else {
$meta =& $this->meta();
if (empty($meta->builder)) return;
global $post;
$view = new PeThemeViewLayout();
$conf = (object)
array(
"id" => $post->ID,
"settings" => $meta->builder
);
$view->output($conf);
}
}
public function hasMedia() {
$format = $this->format();
$meta =& $this->meta();
$ret = false;
switch ($format) {
case "gallery":
$gallery = empty($meta->gallery) ? false : $meta->gallery;
$ret = !empty($gallery->id) && $gallery->id > 0;
break;
case "video":
$video = empty($meta->video) ? false : $meta->video;
$ret = !empty($video->id) && $video->id > 0;
break;
default:
$ret = $this->hasFeatImage();
}
return $ret;
}
public function slider($w,$h) {
if ($this->format() != "gallery") return;
$meta =& $this->meta();
$gallery = empty($meta->gallery) ? false : $meta->gallery;
if (empty($gallery->id)) return;
$view =& $this->master->view;
$conf = $view->create("SliderVolo","gallery",array("id" =>$gallery->id),$w,$h);
$view->resize($conf);
}
public function media() {
$format = $this->format();
$meta =& $this->meta();
switch ($format) {
case "gallery":
$gallery = empty($meta->gallery) ? false : $meta->gallery;
if (!empty($gallery->id)) {
$conf =
$this->master->view->create(
$gallery->type,
"gallery",
array("id" => $gallery->id),
$gallery->width,
$gallery->height
);
// use gallery caption
$conf->caption = (object) array("title" => "ititle","description" => "caption");
//$conf->caption->title = "ititle";
//$conf->caption->description = "caption";
$this->master->view->resize($conf);
}
break;
case "video":
$this->master->video->output();
break;
default:
$format = $this->hasFeatImage() ? "image" : false;
}
return $format;
}
public function current($add = 0) {
$page = $this->page;
if ($page > 1) {
$add += $this->qv["posts_per_page"]*($page-1);
}
echo $this->wpq->current_post + $add;
}
public function terms($tax,$sep = ",") {
global $post;
return join($sep,wp_get_post_terms($post->ID,$tax,array("fields" => "names")));
}
public function &getPostsQueryArgs($type,$count,$tax = null,$custom = null,$paged = false) {
$args = array(
"post_type"=>"$type",
"posts_per_page"=>$count
);
if ($tax) {
$custom[$tax] = $this->terms($tax);
}
if (is_array($custom)) {
$args = array_merge($args,$custom);
}
if ($paged) {
$page = $this->page;
$page = $page ? $page - 1 : 0;
$args["offset"] = $count*$page;
} else {
// if pagination is not needed, avoid counting rows to boost performances
$args['no_found_rows'] = true;
}
if ($args["post_type"] === "attachment") {
$args["post_status"] = "inherit";
}
return $args;
}
public function getPostsLoop($type,$count,$tax = null,$custom = null,$paged = false) {
$data = new StdClass();
$args =& $this->getPostsQueryArgs($type,$count,$tax,$custom,$paged);
$wpq = new WP_Query();
$data->loop = $wpq->query($args);
$loop =& $this->master->data->create($data,true);
if ($paged) {
$loop->pages = $wpq->max_num_pages;
}
return $loop;
}
public function customLoop($type,$count = 10,$tax = null,$custom = null,$paged = false) {
$args =& $this->getPostsQueryArgs($type,$count,$tax,$custom,$paged);
if ($this->current) {
$this->loops[] = $this->current;
}
$this->master->data->postSave();
$this->current = new WP_Query($args);
return $this->current->post_count > 0;
}
public function related($type,$tax,$count) {
//$settings = new StdClass();
//$settings->post_type = "project";
if ($loop = $this->customLoop($type,$count,$tax)) {
get_template_part("related",$type);
$this->resetLoop();
}
}
public function resetLoop() {
$this->master->data->postReset();
$this->current = (count($this->loops) >0) ? array_pop($this->loops) : false;
}
public function blog($settings,$showpager = true) {
global $post;
$exclude = false;
// prevents nested blogs
if ($this->blogLoop) return;
$this->blogLoop = true;
// prevents loops
if (isset($post) && $post) {
$exclude = $post->ID;
}
if (is_string($settings) && !empty($settings)) {
$id = $settings;
$post = get_post($id);
if (!$post) return;
$meta = $this->master->meta->get($id,$post->post_type);
if (empty($meta->blog)) return true;
$settings = $meta->blog;
}
$settings = (object) shortcode_atts(
array(
"layout" => "",
"count" => get_option("posts_per_page"),
"media" => "yes",
"pager" => "yes",
"sticky" => "yes",
"category" => "",
"tag" => "",
"format" => ""
),
(array) $settings
);
// prevents loops
if ($exclude) {
$custom = array("post__not_in" => array($exclude));
}
$custom["ignore_sticky_posts"] = ($settings->sticky === "no") ? 1 : 0;
if ($settings->category) {
$custom["category_name"] = $settings->category;
}
if ($settings->tag) {
$custom["tag"] = $settings->tag;
}
if ($settings->format) {
$tax_query = array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array("post-format-{$settings->format}")
)
);
$custom["tax_query"] = $tax_query;
}
$media = $settings->media === "yes";
$this->customLoop("post",$settings->count,null,$custom,$settings->pager === "yes");
$compact = compact("media");
$this->master->template->get_part($compact,"loop",$this->have_posts() ? $settings->layout : "empty");
if ($showpager && $settings->pager === "yes") {
$this->pager();
}
$this->resetLoop();
$this->blogLoop = false;
}
public function getPagerLoop($max = 5,$pages = false) {
$pages = $pages ? $pages : $this->wpq->max_num_pages;
if ($pages <= 1) return false;
for ($p = 0;$p<$pages;$p++) {
$links[] = get_pagenum_link($p+1);
}
return $this->master->data->createPager($this->page,$links,$max);
}
public function pager($class = "span12",$pages = false) {
$loop = $this->getPagerLoop(5,$pages);
if ($loop) $loop->main->class = $class;
$this->master->template->paginate_links($loop);
}
public function comments() {
comments_number('0','1','%');
}
public function body_class($class = "") {
echo 'class="' . apply_filters("pe_theme_body_class",join( ' ', get_body_class( $class ) )) . '"';
}
public function total() {
echo $this->wpq->found_posts;
}
public function hasNextPage() {
$max = $this->wpq->max_num_pages;
return ($max > 1 && $this->page < $max);
}
public function hasPrevPage() {
$max = $this->wpq->max_num_pages;
return ($max > 1 && $this->page > 1);
}
public function tagCloud($number,$orderby="name") {
wp_tag_cloud(array("number"=>$number,"orderby"=>$orderby,"order"=>$orderby == "count" ? "DESC" : "ASC"));
}
public function tags($sep = ", ",$tax = false) {
if ($tax) {
echo get_the_term_list(null, $tax, "", $sep, "");
} else {
the_tags("",$sep,"");
}
}
public function category($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_category(", ");
}
public function date($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_time(get_option('date_format'));
}
public function author($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_author();
}
public function format($is_format = null) {
global $post;
$format = get_post_format($post->ID);
return empty($is_format) ? $format : $format === $is_format;
}
public function pageTemplate($post_id = null) {
if (function_exists("get_page_template_slug")) return get_page_template_slug($post_id);
$post = get_post( $post_id );
if ( 'page' != $post->post_type )
return false;
$template = get_post_meta( $post->ID, '_wp_page_template', true );
if ( ! $template || 'default' == $template )
return '';
}
public function slug() {
global $post;
echo $post->post_name;
}
public function type() {
global $post;
return $post->post_type;
}
public function classes($add="") {
$c = join(" ",get_post_class());
$c = $add ? "$c $add" : "$c";
printf('class="%s"',$c);
}
public function isVideo() {
return get_post_format() === "video";
}
public function includeLoopPart($prefix="looped") {
global $post;
$type = $post->post_type;
get_template_part("$prefix-$type",$this->format());
}
public function getBlogLink() {
$pfp = get_option("page_for_posts");
$pfp = $pfp ? get_page_link($pfp) : "";
return get_option('show_on_front') == 'page' ? $pfp : home_url();
}
public function wp_tag_cloud_filter($data) {
if (is_tag()) {
global $wp_query;
$currentTagID = $wp_query->get_queried_object()->term_id;
$data = str_replace("tag-link-$currentTagID","tag-link-$currentTagID current-tag",$data);
}
return preg_replace('/style=.[^"|\']+./i','',$data);
}
public function widget_tag_cloud_args_filter($args) {
$options =& $this->master->options;
$orderby = $options->get("tagCloudOrder");
$args = array_merge($args,array("number"=>$options->get("tagCloudCount"),"orderby"=>$orderby,"order"=>$orderby == "count" ? "DESC" : "ASC"));
return $args;
}
public function &meta($postID = FALSE) {
global $post;
//print_r($post);
return $this->master->meta->get($postID ? $postID : ($post ? $post->ID : NULL),$post ? $post->post_type : "post");
}
public function strip_rel_filter($content) {
return preg_replace('/rel="/','data-rel="',$content);
}
public function excerpt_more_filter($more) {
return "";
}
public function the_content_more_link_filter($link) {
//$link = sprintf(' %s',get_permalink(),$GLOBALS["post"]->ID,__("more",'Pixelentity Theme/Plugin'));
$link = sprintf(' %s',get_permalink(),__("more",'Pixelentity Theme/Plugin'));
return $link;
}
public function edit_post_link_filter($link) {
return str_replace("post-edit-link","label",$link);
}
public function getSocialLinks($links,$position = "top") {
$html = "";
if (is_array($links)) {
foreach ($links as $link) {
if (empty($link)) continue;
list($icon,$tooltip) = explode("|",$link["icon"]);
$html .= apply_filters("pe_theme_content_get_social_link",sprintf('<i class="%s"></i>',$link["url"],$position,$tooltip,$icon),$link["url"],$tooltip,$icon);
}
}
return $html;
}
public function socialLinks($links,$position = "top") {
$html = apply_filters("pe_theme_social_links",$this->getSocialLinks($links,$position),$position);
echo $html ? $html : "";
}
public function getPagesByTemplate($template) {
$args = array();
if ($template) {
$args =
array(
'meta_key' => '_wp_page_template',
'meta_value' => "page-$template.php"
);
}
$pages = get_pages($args);
return $pages;
}
public function getPagesLinkByTemplate($template) {
$pages = $this->getPagesByTemplate($template);
if (!is_array($pages)) return false;
$links = false;
foreach ($pages as $page) {
$links[] = get_page_link($page->ID);
}
return $links;
}
public function getPagesOptionsByTemplate($template) {
$pages = $this->getPagesByTemplate($template);
if (!is_array($pages)) return false;
$links = false;
foreach ($pages as $page) {
$links[$page->post_title] = $page->ID;
}
return $links;
}
public function getPageLinkByTemplate($template) {
$pages = $this->getPagesLinkByTemplate($template);
return $pages ? $pages[0] : "";
}
public function adjPost($previous = false) {
$post = get_adjacent_post(false,"", $previous);
$ret = "";
if ($post) {
$ret = new StdClass;
$ret->title = get_the_title($post);
$ret->link = get_permalink($post);
$ret->date = get_the_time(get_option('date_format'), $post);
}
return $ret;
}
public function breadcrumbs($sep = ' / ') {
$template = '<a class="pe-breadcrumbs-%s" href="%s">%s</a>';
$links[] = sprintf($template,'home',home_url(),__('Home','Pixelentity Theme/Plugin'));
if (is_home()) {
$links[] = sprintf($template,'blog','#',__('Blog','Pixelentity Theme/Plugin'));
} elseif (is_category()) {
$links[] = substr(get_category_parents(get_query_var('cat'),true,$sep), 0, -strlen($sep));
} elseif (is_tag() || is_tax()) {
$term = get_queried_object();
if (!empty($term->term_id)) {
$links[] = sprintf($template,'tax',get_tag_link($term->term_id),single_term_title("",false));
}
} elseif (is_archive()) {
if ( is_day() ) {
$date = get_the_date();
} elseif ( is_month() ) {
$date = get_the_date('F Y');
} elseif ( is_year() ) {
$date = get_the_date('Y');
} else {
$date = __("Archives",'Pixelentity Theme/Plugin');
}
$links[] = sprintf($template,'archive','#',$date);
} elseif (is_page()) {
global $post;
if (!empty($post->ID)) {
$parents = get_post_ancestors($post->ID);
if (!empty($parents) && is_array($parents)) {
$parents = array_reverse($parents);
$parents[] = $post->ID;
$home = trailingslashit(home_url());
foreach ($parents as $id) {
$link = get_permalink($id);
if ($link == $home) continue;
$links[] = sprintf($template,'page',$link,get_the_title($id));
}
}
}
} elseif (is_single()) {
global $post;
if (!empty($post->ID)) {
$taxs = get_object_taxonomies($post,"names");
if (!empty($taxs) && is_array($taxs)) {
while ($tax = array_shift($taxs)) {
if ($tax != "post_format") break;
}
if ($tax) {
$terms = get_the_terms($post->ID,$tax);
if (is_array($terms)) {
reset($terms);
$term = key($terms);
$parents = get_ancestors($terms[$term]->term_id,$tax);
$parents = is_array($parents) ? array_reverse($parents) : array();
$parents[] = $terms[$term]->term_id;
foreach ($parents as $id) {
$term = get_term($id,$tax);
$links[] = sprintf($template,'tax',get_term_link($term),$term->name);
}
}
}
}
$links[] = sprintf($template,'single',get_permalink($post->ID),get_the_title($post->ID));
}
}
print join($links,$sep);
}
public function adjPostLink($previous = false) {
$post = get_adjacent_post(false,"", $previous);
return $post ? get_permalink($post) : "";
}
public function prevPostLink() {
return $this->adjPostLink(true);
}
public function nextPostLink() {
return $this->adjPostLink(false);
}
public function linkPages() {
wp_link_pages(array('before' => '<div class="page-links">' . __('Pages:','Pixelentity Theme/Plugin'), 'after' => '</div>'));
}
}
?>
Related
Symfony Doctrine: One to Many relationship is deleting parent entity
I have parent and child entity. After all child entities are deleted, symfony delete my parent entity too. I don't like such behavior, parent entity must exist whenever there are some children or not. Here is my code for parent: /** * #OneToMany(targetEntity="Gallery", mappedBy="promotion", cascade={"persist", "remove"}) */ private $galleries; public function __construct() { $this->galleries = new ArrayCollection(); } public function getGalleries() { return $this->galleries; } public function addGallery($gallery) { $gallery->setPromotion($this); $this->galleries[] = $gallery; return $this; } public function removeGallery($gallery) { $gallery->setPromotion(null); $this->galleries->removeElement($gallery); } And here for child: /** * #ManyToOne(targetEntity="Promotion", inversedBy="galleries") */ private $promotion; I don't know what to do, I have already spend hours on this. It is handled by easy admin bundle, so it won't help you: namespace AppBundle\Controller; use JavierEguiluz\Bundle\EasyAdminBundle\Event\EasyAdminEvents; use Symfony\Component\Security\Acl\Exception\Exception; use AppBundle\Entity\Promotion; use Symfony\Component\HttpFoundation\JsonResponse; class PromotionController extends PageController { protected $folder = 'promotions'; protected $htmlFileName = 'default-template.html'; protected function rearangeAction() { $ids = json_decode($this->request->get('ids')); $order = 1; foreach($ids as $id) { $this->em->createQuery('UPDATE AppBundle:Promotion p SET p.order = :order WHERE p.id = :id') ->setParameter('order', $order++) ->setParameter('id', $id) ->execute(); } return $this->redirectToRoute('easyadmin', $this->prepareRouteParams()); } protected function checkFolderAction() { $row = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.language = :language AND p.subfolder = :subfolder') ->setParameter('language', $this->language) ->setParameter('subfolder', $this->request->get('subfolder')) ->getOneOrNullResult(); if($row) { return new JsonResponse(array('duplicity' => 1)); } else { return new JsonResponse(array('duplicity' => 0)); } } protected function deleteFiles($databaseSubFolders) { $mainFolder = $this->baseDir.'/'.$this->folder.'/'.$this->language; $databaseSubFolders[] = '..'; $databaseSubFolders[] = '.'; $subFolders = array_diff(scandir($mainFolder), $databaseSubFolders); foreach($subFolders as $subFolder) { $this->deleteFolder($mainFolder.'/'.$subFolder); } } protected function exportAction() { $query = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.language = :language') ->setParameter('language', $this->language); $subFolders = array(); foreach($query->getArrayResult() as $key => $val) { $subFolders[] = $val['subfolder']; // pridanie novych a uprava starych $image = basename($val['headerImage']); $imageName = substr($image, 0 ,strpos($image,'.')); $all = '<div class="header"> <div class="row"> <h2> '.$val['headerTitle'].' </h2> <p> '.$val['headerTeaser'].' </p> </div> </div><img src="{{::promo.imgPath}}/'.$image.'" alt="'.$imageName.'">'; $all .= $this->changeMarkdownToHtml($val['html']); $all .= $this->changeMarkdownToHtml($val['terms']); file_put_contents($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$val['subfolder'].'/html/'.$val['filename'], $all); } // zmazanie starych zloziek $this->deleteFiles($subFolders); parent::exportAction(); return $this->redirectToRoute('easyadmin', $this->prepareRouteParams()); } private function actualImage($id, $i) { $row = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.id = :id') ->setParameter('id', $id) ->getOneOrNullResult(); return call_user_func_array(array($row,'getImage'.$i), array()); } protected function preDeleteEntity($id) { // mazanie obrazkov } protected function preSearchEntity($entity) { $entity['search']['dql_filter'] = "entity.language = '".$this->language."'"; return $entity; } protected function prePersistEntity($entity) { // ukladanie dalsich dat $entity->setLanguage($this->language); $entity->setFilename($this->htmlFileName); $row = $this->em->createQuery('SELECT MAX(p.order)+1 FROM AppBundle:Promotion p') ->getOneOrNullResult(); $entity->setOrder($row[1]); return $entity; } protected function postPersistEntity($entity) { if(!is_dir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder())) { mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder()); mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'header'); mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'html'); mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'img'); } // presun obrazkov $images = array(); foreach($entity->getGalleries()->getSnapshot() as $snapshot) { $image = $snapshot->getImage(); $from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($image); $to = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/img/'.$image; $this->copyFile($from, $to); $images[] = $image; } $getImage = $entity->getHeaderImage(); $from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($getImage); $to = $this->baseDir.'/'.$this->folder.'/'.$this->language.$getImage; $this->copyFile($from, $to); $entity->setHtml($this->replaceImages($entity->getHtml(), $images)); return $entity; } protected function preRemoveEntity($entity) { //if($_POST['_method'] != 'DELETE') { // var_dump($entity); // die(); //} return $entity; } protected function editAction() { $id = $this->request->query->get('id'); $this->dispatch(EasyAdminEvents::PRE_EDIT); $this->executeDynamicMethod('preEdit<EntityName>Entity', array($id)); $easyadmin = $this->request->attributes->get('easyadmin'); $entity = $easyadmin['item']; if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) { $newValue = 'true' === mb_strtolower($this->request->query->get('newValue')); $fieldsMetadata = $this->entity['list']['fields']; if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) { throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property)); } $this->updateEntityProperty($entity, $property, $newValue); return new Response((string) $newValue); } $fields = $this->entity['edit']['fields']; $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', array($entity, $fields)); $deleteForm = $this->createDeleteForm($this->entity['name'], $id); // kontrola pre presun $row = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.id = :id') ->setParameter('id', $id) ->getOneOrNullResult(); $previousSubfolder = $row->getSubfolder(); $editForm->handleRequest($this->request); if ($editForm->isSubmitted() && $editForm->isValid()) { $this->dispatch(EasyAdminEvents::PRE_UPDATE, array('entity' => $entity)); $entity = $this->executeDynamicMethod('preUpdate2<EntityName>Entity', array($entity,$previousSubfolder)); $this->em->flush(); $this->dispatch(EasyAdminEvents::POST_UPDATE, array('entity' => $entity)); $entity = $this->executeDynamicMethod('postUpdate2<EntityName>Entity', array($entity,$previousSubfolder)); $refererUrl = $this->request->query->get('referer', ''); return !empty($refererUrl) ? $this->redirect(urldecode($refererUrl)) : $this->redirect($this->generateUrl('easyadmin', array('action' => 'list', 'entity' => $this->entity['name']))); } $this->dispatch(EasyAdminEvents::POST_EDIT); $entity = $this->executeDynamicMethod('postEdit<EntityName>Entity', array($entity)); return $this->render($this->entity['templates']['edit'], array( 'form' => $editForm->createView(), 'entity_fields' => $fields, 'entity' => $entity, 'delete_form' => $deleteForm->createView(), )); } protected function preUpdate2Entity($entity, $previousSubfolder) { // if($_POST['delete_form']['_easyadmin_delete_flag'] == 1) { // $this->em->createQuery('DELETE FROM AppBundle:Gallery g WHERE g.promotion = :id') // ->setParameter('id', $id) // ->execute(); // } $images = array(); foreach($entity->getGalleries()->getSnapshot() as $snapshot) { $image = $snapshot->getImage(); $images[] = $image; } $entity->setHtml($this->replaceImages($entity->getHtml(), $images)); return $entity; } protected function postUpdate2Entity($entity, $previousSubfolder) { if(!is_dir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder())) { mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder()); mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'header'); mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'html'); mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'img'); } // presun obrazkov $images = array(); foreach($entity->getGalleries()->getSnapshot() as $snapshot) { $image = $snapshot->getImage(); $from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($image); $to = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/img/'.$image; if(!file_exists($from)) { $from = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$previousSubfolder.'/img/'.$image; } $this->copyFile($from, $to); $images[] = $image; } // zmazanie obrazkov $folderImages = array_diff(scandir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$previousSubfolder.'/img/'), array('..', '.')); foreach($folderImages as $folderImage) { if(!in_array($folderImage, $images)) { unlink($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$previousSubfolder.'/img/'.$folderImage); } } $getImage = $entity->getHeaderImage(); $from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($getImage); if(!file_exists($from)) { $from = $this->baseDir.'/'.$this->folder.'/'.$this->language.$getImage; } $to = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/header/'.basename($getImage); $this->copyFile($from, $to); return $entity; } protected function postEditEntity($entity) { // cesta pre obrazky $entity->setHeaderImage(null, '/uploads/'.$this->container->getParameter('repo.folder').'/'.$this->folder.'/'.$this->language.$entity->getHeaderImage()); return $entity; } protected function preListEntity($entity) { $entity['list']['dql_filter'] = "entity.language = '".$this->language."'"; return $entity; } protected function postListEntity($fields) { // cesta pre obrazky $fields['headerImage']['base_path'] = '/uploads/'.$this->container->getParameter('repo.folder').'/'.$this->folder.'/'.$this->language; return $fields; } protected function postSearchEntity($fields) { // cesta pre obrazky $fields['headerImage']['base_path'] = '/uploads/'.$this->container->getParameter('repo.folder').'/'.$this->folder.'/'.$this->language; return $fields; } }
Try to remove cascade annotation at all. The rest looks good.
Symfony 2 FOS user Cannot redirect to an empty URL
I'm trying to implement the register part of a project in Symfony with the Sonata Bundle but i get the exception "Cannot redirect to an empty URL". The error is generated in the controller file RegistrationFOSUser1Controller in the registerAction. public function registerAction() { $user = $this->container->get('security.context')->getToken()->getUser(); if ($user instanceof UserInterface) { $this->container->get('session')->getFlashBag()->set('sonata_user_error', 'sonata_user_already_authenticated'); $url = $this->container->get('router')->generate('booster_bici_homepage'); return new RedirectResponse($url); } $form = $this->container->get('sonata.user.registration.form'); $formHandler = $this->container->get('sonata.user.registration.form.handler'); $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled'); $process = $formHandler->process($confirmationEnabled); if ($process) { $user = $form->getData(); $authUser = false; if ($confirmationEnabled) { $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail()); $url = $this->container->get('router')->generate('fos_user_registration_check_email'); } else { $authUser = true; $route = $this->container->get('session')->get('sonata_basket_delivery_redirect'); if (null !== $route) { $this->container->get('session')->remove('sonata_basket_delivery_redirect'); $url = $this->container->get('router')->generate($route); } else { $url = $this->container->get('session')->get('sonata_user_redirect_url');//IT SEEMS THAT HERE IS RETURNED NULL } } $this->setFlash('fos_user_success', 'registration.flash.user_created'); $response = new RedirectResponse($url);// THIS IS THE LINE OF THE ERROR if ($authUser) { $this->authenticateUser($user, $response); } return $response; } $this->container->get('session')->set('sonata_user_redirect_url', $this->container->get('request')->headers->get('referer')); return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array( 'form' => $form->createView(), )); } The part where the error is generated is : if ($process) { $user = $form->getData(); $authUser = false; if ($confirmationEnabled) { $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail()); $url = $this->container->get('router')->generate('fos_user_registration_check_email'); } else { $authUser = true; $route = $this->container->get('session')->get('sonata_basket_delivery_redirect'); if (null !== $route) { $this->container->get('session')->remove('sonata_basket_delivery_redirect'); $url = $this->container->get('router')->generate($route); } else { $url = $this->container->get('session')->get('sonata_user_redirect_url'); //IT SEEMS THAT HERE IS RETURNED NULL } } $this->setFlash('fos_user_success', 'registration.flash.user_created'); $response = new RedirectResponse($url);// THIS IS THE LINE OF THE ERROR I can see that the problem is that $url is empty. I have traced the problem to the line: $url = $this->container->get('session')->get('sonata_user_redirect_url'); It seems that $this->container->get('session')->get('sonata_user_redirect_url') returns null but i don't know what to do in order to avoid that or what i'm doing wrong. Any ideas?
just change: $url = $this->container->get('session')->get('sonata_user_redirect_url'); with: $url = $this->generateUrl('sonata_user_profile_show');
Get multiple custom taxonomy and terms index using json-api
I use json-api plugin and I have three custom taxonomies. for example: car, phone, and book. I try to get all taxonomy index something like this http://example.com/api/taxonomy/get_taxonomy_index/?taxonomy=car,phone,book But it doesn't work for more than one taxonomy. Does Anyone know how to get all my custom taxonomy and terms index? Here is JSON_API_Taxonomy_Controller: class JSON_API_Taxonomy_Controller { public function get_taxonomy_index() { $terms = $this->get_terms(); return array( 'count' => count( $terms ), 'terms' => $terms ); } public function get_terms() { global $json_api; $taxonomy = $this->get_current_taxonomy(); if (!$taxonomy) { $json_api->error("Not found."); } $wp_terms = get_terms( $taxonomy ); $terms = array(); foreach ( $wp_terms as $wp_term ) { if ( $wp_term->term_id == 1 && $wp_term->slug == 'uncategorized' ) { continue; } $terms[] = new JSON_API_Term( $wp_term ); } return $terms; } protected function get_current_taxonomy() { global $json_api; $taxonomy = $json_api->query->get('taxonomy'); if ( $taxonomy ) { return $taxonomy; } else { $json_api->error("Include 'taxonomy' var in your request."); } return null; } } // Generic rewrite of JSON_API_Tag class to represent any term of any type of taxonomy in WP class JSON_API_Term { var $id; // Integer var $slug; // String var $title; // String var $description; // String function JSON_API_Term($term = null) { if ($term) { $this->import_wp_object($term); } } function import_wp_object($term) { $this->id = (int) $term->term_id; $this->slug = $term->slug; $this->title = $term->name; $this->description = $term->description; $this->post_count = (int) $term->count; } } So I want json object output: registered taxonomies as parent and terms as child.
Create my own entity generator on symfony using doctrine generator
I am building an entity generator in order to update my DB's structure and data according to a distant one (DB), via SOAP WS... I get the structure from an array, and am currently writing my entity classes by myself, with a file_put_content(). But as I advance, I can't help noticing that the Doctrine\ORM\Tools\EntityGenerator already does what I intend to do, way better I would ever be able to!! So i was wondering if there was a way to use this implemented generator from my controller? I mean, this is what Symfony is all about right? Using existing classes & bundles from anywhere in my code? :) Any idea someOne? Thx :)
You can use this code: use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Sensio\Bundle\GeneratorBundle\Generator\DoctrineEntityGenerator; use Sensio\Bundle\GeneratorBundle\Command\Validators; class MyController extends Controller { private $generator; public function generateEntityAction() { $format = "annotation"; //it can also be yml/php/xml $fields = "title:string(255) body:text"; $withRepository = false; //true/false $entity = Validators::validateEntityName("MyBundle:EntityName"); list($bundle, $entity) = $this->parseShortcutNotation($entity); $format = Validators::validateFormat($format); $fields = $this->parseFields($fields); $bundle = $this->get('service_container')->get('kernel')->getBundle($bundle); $generator = $this->getGenerator(); $generator->generate($bundle, $entity, $format, array_values($fields), $withRepository); } protected function createGenerator() { return new DoctrineEntityGenerator($this->get('service_container')->get('filesystem'), $this->get('service_container')->get('doctrine')); } protected function getSkeletonDirs(BundleInterface $bundle = null) { $skeletonDirs = array(); if (isset($bundle) && is_dir($dir = $bundle->getPath() . '/Resources/SensioGeneratorBundle/skeleton')) { $skeletonDirs[] = $dir; } if (is_dir($dir = $this->get('service_container')->get('kernel')->getRootdir() . '/Resources/SensioGeneratorBundle/skeleton')) { $skeletonDirs[] = $dir; } $skeletonDirs[] = __DIR__ . '/../Resources/skeleton'; $skeletonDirs[] = __DIR__ . '/../Resources'; return $skeletonDirs; } protected function getGenerator(BundleInterface $bundle = null) { if (null === $this->generator) { $this->generator = $this->createGenerator(); $this->generator->setSkeletonDirs($this->getSkeletonDirs($bundle)); } return $this->generator; } protected function parseShortcutNotation($shortcut) { $entity = str_replace('/', '\\', $shortcut); if (false === $pos = strpos($entity, ':')) { throw new \InvalidArgumentException(sprintf('The entity name must contain a : ("%s" given, expecting something like AcmeBlogBundle:Blog/Post)', $entity)); } return array(substr($entity, 0, $pos), substr($entity, $pos + 1)); } private function parseFields($input) { if (is_array($input)) { return $input; } $fields = array(); foreach (explode(' ', $input) as $value) { $elements = explode(':', $value); $name = $elements[0]; if (strlen($name)) { $type = isset($elements[1]) ? $elements[1] : 'string'; preg_match_all('/(.*)\((.*)\)/', $type, $matches); $type = isset($matches[1][0]) ? $matches[1][0] : $type; $length = isset($matches[2][0]) ? $matches[2][0] : null; $fields[$name] = array('fieldName' => $name, 'type' => $type, 'length' => $length); } } return $fields; } } Mostly, it comes from Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineEntityCommand and Sensio\Bundle\GeneratorBundle\Command\GeneratorCommand
Mock Object variable in PHPUnit
I want to create a test for the following function in Cakephp2.0 with PHPUnit: public function matching($check, $field) { $return = true; foreach ($check as $c) { if ($c != $this->data['User'][$field]) { $return = false; } } return $return; } How do I set the value of: $this->data['User'][$field] My test function is: public function testMatching() { $this->data['User']['password'] = 'testpass'; $check = array('testpass'); $result = $this->User->matching($check, 'password'); $this->assertEquals(true, $result); } Thanks.