Delete and Edit Pages

March 2016 ยท 4 minute read

1. Create Edit action in the pageBundle/Controller/AdminController

/**	   
 * Edit page	   
 * 
 * @Route("/edit/{id}/", name="PageBundle:Admin:edit")
 * @Template("PageBundle:Admin:edit.html.twig")
 */
		  
public function editAction($id, Request $request) {
	$em = $this		  
	->getDoctrine()		  
	->getManager();

	// Get page	  
	$page = $em		  
	->getRepository('PageBundle:Page')			  
	->findOneById($id);

	if ($page === null) {		  
		//Page doesn't exist			  
		throw $this->createNotFoundException();
	}

	// Check permissions		  
	$this->checkAccess('EDIT', $page);

	// Build form		  
	$form = $this->createForm(new PageForm(), $page);	  
	$form->handleRequest($request);

	if ($form->isValid()) {		  
		// Form has been posted and is valid – persist to database			  
		$em->persist($page);		  
		$em->flush();

		// Log alert message		  
		$this->alert(			  
			'success',			  
			$this->translate(				  
				'admin.edit.success',					  
				array('%name%' => $page->getName()),				  
				'PageBundle'				  
			)	  
		);

		// Redirect to self		  
		return $this->redirect(			  
			$this->generateUrl(			  
				'PageBundle:Admin:index'				  
			)		  
		);	  
	}

	// Render defined template with this data
	return array(  
		'page' => $page,  
		'form' => $form->createView(),	  
	);	  
}

2. Add Controls to the index.html.twig to make edit/delete controls etc on the index page

{% block controls %}
{%
	include 'AdminBundle:Utility:controls.html.twig' with {
		controls: [     
			{        
				class: 'create',      
				url: path('PageBundle:Admin:create'),     
				label: 'admin.create.title'|trans,   
				hasPermission: true     
			} 
		]
	}
%}
{% endblock controls %}

3. Add into PageBundle/Resources/translations: pages: translations

admin:
	index:  
		title: 'Pages'

pages:
	title: "%name%"
		create: "Create a new page under '%entity%'"

4. Create an edit.html.twig view in the page bundle

{% extends 'PageBundle:Admin:index.html.twig' %}
{% set domain = 'PageBundle' %}
{% trans_default_domain domain %}

{% block title -%}
	{{ 'admin.edit.title'|trans({'%name%': page.name}) }} {{ 'space.title_separator'|trans({}, 'GlobalBundle')|raw }}
{%- endblock title %}

{% block main %} 
	{{ form_start(form) }}
	{{ parent() }}
	{{ form_end(form) }}
{% endblock main %}

{% block header %}
	<h1>{{ 'admin.edit.title'|trans({'%name%': page.name}) }}</h1>
{% endblock header %}

{% block breadcrumbs %}
	{{ parent() }}   
	<a href="{{ path('PageBundle:Admin:edit', {id: page.id}) }}">{{ 'admin.edit.title'|trans({'%name%': page.name}) }}</a>
{% endblock breadcrumbs %}

{% block content %} 
	{{ form_widget(form) }}
{% endblock content %}

{% block controls %}
{%
	include 'AdminBundle:Utility:controls.html.twig' with {
		controls: [       
			{             
				class: 'save success',            
				label: 'admin.edit.submit'|trans         
			},{            
				class: 'delete danger',              
				url: path('PageBundle:Admin:delete', {id: page.id}),          
				label: 'delete entity'|trans({'%name%': page.name}, 'GlobalBundle'),             
				hasPermission: is_granted('DELETE', page)          
			},{              
				class: 'back',           
				url: path('PageBundle:Admin:index'),             
				label: 'admin.back.index'|trans,             
				hasPermission: is\_granted('VIEW', get\_entity_class('PageBundle:Page'))    
			} 
		]
	}
%}
{% endblock controls %}

5. Add into PageBundle/Resources/translations: edit: translations

edit:  
title: 'Edit page %name%' 
title_shorts: 'Edit' 
submit: 'Update page' 
success: "Page '%name%' has been updated."

6. Add alerts block in AdminBundle/Resources/views/layout.html.twig

{% block alerts %}
{%
	include 'GlobalBundle:Utility:alerts.html.twig' with {    
		classes: ['error', 'warning', 'success', 'info'] 
	}
%}
{% endblock alerts %}

7. Create a template partial in GlobalBundle/views/Utility/ for alerts.html.twig so it can be used anywhere in the app.

{% set alerts = [] %} 
{% if classes is not iterable %}
{% set classes = [classes] %}
{% endif %}
{% for class in classes %}
{% set alertSet = app.session.flashbag.get(class) %}
{% if alertSet is not empty %}
{% set alerts = alerts|merge({(class): alertSet}) %}
{% endif %}
{% endfor %}
{% if alerts is not empty %}
	<div class="alerts">
{% for class, alertSet in alerts %}
	  
	  <ul class="{{ class }}">
{% for alert in alertSet %}
	    
	    <li>
{{ alert|raw }}
	    </li>
{% endfor %}
	  </ul> 
	  
{% endfor %}
	</div>  
{% endif %}

8. Add Delete page Function into PageBundle/Controller/AdminController.php

/**
 * Delete page
 *
 * @Route("/delete/{id}/", name="PageBundle:Admin:delete")
 * @Template("PageBundle:Admin:delete.html.twig")
 */
 public function deleteAction($id, Request $request) {
 	$em = $this
 	->getDoctrine()
 	->getManager();

    //Get page item
    $page = $em
    ->getRepository('PageBundle:Page')
    ->findOneById($id);

    if ($page === null) {
    	//Page doesn't exist
    	throw $this->creatNotFoundException();
    }

    //Check permissions
    $this->checkAccess('DELETE', $page);

    $form = $this
    ->createFormBuilder($page)
    ->getForm();
    $form->handleRequest($request);

    if ($form->isSubmitted()) {
    	//Delete empty
    	$em->remove($page);
    	$em->flush();

    	//Log alert message
	    $this->alert(
	    	'success',
	    	$this->translate(
	    		'admin.delete.success',
	    		array('%name%' => $page->getName()),
	    		'PageBundle'
	    	)
	    );

	    //Redirect to index
	    return $this->redirect(
	    	$this->generateUrl(
	    		'PageBundle:Admin:index'
	    	)
	    );

	}

	return array(
		'page' => $page,
		'form' => $form->createView()
	);
}

9. Create a template partial in GlobalBundle/views/Utility/ for confirm.html.twigconfirm

{% trans_default_domain 'GlobalBundle' %}
{% if class is not defined %}
{% set class = " %}
{% endif %}
<div class="confirm {{ class }}"> 
  <p>({ 'confirm action message'|trans({'%action%': action|lower, '%entity%': entity|lower, '%name%': name })</p>
</div>  

10. Create a PageBundle/Resources/views/delete.html.twig view in the page bundle

{% extends 'PageBundle:Admin:index.html.twig' %}
{% set domain = 'PageBundle' %}
{% trans_default_domain domain %}

{% block title -%}
	{{ 'admin.delete.title'|trans({'%name%': page.name}) }} {{ 'space.title_separator'|trans({}, 'GlobalBundle')|raw }}
{%- endblock title %}

{% block main %}
	{{ form_start(form) }}
	{{ parent() }}
	{{ form_end(form) }}
{% endblock main %}

{% block header %}
	<h1>{{ 'admin.delete.title'|trans({'%name%': page.name}) }}</h1>
{% endblock header %}

{% block breadcrumbs %}
	{{ parent() }}
	<a href="{{ path('PageBundle:Admin:delete', {id: page.id}) }}">{{ 'admin.delete.title'|trans({'%name%': page.name}) }}</a>
{% endblock breadcrumbs %}

{% block content %}
	{{ form_widget(form) }}
{% endblock content %}

{% block controls %}
{
	include 'AdminBundle:Utility:controls.html.twig' with {
		controls: [
			{
				class: 'delete danger',
				label: 'admin.delete.submit'|trans
			},{
				class: 'back',
				url: path('PageBundle:Admin:index'),
				label: 'admin.back.index'|trans,
			}
		]
	}
%}
{% endblock controls %}

11. Add into PageBundle/Resources/translations: delete & back: translations

delete:
	title: 'Delete page %name%'
	submit: 'Delete page'
	success: "Page '%name%' has been deleted."

back:
	index: 'Return to index'
	edit: 'Return to edit page'

12. Add the side bar control links {% block controls %} in PageBundle/Resources/views/Admin/index.html.twig

{
	include 'AdminBundle:Utility:controls.html.twig' with {
		controls: [
			{
				class: 'create',
				url: path('PageBundle:Admin:create'),
				label: 'admin.create.title'|trans,
				hasPermission: true
			}
		]
	}
%}