Finds and displays a Post entity.

@Route("/{id}/preview", name="manage_post_preview")
@Template("VeonikBlogBundle:Home:index.html.twig")
181439
public function previewAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VeonikBlogBundle:Post')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Post entity.');
        }

        $request->attributes->set('slug', $entity->getSlug());

        return array(
            'entities'      => array($entity),
        );
    }
461078
protected static function is_previewing() {
		global $wp_query;
		if ( isset($_GET['preview']) && isset($_GET['preview_nonce']) && wp_verify_nonce($_GET['preview_nonce'], 'post_preview_'.$wp_query->queried_object_id) ) {
			return true;
		}
	}
614217
def post(self, request, *args, **kwargs):
        
        self.init_attachment_cache()

        # Stores a boolean indicating if we are considering a preview
        self.preview = 'preview' in self.request.POST

        # Initializes the forms
        post_form_class = self.get_post_form_class()
        post_form = self.get_post_form(post_form_class)
        attachment_formset_class = self.get_attachment_formset_class()
        attachment_formset = self.get_attachment_formset(attachment_formset_class)
        poll_option_formset_class = self.get_poll_option_formset_class()
        poll_option_formset = self.get_poll_option_formset(poll_option_formset_class)

        post_form_valid = post_form.is_valid()
        attachment_formset_valid = (
            attachment_formset.is_valid() if attachment_formset else None
        )
        poll_option_formset_valid = (
            poll_option_formset.is_valid()
            if poll_option_formset and len(post_form.cleaned_data['poll_question']) else None
        )

        self.attachment_preview = self.preview if attachment_formset_valid else None
        self.poll_preview = self.preview if poll_option_formset_valid else None

        poll_options_validated = poll_option_formset_valid is not None
        if (
            post_form_valid and
            attachment_formset_valid is not False and
            poll_option_formset_valid is not False
        ):
            return self.form_valid(
                post_form, attachment_formset, poll_option_formset,
                poll_options_validated=poll_options_validated,
            )
        else:
            return self.form_invalid(
                post_form, attachment_formset, poll_option_formset,
                poll_options_validated=poll_options_validated,
            )
119540
public function composePreviewAction(Request $request = null)
    {
        $this->admin->checkAccess('composePreview');

        $blockId = $request->get('block_id');

        /** @var BaseBlock $block */
        $block = $this->admin->getObject($blockId);
        if (!$block) {
            throw new PageNotFoundException(sprintf('Unable to find block with id %d', $blockId));
        }

        $container = $block->getParent();
        if (!$container) {
            throw new PageNotFoundException('No parent found, unable to preview an orphan block');
        }

        $blockServices = $this->get('sonata.block.manager')->getServicesByContext('sonata_page_bundle', false);

        return $this->render('@SonataPage/BlockAdmin/compose_preview.html.twig', [
            'container' => $container,
            'child' => $block,
            'blockServices' => $blockServices,
        ]);
    }
226906
public function preview()
    {
        // Enable theme for preview (may be needed for Shortcodes)
        Config::nest();
        Config::modify()->set(SSViewer::class, 'theme_enabled', true);

        $content = $this->customise([
            'Body' => $this->record->getEmailBodyContent(),
            'HideFormData' => (bool) $this->record->HideFormData,
            'Fields' => $this->getPreviewFieldData()
        ])->renderWith($this->record->EmailTemplate);

        Config::unnest();

        return $content;
    }
360971
public function preview(Request $request, $contenttypeslug)
    {
        if (!$request->isMethod('POST')) {
            throw new MethodNotAllowedHttpException(['POST'], 'This route only accepts POST requests.');
        }

        $contenttype = $this->getContentType($contenttypeslug);
        $formValues = $request->request->all();

        $storage = $this->storage();
        if ($storage instanceof EntityManager) {
            /** @var EntityManager $storage */
            /** @var Content $content */
            $content = $storage->create($contenttypeslug, $formValues);

            /** @var Collection\Relations $related */
            $related = $storage->createCollection(Relations::class);
            $related->setFromPost($formValues, $content);
            $content->setRelation($related);

            /** @var Collection\Taxonomy $taxonomies */
            $taxonomies = $storage->createCollection(Taxonomy::class);
            $taxonomies->setFromPost($formValues, $content);
            $content->setTaxonomy($taxonomies);

        } else {
            $content = $storage->getContentObject($contenttypeslug, [], false);
            $content->setFromPost($formValues, $contenttype);
        }

        $this->fixBlockFieldsForPreview($content);
        $this->fixHTMLFieldsForPreview($content);

        $liveEditor = $request->get('_live-editor-preview');
        if (!empty($liveEditor)) {
            $jsFile = (new JavaScript('js/ckeditor/ckeditor.js', 'bolt'))
                ->setPriority(1)
                ->setLate(false);
            $cssFile = (new Stylesheet('css/liveeditor.css', 'bolt'))
                ->setPriority(5)
                ->setLate(false);
            $snippet = (new Snippet())
                ->setCallback('<script>window.boltIsEditing = true;</script>')
                ->setLocation(Target::BEFORE_HEAD_JS);

            $this->app['asset.queue.snippet']->add($snippet);
            $this->app['asset.queue.file']->add($jsFile);
            $this->app['asset.queue.file']->add($cssFile);
        }

        // Then, select which template to use, based on our 'cascading templates rules'
        $template = $this->templateChooser()->record($content);

        // Make sure we can also access it as {{ page.title }} for pages, etc. We set these in the global scope,
        // So that they're also available in menu's and templates rendered by extensions.
        $globals = [
            'record'                      => $content,
            $contenttype['singular_slug'] => $content,
        ];

        return $this->render($template, [], $globals);
    }
911794
public function preview($entity, $id)
    {
        $modelString = 'Grafite\Cms\Models\\'.ucfirst($entity);

        if (!class_exists($modelString)) {
            $modelString = 'Grafite\Cms\Models\\'.ucfirst($entity).'s';
        }

        $model = new $modelString();
        $modelInstance = $model->find($id);

        $data = [
            $entity => $modelInstance,
        ];

        if (config('app.locale') != config('cms.default-language', Cms::config('cms.default-language'))) {
            if ($modelInstance->translation(config('app.locale'))) {
                $data = [
                    $entity => $modelInstance->translation(config('app.locale'))->data,
                ];
            }
        }

        $view = 'cms-frontend::'.$entity.'.show';

        if (!View::exists($view)) {
            $view = 'cms-frontend::'.$entity.'s.show';
        }

        if ($entity === 'page') {
            $view = 'cms-frontend::pages.'.$modelInstance->template;
        }

        if ($entity === 'blog') {
            $view = 'cms-frontend::blog.'.$modelInstance->template;
        }

        return view($view, $data);
    }
283307
public function editAction($id = null)
    {
        $request = $this->getRequest();
        // the key used to lookup the template
        $templateKey = 'edit';

        $id = $request->get($this->admin->getIdParameter());
        $existingObject = $this->admin->getObject($id);

        if (!$existingObject) {
            throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
        }

        $this->checkParentChildAssociation($request, $existingObject);

        $this->admin->checkAccess('edit', $existingObject);

        $preResponse = $this->preEdit($request, $existingObject);
        if (null !== $preResponse) {
            return $preResponse;
        }

        $this->admin->setSubject($existingObject);
        $objectId = $this->admin->getNormalizedIdentifier($existingObject);

        $form = $this->admin->getForm();

        if (!\is_array($fields = $form->all()) || 0 === \count($fields)) {
            throw new \RuntimeException(
                'No editable field defined. Did you forget to implement the "configureFormFields" method?'
            );
        }

        $form->setData($existingObject);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            $isFormValid = $form->isValid();

            // persist if the form was valid and if in preview mode the preview was approved
            if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
                $submittedObject = $form->getData();
                $this->admin->setSubject($submittedObject);

                try {
                    $existingObject = $this->admin->update($submittedObject);

                    if ($this->isXmlHttpRequest()) {
                        return $this->renderJson([
                            'result' => 'ok',
                            'objectId' => $objectId,
                            'objectName' => $this->escapeHtml($this->admin->toString($existingObject)),
                        ], 200, []);
                    }

                    $this->addFlash(
                        'sonata_flash_success',
                        $this->trans(
                            'flash_edit_success',
                            ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
                            'SonataAdminBundle'
                        )
                    );

                    // redirect to edit mode
                    return $this->redirectTo($existingObject);
                } catch (ModelManagerException $e) {
                    $this->handleModelManagerException($e);

                    $isFormValid = false;
                } catch (LockException $e) {
                    $this->addFlash('sonata_flash_error', $this->trans('flash_lock_error', [
                        '%name%' => $this->escapeHtml($this->admin->toString($existingObject)),
                        '%link_start%' => '<a href="'.$this->admin->generateObjectUrl('edit', $existingObject).'">',
                        '%link_end%' => '</a>',
                    ], 'SonataAdminBundle'));
                }
            }

            // show an error message if the form failed validation
            if (!$isFormValid) {
                if (!$this->isXmlHttpRequest()) {
                    $this->addFlash(
                        'sonata_flash_error',
                        $this->trans(
                            'flash_edit_error',
                            ['%name%' => $this->escapeHtml($this->admin->toString($existingObject))],
                            'SonataAdminBundle'
                        )
                    );
                }
            } elseif ($this->isPreviewRequested()) {
                // enable the preview template if the form was valid and preview was requested
                $templateKey = 'preview';
                $this->admin->getShow();
            }
        }

        $formView = $form->createView();
        // set the theme for the current Admin Form
        $this->setFormTheme($formView, $this->admin->getFormTheme());

        // NEXT_MAJOR: Remove this line and use commented line below it instead
        $template = $this->admin->getTemplate($templateKey);
        // $template = $this->templateRegistry->getTemplate($templateKey);

        return $this->renderWithExtraParams($template, [
            'action' => 'edit',
            'form' => $formView,
            'object' => $existingObject,
            'objectId' => $objectId,
        ], null);
    }
1185190
private function getPost($postid)
    {
        $post = $this->getDoctrine()->getManager()->getRepository('VeonikBlogBundle:AbstractPost')
            ->createQueryBuilder('p')
            ->addSelect('c')
            ->leftJoin('p.comments', 'c')
            ->where('p.id = :post_id')
            ->setParameters(array(
                'post_id' => $postid
            ))
            ->getQuery()
            ->getOneOrNullResult();

        if (!$post) {
            throw $this->createNotFoundException('Unable to locate Post');
        }

        return $post;
    }
1248207
public function previewAction(Request $request)
    {
        $tid = $request->get('tid');
        $teaserId = $request->get('teaser_id', null);
        $language = $request->get('language');
        $languages = $request->get('languages');
        $version = $request->get('version', null);
        $includeElements = (bool) $request->get('include_elements', false);
        $includeElementInstances = (bool) $request->get('include_element_instances', false);
        $includeTeasers = (bool) $request->get('include_teasers', false);
        $includeTeaserInstances = (bool) $request->get('include_teaser_instances', false);
        $recursive = (bool) $request->get('recursive', false);
        $onlyOffline = (bool) $request->get('only_offline', false);
        $onlyAsync = (bool) $request->get('only_async', false);

        if ($languages) {
            $languages = explode(',', $languages);
        } else {
            $languages = [$language];
        }

        $selector = $this->get('phlexible_element.publish.selector');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $selection = new Selection();
        foreach ($languages as $language) {
            $langSelection = $selector->select(
                $tid,
                $language,
                $version,
                $includeElements,
                $includeElementInstances,
                $includeTeasers,
                $includeTeaserInstances,
                $recursive,
                $onlyOffline,
                $onlyAsync
            );
            $selection->merge($langSelection);
        }

        $result = [];
        foreach ($selection->all() as $selectionItem) {
            if ($selectionItem->getTarget() instanceof TreeNodeInterface) {
                $id = $selectionItem->getTarget()->getId();
                $icon = $iconResolver->resolveTreeNode($selectionItem->getTarget(), $selectionItem->getLanguage());
            } else {
                $id = $selectionItem->getTarget()->getId();
                $icon = $iconResolver->resolveTeaser($selectionItem->getTarget(), $selectionItem->getLanguage());
            }

            $result[] = [
                'type' => $selectionItem->getTarget() instanceof TreeNodeInterface ? 'full_element' : 'part_element',
                'instance' => $selectionItem->isInstance(),
                'depth' => $selectionItem->getDepth(),
                'path' => $selectionItem->getPath(),
                'id' => $id,
                'eid' => $selectionItem->getTarget()->getTypeId(),
                'version' => $selectionItem->getVersion(),
                'language' => $selectionItem->getLanguage(),
                'title' => $selectionItem->getTitle(),
                'icon' => $icon,
                'action' => true,
            ];
        }

        return new JsonResponse(['preview' => $result]);
    }
156750
public function showBusinessPageByIdAction(Request $request, $entityId, $type)
    {
        $businessEntityHelper = $this->get('victoire_core.helper.queriable_business_entity_helper');
        $businessEntity = $businessEntityHelper->findById($type);
        $entity = $businessEntityHelper->getByBusinessEntityAndId($businessEntity, $entityId);

        $refClass = new \ReflectionClass($entity);

        $templateId = $this->get('victoire_business_page.business_page_helper')
            ->guessBestPatternIdForEntity($refClass, $entityId, $this->container->get('doctrine.orm.entity_manager'));

        $page = $this->get('victoire_page.page_helper')->findPageByParameters([
            'viewId'   => $templateId,
            'entityId' => $entityId,
            'locale'   => $request->getLocale(),
        ]);

        return $this->redirect(
            $this->generateUrl(
                'victoire_core_page_show',
                [
                    'url' => $page->getReference()->getUrl(),
                ]
            )
        );
    }
339845
public function viewItem()
    {
        $this->loadStandaloneMode();

		if (!$this->isXmlHttpRequest()) {
			throw new common_exception_BadRequest('wrong request mode');
		}

		$itemClass = $this->getCurrentClass();
		$item = $this->getCurrentInstance();

		$lang = null;
		if($this->hasRequestParameter('target_lang')){
			$lang = $this->getRequestParameter('target_lang');
		}

		$hiddenProperties = array(
			taoItems_models_classes_ItemsService::PROPERTY_ITEM_CONTENT
		);

		$properties = array();
		foreach($this->getClassService()->getClazzProperties($itemClass) as $property){
			if(in_array($property->getUri(), $hiddenProperties)){
				continue;
			}
			$range = $property->getRange();

			if(is_null($lang)){
				$propValues = $item->getPropertyValues($property);
			} else {
				$propContainer = $item->getPropertyValuesByLg($property, $lang);
				$propValues = $propContainer->getIterator();
			}
			foreach($propValues as $propValue){
				if($range->getUri() == OntologyRdfs::RDFS_LITERAL){
					$value = (string)$propValue;
				} else {
					$resource = new core_kernel_classes_Resource($propValue);
					$value = $resource->getLabel();
				}
				$properties[] = array(
					'name'	=> $property->getLabel(),
					'value'	=> $value
				);
			}
		}

		$previewData = $this->initPreview($item, $itemClass);
		if(count($previewData) == 0){
			$this->setData('preview', false);
			$this->setData('previewMsg', __('Not yet available'));
		}
		else{
			$this->setData('preview', true);
			$this->setData('instanceUri', tao_helpers_Uri::encode($item->getUri(), false));
			foreach($previewData as $key => $value){
				$this->setData($key, $value);
			}
		}

		$this->setData('uri', tao_helpers_Uri::encode($item->getUri()));
		$this->setData('classUri', tao_helpers_Uri::encode($itemClass->getUri()));

		$this->setData('label', $item->getLabel());
		$this->setData('itemProperties', $properties);
		$this->setView('view.tpl');
	}
1372775
public function preview($params)
    {
        $rst = $this->_request->post($this->_url . "message/mass/preview", $params);
        return $this->_client->rst($rst);
    }
274442
def preview(self, path=None, extra_context=None, publish=False):
        
        try:
            self.call_hook("preview", self)

            if path is None:
                path = 'index.html'

            # Detect files
            filepath, mimetype = self._resolve_path(path)

            # Serve dynamic
            if filepath and mimetype and mimetype in self.project.TEMPLATE_TYPES:
                context = self.get_context(publish)
                context.update({
                    "PATH": path,
                    "PREVIEW_SERVER": not publish,
                    "TIMESTAMP": int(time.time()),
                })
                if extra_context:
                    context.update(extra_context)

                rendered = render_template(path, **context)
                return Response(rendered, mimetype=mimetype)

            # Serve static
            if filepath:
                dir, filename = os.path.split(filepath)
                return send_from_directory(dir, filename)

        except Exception as e:
            ex_type, ex, tb = sys.exc_info()
            try:
                # Find template with name of error
                cls = e.__class__
                ex_type, ex, tb = sys.exc_info()

                context = self.project.DEFAULT_CONTEXT
                context.update({
                    'PATH': path,
                    'traceback': traceback.format_exception(ex_type, ex, tb),
                    'e': e,
                })
                if extra_context:
                    context.update(extra_context)

                try:
                    error_path = '_{0}.{1}.html'.format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)
                except TemplateNotFound:
                    # Find template without underscore prefix, @TODO remove in v1.1
                    error_path = '{0}.{1}.html'.format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)

                return Response(rendered, mimetype="text/html")
            except TemplateNotFound:
                # Otherwise raise old error
                reraise(ex_type, ex, tb)

        # Last ditch effort -- see if path has "index.html" underneath it
        if not path.endswith("index.html"):
            if not path.endswith("/"):
                path = "{0}/".format(path)
            path = "{0}{1}".format(path, "index.html")
            return self.preview(path)

        # It's a 404
        if path.endswith('/index.html'):
            path = path[:-11]
        rendered = render_template("404.html", PATH=path)
        return Response(rendered, status=404)
526151
public function preview($id = null)
    {
        $photo = $this->Photos->findPendingById($id)
            ->select(['id', 'album_id', 'filename'])
            ->contain([$this->Photos->Albums->getAlias() => ['fields' => ['id', 'title', 'slug']]])
            ->firstOrFail();

        $this->set(compact('photo'));
        $this->render('view');
    }
736124
public function postAction(Request $request)
    {
        $type = 'page';
        $language = $this->getLanguage($request);
        $action = $request->get('action');

        $this->checkActionParameterSecurity($action, $language);

        $document = $this->getDocumentManager()->create($type);
        $formType = $this->getMetadataFactory()->getMetadataForAlias($type)->getFormType();

        $this->persistDocument($request, $formType, $document, $language);
        $this->handleActionParameter($action, $document, $language);
        $this->getDocumentManager()->flush();

        $context = new Context();
        $context->setGroups(['defaultPage']);

        return $this->handleView($this->view($document)->setContext($context));
    }
518412
public function previewAction()
    {
        //wyszukiwanie wiadomości
        if (null === $mail = (new \Cms\Orm\CmsMailQuery)->findPk($this->id)) {
            $this->getResponse()->redirect('cmsAdmin', 'mail', 'index');
        }
        $this->view->message = $mail->message;
    }